branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/2.x | <repo_name>sparkle-project/Sparkle<file_sep>/Documentation/Design Practices.md
# Design Practices
## XPC Services
XPC services in Sparkle are all optional, so the code involved in the services needs to be usable directly from the framework as well. For this to work well, if the class used in the XPC service takes a delegate, it must not be weakly referenced, so the retain cycle will have to be broken explicitly (via an explicit added invalidate method). dealloc also must not be implemented (do cleanup in custom invalidate method). As one may tell, two of the services are simply proxies (InstallerConnection, InstallerStatus) -- we now recommend most developers to set up a temporary exception with their bundle ID rather than use these two services.
The protocols used in XPC services must also not adopt other protocols (i.e, one protocol inheriting from another protocol). This is because the XPC protocol decoder on older supported systems doesn't properly handle this case, and won't be able to find that methods exist on a class.
## Singletons
Singletons and other global mutable variables have been either removed entirely or completely avoided with an exception to backwards compatibility. They have no place in a well architectured framework.
`SPUUpdater` doesn't maintain singleton instances and can now be properly deconstructed. Note because a caller is not expected to explicitly invalidate an updater, this means that the updater needs to avoid geting into a retain cycle. Intermediate clasess were created for the update cycle and schedule timer to avoid just this.
One may argue that we shouldn't allow multiple live updaters running at the same bundle simutaneously, but I disagree and I think that is missing the point. It also does not account for updaters running external to the process. For example, it may be perfectly reasonable to start an update from `sparkle-cli` that defers the installation until quit, and have the application that is being updated be able to resume that installation and relaunch immediately.
The original `SUUpdater` may have also been created to assist plug-ins and other non-app bundles. My advice there is in order to be truely safe, you must not inject a framework like Sparkle into the host application anyway. An external tool that is bundled like `sparkle-cli` may be more appropriate to use here.
## Extensibility
Sparkle 2.0 does not support subclassing classes internal (not exported) to Sparkle anymore. Doing so would be almost impossible to maintain into the future. Subclassing in general has been banned. Composition is prefered everywhere, even amongst the internal update drivers which were rewritten to follow a protocol oriented approach. The reason why composition is preferred is because it's easier to follow the flow of logic.
I hope the user driver API gives enough extensibility without someone wanting to create another fork.
## Delegation
Newer classes, other than assisting backwards compatibility, that support delegation don't pass the delegator around anymore. Doing so has some [bad consequences](https://zgcoder.net/ramblings/avoid-passing-the-delegator) and makes code hard to maintain.
Optional delegate methods that have return types need to be optional or have known default values for primitive types.
You may notice that the delegate and user driver are not accessible as properties from `SPUUpdater`. This is intentional. The methods that belong to these types aren't meaningful to any caller except from internal classes.
## Decoupling
Two software components should not directly know about each other. Preferrably they wouldn't know about each other at all, but if they must, they can use the delegation pattern with a declared protocol.
See `Documentation/graph-of-sparkle.png` for a graph of how the code looks like currently. This was generated via [objc_dep](https://github.com/nst/objc_dep) (great tool). Note that there are no red edges which would mean that two nodes know of each other.
## Attributes & Code Size
Instance variables and instance variable access should be used for private members (declared in `@implementation` block) whenever possible over properties. Preferring instance variables over properties for internal usage can significantly reduce code size. Instance variables should also be ordered by having the larger sized data members declared first.
`SPU_OBJC_DIRECT_MEMBERS` should be used for any internal class in Sparkle and `SPU_OBJC_DIRECT` should be used for any other internal methods to Sparkle that doesn't need to utilize the Obj-C runtime to reduce code size. Note these attributes should not be used for *any* class or method that is exported to the developer (this includes private headers / APIs we carefully decided to expose too). For internal methods and classes that are also used by our Swift tools or unit tests, we may not expose them as direct specifically when building for those targets.
`nonatomic` should really be used wherever possible with regards to obj-c properties (`atomic` is a bad default). `readonly` should be used wherever possible as well, which also implies that only ivar access should be used in initializers. `NS_ASSUME_NONNULL_BEGIN` and `NS_ASSUME_NONNULL_END` should be used around new headers whenever possible. AppKit prevention guards should be used for any non-UI class whenever possible.
Sparkle has several feature flags in ConfigCommon.xcconfig (e.g. `SPARKLE_BUILD_LEGACY_SUUPDATER`, `SPARKLE_BUILD_LEGACY_DSA_SUPPORT`, `SPARKLE_BUILD_UI_BITS`, etc). This allows disabling any combination of these features and building Sparkle with a more minimal feature set. These flags (with the exception for stripping UI bits, localizations, or XPC Services) are for disabling features that are legacy or not recommended to use for most applications. Note when altering these flags, `OTHER_SWIFT_FLAGS_COMMON` may need to be updated appropriately too.
<file_sep>/generate_appcast/ArchiveItem.swift
//
// Created by Kornel on 22/12/2016.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
import Foundation
import UniformTypeIdentifiers
struct UpdateBranch: Hashable {
let minimumSystemVersion: String?
let maximumSystemVersion: String?
let minimumAutoupdateVersion: String?
let channel: String?
}
class DeltaUpdate {
let fromVersion: String
let archivePath: URL
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
var dsaSignature: String?
#endif
var edSignature: String?
let sparkleExecutableFileSize: Int?
let sparkleLocales: String?
init(fromVersion: String, archivePath: URL, sparkleExecutableFileSize: Int?, sparkleLocales: String?) {
self.archivePath = archivePath
self.fromVersion = fromVersion
self.sparkleExecutableFileSize = sparkleExecutableFileSize
self.sparkleLocales = sparkleLocales
}
var fileSize: Int64 {
let archiveFileAttributes = try! FileManager.default.attributesOfItem(atPath: self.archivePath.path)
return (archiveFileAttributes[.size] as! NSNumber).int64Value
}
class func create(from: ArchiveItem, to: ArchiveItem, deltaVersion: SUBinaryDeltaMajorVersion, deltaCompressionMode: SPUDeltaCompressionMode, deltaCompressionLevel: UInt8, archivePath: URL) throws -> DeltaUpdate {
var createDiffError: NSError?
if !createBinaryDelta(from.appPath.path, to.appPath.path, archivePath.path, deltaVersion, deltaCompressionMode, deltaCompressionLevel, false, &createDiffError) {
throw createDiffError!
}
// Ensure applying the diff also succeeds
let fileManager = FileManager.default
let tempApplyToPath = to.appPath.deletingLastPathComponent().appendingPathComponent(".temp_" + to.appPath.lastPathComponent)
let _ = try? fileManager.removeItem(at: tempApplyToPath)
var applyDiffError: NSError?
if !applyBinaryDelta(from.appPath.path, tempApplyToPath.path, archivePath.path, false, { _ in
}, &applyDiffError) {
let _ = try? fileManager.removeItem(at: archivePath)
throw applyDiffError!
}
let _ = try? fileManager.removeItem(at: tempApplyToPath)
return DeltaUpdate(fromVersion: from.version, archivePath: archivePath, sparkleExecutableFileSize: from.sparkleExecutableFileSize, sparkleLocales: from.sparkleLocales)
}
}
class ArchiveItem: CustomStringConvertible {
let version: String
// swiftlint:disable identifier_name
let _shortVersion: String?
let minimumSystemVersion: String
let frameworkVersion: String?
let sparkleExecutableFileSize: Int?
let sparkleLocales: String?
let archivePath: URL
let appPath: URL
let feedURL: URL?
let publicEdKey: Data?
let supportsDSA: Bool
let archiveFileAttributes: [FileAttributeKey: Any]
var deltas: [DeltaUpdate]
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
var dsaSignature: String?
#endif
var edSignature: String?
var downloadUrlPrefix: URL?
var releaseNotesURLPrefix: URL?
var signingError: Error?
init(version: String, shortVersion: String?, feedURL: URL?, minimumSystemVersion: String?, frameworkVersion: String?, sparkleExecutableFileSize: Int?, sparkleLocales: String?, publicEdKey: String?, supportsDSA: Bool, appPath: URL, archivePath: URL) throws {
self.version = version
self._shortVersion = shortVersion
self.feedURL = feedURL
self.minimumSystemVersion = minimumSystemVersion ?? "10.13"
self.frameworkVersion = frameworkVersion
self.sparkleExecutableFileSize = sparkleExecutableFileSize
self.sparkleLocales = sparkleLocales
self.archivePath = archivePath
self.appPath = appPath
self.supportsDSA = supportsDSA
if let publicEdKey = publicEdKey {
self.publicEdKey = Data(base64Encoded: publicEdKey)
} else {
self.publicEdKey = nil
}
let path = (self.archivePath.path as NSString).resolvingSymlinksInPath
self.archiveFileAttributes = try FileManager.default.attributesOfItem(atPath: path)
self.deltas = []
}
convenience init(fromArchive archivePath: URL, unarchivedDir: URL, validateBundle: Bool, disableNestedCodeCheck: Bool) throws {
let resourceKeys: [URLResourceKey]
if #available(macOS 11, *) {
resourceKeys = [.contentTypeKey]
} else {
resourceKeys = [.typeIdentifierKey]
}
let items = try FileManager.default.contentsOfDirectory(at: unarchivedDir, includingPropertiesForKeys: resourceKeys, options: .skipsHiddenFiles)
let bundles = items.filter({
if let resourceValues = try? $0.resourceValues(forKeys: Set(resourceKeys)) {
if #available(macOS 11, *) {
return resourceValues.contentType!.conforms(to: .bundle)
} else {
return UTTypeConformsTo(resourceValues.typeIdentifier! as CFString, kUTTypeBundle)
}
} else {
return false
}
})
if bundles.count > 0 {
if bundles.count > 1 {
throw makeError(code: .unarchivingError, "Too many bundles in \(unarchivedDir.path) \(bundles)")
}
let appPath = bundles[0]
// If requested to validate the bundle, ensure it is properly signed
if validateBundle && SUCodeSigningVerifier.bundle(atURLIsCodeSigned: appPath) {
try SUCodeSigningVerifier.codeSignatureIsValid(atBundleURL: appPath, checkNestedCode: !disableNestedCodeCheck)
}
guard let infoPlist = NSDictionary(contentsOf: appPath.appendingPathComponent("Contents/Info.plist")) else {
throw makeError(code: .unarchivingError, "No plist \(appPath.path)")
}
guard let version = infoPlist[kCFBundleVersionKey!] as? String else {
throw makeError(code: .unarchivingError, "No Version \(kCFBundleVersionKey as String? ?? "missing kCFBundleVersionKey") \(appPath)")
}
let shortVersion = infoPlist["CFBundleShortVersionString"] as? String
let publicEdKey = infoPlist[SUPublicEDKeyKey] as? String
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
let supportsDSA = infoPlist[SUPublicDSAKeyKey] != nil || infoPlist[SUPublicDSAKeyFileKey] != nil
#else
let supportsDSA = false
#endif
var feedURL: URL?
if let feedURLStr = infoPlist["SUFeedURL"] as? String {
feedURL = URL(string: feedURLStr)
if feedURL?.pathExtension == "php" {
feedURL = feedURL!.deletingLastPathComponent()
feedURL = feedURL!.appendingPathComponent("appcast.xml")
}
}
var frameworkVersion: String? = nil
let sparkleExecutableFileSize: Int?
let sparkleLocales: String?
do {
let canonicalFrameworksURL = appPath.appendingPathComponent("Contents/Frameworks/Sparkle.framework")
let frameworksURL: URL?
let usingLegacySparkleCore: Bool
if !FileManager.default.fileExists(atPath: canonicalFrameworksURL.path) {
// Try legacy SparkleCore framework that was shipping in early 2.0 betas
let sparkleCoreFrameworksURL = appPath.appendingPathComponent("Contents/Frameworks/SparkleCore.framework")
if FileManager.default.fileExists(atPath: sparkleCoreFrameworksURL.path) {
frameworksURL = sparkleCoreFrameworksURL
usingLegacySparkleCore = true
} else {
frameworksURL = nil
usingLegacySparkleCore = false
}
} else {
frameworksURL = canonicalFrameworksURL
usingLegacySparkleCore = false
}
if let frameworksURL = frameworksURL {
let resourcesURL = frameworksURL.appendingPathComponent("Resources").resolvingSymlinksInPath()
if let frameworkInfoPlist = NSDictionary(contentsOf: resourcesURL.appendingPathComponent("Info.plist")) {
frameworkVersion = frameworkInfoPlist[kCFBundleVersionKey as String] as? String
}
let frameworkExecutableURL = frameworksURL.appendingPathComponent(!usingLegacySparkleCore ? "Sparkle" : "SparkleCore").resolvingSymlinksInPath()
do {
let resourceValues = try frameworkExecutableURL.resourceValues(forKeys: [.fileSizeKey])
sparkleExecutableFileSize = resourceValues.fileSize
} catch {
sparkleExecutableFileSize = nil
}
do {
let fileManager = FileManager.default
let resourcesDirectoryContents = try fileManager.contentsOfDirectory(atPath: resourcesURL.path)
let localeExtension = ".lproj"
let localeExtensionCount = localeExtension.count
let maxLocalesToProcess = 7
var localesPresent: [String] = []
var localeIndex = 0
for filename in resourcesDirectoryContents {
guard filename.hasSuffix(localeExtension) else {
continue
}
// English and Base directories are the least likely to be stripped,
// so let's not bother recording them.
guard filename != "en" && filename != "Base" else {
continue
}
let locale = String(filename.dropLast(localeExtensionCount))
localesPresent.append(locale)
localeIndex += 1
if localeIndex >= maxLocalesToProcess {
break
}
}
if localesPresent.count > 0 {
sparkleLocales = localesPresent.joined(separator: ",")
} else {
sparkleLocales = nil
}
} catch {
sparkleLocales = nil
}
} else {
sparkleExecutableFileSize = nil
sparkleLocales = nil
}
}
try self.init(version: version,
shortVersion: shortVersion,
feedURL: feedURL,
minimumSystemVersion: infoPlist["LSMinimumSystemVersion"] as? String,
frameworkVersion: frameworkVersion,
sparkleExecutableFileSize: sparkleExecutableFileSize,
sparkleLocales: sparkleLocales,
publicEdKey: publicEdKey,
supportsDSA: supportsDSA,
appPath: appPath,
archivePath: archivePath)
} else {
throw makeError(code: .missingUpdateError, "No supported items in \(unarchivedDir) \(items) [note: only .app bundles are supported]")
}
}
var shortVersion: String {
return self._shortVersion ?? self.version
}
var description: String {
return "\(self.archivePath) \(self.version)"
}
var archiveURL: URL? {
guard let escapedFilename = self.archivePath.lastPathComponent.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
return nil
}
if let downloadUrlPrefix = self.downloadUrlPrefix {
// if a download url prefix was given use this one
return URL(string: escapedFilename, relativeTo: downloadUrlPrefix)
} else if let relativeFeedUrl = self.feedURL {
return URL(string: escapedFilename, relativeTo: relativeFeedUrl)
}
return URL(string: escapedFilename)
}
var pubDate: String {
let date = self.archiveFileAttributes[.creationDate] as! Date
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss ZZ"
return formatter.string(from: date)
}
var fileSize: Int64 {
return (self.archiveFileAttributes[.size] as! NSNumber).int64Value
}
private var releaseNotesPath: URL? {
var basename = self.archivePath.deletingPathExtension()
if basename.pathExtension == "tar" { // tar.gz
basename = basename.deletingPathExtension()
}
let htmlReleaseNotes = basename.appendingPathExtension("html")
if FileManager.default.fileExists(atPath: htmlReleaseNotes.path) {
return htmlReleaseNotes
}
let plainTextReleaseNotes = basename.appendingPathExtension("txt")
if FileManager.default.fileExists(atPath: plainTextReleaseNotes.path) {
return plainTextReleaseNotes
}
return nil
}
private func getReleaseNotesAsFragment(_ path: URL, _ embedReleaseNotesAlways: Bool) -> (content: String, format: String)? {
guard let content = try? String(contentsOf: path) else {
return nil
}
let format = (path.pathExtension.caseInsensitiveCompare("txt") == .orderedSame) ? "plain-text" : "html"
if embedReleaseNotesAlways {
return (content, format)
} else if path.pathExtension.caseInsensitiveCompare("html") == .orderedSame && !content.localizedCaseInsensitiveContains("<!DOCTYPE") && !content.localizedCaseInsensitiveContains("<body") {
// HTML fragments should always be embedded
return (content, format)
} else {
return nil
}
}
func releaseNotesContent(embedReleaseNotesAlways: Bool) -> (content: String, format: String)? {
if let path = self.releaseNotesPath {
return self.getReleaseNotesAsFragment(path, embedReleaseNotesAlways)
}
return nil
}
func releaseNotesURL(embedReleaseNotesAlways: Bool) -> URL? {
guard let path = self.releaseNotesPath else {
return nil
}
// The file is already used as inline description
if self.getReleaseNotesAsFragment(path, embedReleaseNotesAlways) != nil {
return nil
}
return self.releaseNoteURL(for: path.lastPathComponent)
}
func releaseNoteURL(for unescapedFilename: String) -> URL? {
guard let escapedFilename = unescapedFilename.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
return nil
}
if let releaseNotesURLPrefix = self.releaseNotesURLPrefix {
// If a URL prefix for release notes was passed on the commandline, use it
return URL(string: escapedFilename, relativeTo: releaseNotesURLPrefix)
} else if let relativeURL = self.feedURL {
return URL(string: escapedFilename, relativeTo: relativeURL)
} else {
return URL(string: escapedFilename)
}
}
func localizedReleaseNotes() -> [(String, URL)] {
var basename = archivePath.deletingPathExtension()
if basename.pathExtension == "tar" {
basename = basename.deletingPathExtension()
}
var localizedReleaseNotes = [(String, URL)]()
for languageCode in Locale.isoLanguageCodes {
let baseLocalizedReleaseNoteURL = basename
.appendingPathExtension(languageCode)
let htmlLocalizedReleaseNoteURL = baseLocalizedReleaseNoteURL.appendingPathExtension("html")
let plainTextLocalizedReleaseNoteURL = baseLocalizedReleaseNoteURL.appendingPathExtension("txt")
let localizedReleaseNoteURL: URL?
if (try? htmlLocalizedReleaseNoteURL.checkResourceIsReachable()) ?? false {
localizedReleaseNoteURL = htmlLocalizedReleaseNoteURL
} else if (try? plainTextLocalizedReleaseNoteURL.checkResourceIsReachable()) ?? false {
localizedReleaseNoteURL = plainTextLocalizedReleaseNoteURL
} else {
localizedReleaseNoteURL = nil
}
if let localizedReleaseNoteURL = localizedReleaseNoteURL,
let localizedReleaseNoteRemoteURL = self.releaseNoteURL(for: localizedReleaseNoteURL.lastPathComponent)
{
localizedReleaseNotes.append((languageCode, localizedReleaseNoteRemoteURL))
}
}
return localizedReleaseNotes
}
let mimeType = "application/octet-stream"
}
<file_sep>/Package.swift
// swift-tools-version:5.3
import PackageDescription
// Version is technically not required here, SPM doesn't check
let version = "2.5.0-beta.1"
// Tag is required to point towards the right asset. SPM requires the tag to follow semantic versioning to be able to resolve it.
let tag = "2.5.0-beta.1"
let checksum = "cfd39886db2d1c9b84e23e5127fad0a41f216e40af97fa7ff063feb0211b6e61"
let url = "https://github.com/sparkle-project/Sparkle/releases/download/\(tag)/Sparkle-for-Swift-Package-Manager.zip"
let package = Package(
name: "Sparkle",
platforms: [.macOS(.v10_11)],
products: [
.library(
name: "Sparkle",
targets: ["Sparkle"])
],
targets: [
.binaryTarget(
name: "Sparkle",
url: url,
checksum: checksum
)
]
)
<file_sep>/Tests/SUUpdateValidatorTest.swift
//
// SUUpdateValidatorTest.swift
// Sparkle
//
// Created by <NAME> on 2020-06-13.
// Copyright © 2020 Sparkle Project. All rights reserved.
//
import Foundation
import XCTest
class SUUpdateValidatorTest: XCTestCase {
enum BundleConfig: String, CaseIterable, Equatable {
case none = "None"
case dsaOnly = "DSAOnly"
case edOnly = "EDOnly"
case both = "Both"
case codeSignedOnly = "CodeSignedOnly"
case codeSignedBoth = "CodeSignedBoth"
case codeSignedOnlyNew = "CodeSignedOnlyNew"
case codeSignedBothNew = "CodeSignedBothNew"
case codeSignedOldED = "CodeSignedOldED"
case codeSignedInvalidOnly = "CodeSignedInvalidOnly"
case codeSignedInvalid = "CodeSignedInvalid"
var hasAnyKeys: Bool {
switch self {
case .none, .codeSignedOnly, .codeSignedOnlyNew, .codeSignedInvalidOnly:
return false
case .edOnly, .both, .codeSignedBoth, .codeSignedBothNew, .codeSignedOldED, .codeSignedInvalid:
return true
case .dsaOnly:
return true
}
}
}
struct SignatureConfig: CaseIterable, Equatable, CustomDebugStringConvertible {
enum State: CaseIterable, Equatable {
case none, invalid, invalidFormat, valid
}
var ed: State
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
var dsa: State
#endif
static let allCases: [SignatureConfig] = State.allCases.flatMap { dsaState in
State.allCases.map { edState in
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
SignatureConfig(ed: edState, dsa: dsaState)
#else
SignatureConfig(ed: edState)
#endif
}
}
var debugDescription: String {
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
return "(ed: \(self.ed), dsa: \(self.dsa))"
#else
return "(ed: \(self.ed))"
#endif
}
}
func bundle(_ config: BundleConfig) -> Bundle {
let testBundle = Bundle(for: SUUpdateValidatorTest.self)
let configBundleURL = testBundle.url(forResource: config.rawValue, withExtension: "bundle", subdirectory: "SUUpdateValidatorTest")!
return Bundle(url: configBundleURL)!
}
func signatures(_ config: SignatureConfig) -> SUSignatures {
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
let dsaSig: String?
switch config.dsa {
case .none: dsaSig = nil
case .invalid: dsaSig = "<KEY>
// Use some invalid base64 strings
case .invalidFormat: dsaSig = "%%<KEY>
case .valid: dsaSig = "<KEY>
}
#endif
let edSig: String?
switch config.ed {
case .none: edSig = nil
case .invalid: edSig = "wTcpXC<KEY>
// Use some invalid base64 strings
case .invalidFormat: edSig = "%%<KEY>
case .valid: edSig = "EIawm2YkDZ2gBfkEMF2+1VuuTeXnCGZOdnMdVgPP<KEY>
}
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
return SUSignatures(ed: edSig, dsa: dsaSig)
#else
return SUSignatures(ed: edSig)
#endif
}
var signedTestFilePath: String {
let testBundle = Bundle(for: SUUpdateValidatorTest.self)
return testBundle.path(forResource: "signed-test-file", ofType: "txt")!
}
func testPrevalidation(bundle bundleConfig: BundleConfig, signatures signatureConfig: SignatureConfig, expectedResult: Bool, line: UInt = #line) {
let host = SUHost(bundle: self.bundle(bundleConfig))
let signatures = self.signatures(signatureConfig)
let validator = SUUpdateValidator(downloadPath: self.signedTestFilePath, signatures: signatures, host: host)
let result = (try? validator.validateDownloadPath()) != nil
XCTAssertEqual(result, expectedResult, "bundle: \(bundleConfig), signatures: \(signatureConfig)", line: line)
}
func testPrevalidation() {
for signatureConfig in SignatureConfig.allCases {
testPrevalidation(bundle: .none, signatures: signatureConfig, expectedResult: false)
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
testPrevalidation(bundle: .dsaOnly, signatures: signatureConfig, expectedResult: signatureConfig.dsa == .valid)
#endif
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
testPrevalidation(bundle: .edOnly, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid && signatureConfig.dsa != .invalidFormat)
#else
testPrevalidation(bundle: .edOnly, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid)
#endif
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
testPrevalidation(bundle: .both, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid && signatureConfig.dsa != .invalidFormat)
#else
testPrevalidation(bundle: .both, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid)
#endif
}
}
func testPostValidation(oldBundle oldBundleConfig: BundleConfig, newBundle newBundleConfig: BundleConfig, signatures signatureConfig: SignatureConfig, expectedResult: Bool, line: UInt = #line) {
let oldBundle = self.bundle(oldBundleConfig)
let host = SUHost(bundle: oldBundle)
let signatures = self.signatures(signatureConfig)
let validator = SUUpdateValidator(downloadPath: self.signedTestFilePath, signatures: signatures, host: host)
let updateDirectory = temporaryDirectory("SUUpdateValidatorTest")!
defer { try! FileManager.default.removeItem(atPath: updateDirectory) }
let newBundle = self.bundle(newBundleConfig)
try! FileManager.default.copyItem(at: newBundle.bundleURL, to: URL(fileURLWithPath: updateDirectory).appendingPathComponent(oldBundle.bundleURL.lastPathComponent))
let result = (try? validator.validate(withUpdateDirectory: updateDirectory)) != nil
XCTAssertEqual(result, expectedResult, "oldBundle: \(oldBundleConfig), newBundle: \(newBundleConfig), signatures: \(signatureConfig)", line: line)
}
func testPostValidation(bundle bundleConfig: BundleConfig, signatures signatureConfig: SignatureConfig, expectedResult: Bool, line: UInt = #line) {
testPostValidation(oldBundle: bundleConfig, newBundle: bundleConfig, signatures: signatureConfig, expectedResult: expectedResult, line: line)
}
func testPostValidationWithoutCodeSigning() {
for signatureConfig in SignatureConfig.allCases {
testPostValidation(bundle: .none, signatures: signatureConfig, expectedResult: false)
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
testPostValidation(bundle: .dsaOnly, signatures: signatureConfig, expectedResult: signatureConfig.dsa == .valid)
#endif
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
testPostValidation(bundle: .edOnly, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid && signatureConfig.dsa != .invalidFormat)
#else
testPostValidation(bundle: .edOnly, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid)
#endif
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
testPostValidation(bundle: .both, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid && signatureConfig.dsa != .invalidFormat)
#else
testPostValidation(bundle: .both, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid)
#endif
}
}
func testPostValidationWithCodeSigning() {
for signatureConfig in SignatureConfig.allCases {
testPostValidation(bundle: .codeSignedOnly, signatures: signatureConfig, expectedResult: true)
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
testPostValidation(bundle: .codeSignedBoth, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid && signatureConfig.dsa != .invalidFormat)
#else
testPostValidation(bundle: .codeSignedBoth, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid)
#endif
testPostValidation(bundle: .codeSignedInvalidOnly, signatures: signatureConfig, expectedResult: false)
testPostValidation(bundle: .codeSignedInvalid, signatures: signatureConfig, expectedResult: false)
}
}
func testPostValidationWithKeyRemoval() {
for bundleConfig in BundleConfig.allCases {
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
testPostValidation(oldBundle: .dsaOnly, newBundle: bundleConfig, signatures: SignatureConfig(ed: .valid, dsa: .valid), expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid)
#else
testPostValidation(oldBundle: .dsaOnly, newBundle: bundleConfig, signatures: SignatureConfig(ed: .valid), expectedResult: false)
#endif
do {
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
let signatureConfig = SignatureConfig(ed: .valid, dsa: .valid)
#else
let signatureConfig = SignatureConfig(ed: .valid)
#endif
testPostValidation(oldBundle: .edOnly, newBundle: bundleConfig, signatures: signatureConfig, expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid)
}
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
testPostValidation(oldBundle: .both, newBundle: bundleConfig, signatures: SignatureConfig(ed: .valid, dsa: .valid), expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid)
#else
testPostValidation(oldBundle: .both, newBundle: bundleConfig, signatures: SignatureConfig(ed: .valid), expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid)
#endif
do {
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
let signatureConfig = SignatureConfig(ed: .valid, dsa: .valid)
#else
let signatureConfig = SignatureConfig(ed: .valid)
#endif
testPostValidation(oldBundle: .codeSignedBoth, newBundle: bundleConfig, signatures: signatureConfig, expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid)
}
}
}
func testPostValidationWithKeyRotation() {
for signatureConfig in SignatureConfig.allCases {
#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT
let signatureIsValid = (signatureConfig.ed == .valid && signatureConfig.dsa != .invalidFormat)
#else
let signatureIsValid = (signatureConfig.ed == .valid)
#endif
// It's okay to add DSA keys or add code signing.
testPostValidation(oldBundle: .codeSignedOnly, newBundle: .codeSignedBoth, signatures: signatureConfig, expectedResult: signatureIsValid)
testPostValidation(oldBundle: .both, newBundle: .codeSignedBoth, signatures: signatureConfig, expectedResult: signatureIsValid)
// If you want to change your code signing, you have to be using both forms of auth.
testPostValidation(oldBundle: .codeSignedOnly, newBundle: .codeSignedOnlyNew, signatures: signatureConfig, expectedResult: false)
testPostValidation(oldBundle: .codeSignedBoth, newBundle: .codeSignedOnlyNew, signatures: signatureConfig, expectedResult: false)
testPostValidation(oldBundle: .codeSignedOnly, newBundle: .codeSignedBothNew, signatures: signatureConfig, expectedResult: false)
testPostValidation(oldBundle: .codeSignedBoth, newBundle: .codeSignedBothNew, signatures: signatureConfig, expectedResult: signatureIsValid)
// If you want to change your keys, you have to be using both forms of auth.
testPostValidation(oldBundle: .codeSignedOldED, newBundle: .codeSignedOnly, signatures: signatureConfig, expectedResult: false)
testPostValidation(oldBundle: .codeSignedOldED, newBundle: .codeSignedBoth, signatures: signatureConfig, expectedResult: signatureIsValid)
// You can't change two things at once.
testPostValidation(oldBundle: .codeSignedOldED, newBundle: .codeSignedBothNew, signatures: signatureConfig, expectedResult: false)
// It's permitted to remove code signing too.
testPostValidation(oldBundle: .codeSignedBoth, newBundle: .both, signatures: signatureConfig, expectedResult: signatureIsValid)
}
}
}
<file_sep>/Sparkle.podspec
Pod::Spec.new do |s|
s.name = "Sparkle"
s.version = "2.5.0-beta.1"
s.summary = "A software update framework for macOS"
s.description = "Sparkle is an easy-to-use software update framework for macOS."
s.homepage = "https://sparkle-project.org"
s.documentation_url = "https://sparkle-project.org/documentation/"
s.screenshot = "https://sparkle-project.org/images/[email protected]"
s.license = {
:type => 'MIT',
:file => 'LICENSE'
}
s.authors = {
'Zorg' => '<EMAIL>',
'<NAME>' => '<EMAIL>',
'<NAME>' => '<EMAIL>',
'<NAME>' => '<EMAIL>',
'<NAME>' => '<EMAIL>',
}
s.platform = :osx, '10.13'
s.source = { :http => "https://github.com/sparkle-project/Sparkle/releases/download/#{s.version}/Sparkle-#{s.version}.tar.xz" }
s.source_files = 'Sparkle.framework/Versions/B/Headers/*.h'
s.preserve_paths = ['bin/*', 'Entitlements', 'Symbols']
s.public_header_files = 'Sparkle.framework/Versions/B/Headers/*.h'
s.vendored_frameworks = 'Sparkle.framework'
s.xcconfig = {
'FRAMEWORK_SEARCH_PATHS' => '"${PODS_ROOT}/Sparkle"',
'LD_RUNPATH_SEARCH_PATHS' => '@loader_path/../Frameworks'
}
s.requires_arc = true
end
<file_sep>/Configurations/strip-framework.sh
#!/bin/sh
FRAMEWORK_PATH="${TARGET_BUILD_DIR}"/"${FULL_PRODUCT_NAME}"
# Remove any unused XPC Services
removedservices=0
if [[ "$SPARKLE_EMBED_INSTALLER_LAUNCHER_XPC_SERVICE" -eq 0 ]]; then
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_LAUNCHER_NAME}.xpc"
removedservices=$((removedservices+1))
fi
if [[ "$SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE" -eq 0 ]]; then
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${DOWNLOADER_NAME}.xpc"
removedservices=$((removedservices+1))
fi
if [[ "$SPARKLE_EMBED_INSTALLER_STATUS_XPC_SERVICE" -eq 0 ]]; then
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_STATUS_NAME}.xpc"
removedservices=$((removedservices+1))
fi
if [[ "$SPARKLE_EMBED_INSTALLER_CONNECTION_XPC_SERVICE" -eq 0 ]]; then
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_CONNECTION_NAME}.xpc"
removedservices=$((removedservices+1))
fi
if [[ "$removedservices" -eq 4 ]]; then
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"
rm -rf "${FRAMEWORK_PATH}"/"XPCServices"
fi
# Remove any unused nibs
if [[ "$SPARKLE_BUILD_UI_BITS" -eq 0 ]]; then
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/"SUStatus.nib"
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/"Base.lproj/SUUpdateAlert.nib"
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/"Base.lproj/SUUpdatePermissionPrompt.nib"
rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/"ReleaseNotesColorStyle.css"
fi
# Remove localization files if requested
if [[ "$SPARKLE_COPY_LOCALIZATIONS" -eq 0 ]]; then
for dir in "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/*; do
base=$(basename "$dir")
if [[ "$base" =~ .*".lproj" ]]; then
if [[ "$base" = "Base.lproj" ]]; then
rm -rf "$dir/Sparkle.strings"
# Remove Base.lproj if it's empty and the nibs have been stripped out already
rmdir "$dir"
else
rm -rf "$dir"
fi
fi
done
fi
<file_sep>/README.markdown
# Sparkle 2   [](https://github.com/Carthage/Carthage) [](https://cocoapods.org/pods/Sparkle)
Secure and reliable software update framework for macOS.
<img src="Resources/Screenshot.png" width="732" alt="Sparkle shows familiar update window with release notes">
Sparkle 2 adds support for application sandboxing, custom user interfaces, updating external bundles, and a more modern architecture which includes faster and more reliable installs.
Pre-releases when available can be found on the [Sparkle's Releases](https://github.com/sparkle-project/Sparkle/releases) or on your favorite package manager. More nightly builds can be downloaded by selecting a recent [workflow run](https://github.com/sparkle-project/Sparkle/actions?query=event%3Apush+is%3Asuccess+branch%3A2.x) and downloading the corresponding Sparkle-distribution artifact.
The current status for future versions of Sparkle is tracked by [its roadmap](https://github.com/sparkle-project/Sparkle/milestones).
Please visit [Sparkle's website](http://sparkle-project.org) for up to date documentation on using and migrating over to Sparkle 2. Refer to [Changelog](CHANGELOG) for a more detailed list of changes. More internal design documents to the project can be found in the repository under [Documentation](Documentation/).
## Features
* Seamless. There's no mention of Sparkle; your icons and app name are used.
* Secure. Updates are verified using EdDSA signatures and Apple Code Signing. Supports Sandboxed applications in Sparkle 2.
* Fast. Supports delta updates which only patch files that have changed and atomic-safe installs.
* Easy to install. Sparkle requires no code in your app, and only needs static files on a web server.
* Customizable. Sparkle 2 supports plugging in a custom UI for updates.
* Flexible. Supports applications, package installers, preference panes, and other plug-ins. Sparkle 2 supports updating external bundles.
* Handles permissions, quarantine, and automatically asks for authentication if needed.
* Uses RSS-based appcasts for release information. Appcasts are a de-facto standard supported by 3rd party update-tracking programs and websites.
* Stays hidden until second launch for better first impressions.
* Truly self-updating — the user can choose to automatically download and install all updates in the background.
* Ability to use channels for beta updates (in Sparkle 2), add phased rollouts to users, and mark updates as critical or major.
* Progress and status notifications for the host app.
## Requirements
* Runtime: macOS 10.13 or greater for 2.3, macOS 10.11 or greater for 2.2.x
* Build: Latest major Xcode (stable or beta, whichever is latest) and one major version less.
* HTTPS server for serving updates (see [App Transport Security](http://sparkle-project.org/documentation/app-transport-security/))
## Usage
See [getting started guide](https://sparkle-project.org/documentation/). No code is necessary, but a bit of configuration is required.
### Troubleshooting
* Please check **Console.app** for logs under your application. Sparkle prints detailed information there about all problems it encounters. It often also suggests solutions to the problems, so please read Sparkle's log messages carefully.
* Use the `generate_appcast` tool which creates appcast files, correct signatures, and delta updates automatically.
* Make sure the URL specified in [`SUFeedURL`](https://sparkle-project.org/documentation/customization/) is valid (typos/404s are a common error!), and that it uses modern TLS ([test it](https://www.ssllabs.com/ssltest/)).
### API symbols
Sparkle is built with `-fvisibility=hidden -fvisibility-inlines-hidden` which means no symbols are exported by default.
If you are adding a symbol to the public API you must decorate the declaration with the `SU_EXPORT` macro (grep the source code for examples).
### Building the distribution package
You do not usually need to build a Sparkle distribution unless you're making changes to Sparkle itself.
To build a Sparkle distribution, `cd` to the root of the Sparkle source tree and run `make release`. Sparkle-*VERSION*.tar.xz (or .bz2) will be created in a temporary directory and revealed in Finder after the build has completed.
Alternatively, build the Distribution scheme in the Xcode UI.
### Code of Conduct
We pledge to have an open and welcoming environment. See our [Code of Conduct](CODE_OF_CONDUCT.md).
<file_sep>/generate_appcast/FeedXML.swift
//
// Created by Kornel on 22/12/2016.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
import Foundation
func findElement(name: String, parent: XMLElement) -> XMLElement? {
if let found = try? parent.nodes(forXPath: name) {
if found.count > 0 {
if let element = found[0] as? XMLElement {
return element
}
}
}
return nil
}
func createElement(name: String, parent: XMLElement) -> XMLElement {
let element = XMLElement(name: name)
parent.addChild(element)
return element
}
func findOrCreateElement(name: String, parent: XMLElement) -> XMLElement {
if let element = findElement(name: name, parent: parent) {
return element
}
return createElement(name: name, parent: parent)
}
func text(_ text: String) -> XMLNode {
return XMLNode.text(withStringValue: text) as! XMLNode
}
func extractVersion(parent: XMLNode) -> String? {
guard let itemElement = parent as? XMLElement else {
return nil
}
// Look for version attribute in enclosure
if let enclosure = findElement(name: "enclosure", parent: itemElement) {
if let versionAttribute = enclosure.attribute(forName: SUAppcastAttributeVersion) {
return versionAttribute.stringValue
}
}
// Look for top level version element
if let versionElement = findElement(name: SUAppcastElementVersion, parent: itemElement) {
return versionElement.stringValue
}
return nil
}
func readAppcast(archives: [String: ArchiveItem], appcastURL: URL) throws -> [String: UpdateBranch] {
let options: XMLNode.Options = [
XMLNode.Options.nodeLoadExternalEntitiesNever,
XMLNode.Options.nodePreserveCDATA,
XMLNode.Options.nodePreserveWhitespace,
]
let doc = try XMLDocument(contentsOf: appcastURL, options: options)
let rootNodes = try doc.nodes(forXPath: "/rss")
if rootNodes.count != 1 {
throw makeError(code: .appcastError, "Weird XML? \(appcastURL.path)")
}
let root = rootNodes[0] as! XMLElement
let channelNodes = try root.nodes(forXPath: "channel")
if channelNodes.count == 0 {
throw makeError(code: .appcastError, "Weird Feed? No channels: \(appcastURL.path)")
}
let channel = channelNodes[0] as! XMLElement
guard let itemNodes = try? channel.nodes(forXPath: "item") else {
return [:]
}
var updateBranches: [String: UpdateBranch] = [:]
for item in itemNodes {
guard let item = item as? XMLElement else {
continue
}
let version: String?
if let versionElement = findElement(name: SUAppcastElementVersion, parent: item) {
version = versionElement.stringValue
} else if let enclosure = findElement(name: "enclosure", parent: item), let versionAttribute = enclosure.attribute(forName: SUAppcastAttributeVersion) {
version = versionAttribute.stringValue
} else {
version = nil
}
guard let version = version else {
continue
}
let minimumSystemVersion: String?
if let minVer = findElement(name: SUAppcastElementMinimumSystemVersion, parent: item) {
minimumSystemVersion = minVer.stringValue
} else if let archive = archives[version] {
minimumSystemVersion = archive.minimumSystemVersion
} else {
minimumSystemVersion = nil
}
let maximumSystemVersion: String?
if let maxVer = findElement(name: SUAppcastElementMaximumSystemVersion, parent: item) {
maximumSystemVersion = maxVer.stringValue
} else {
maximumSystemVersion = nil
}
let minimumAutoupdateVersion: String?
if let minimumAutoupdateVersionElement = findElement(name: SUAppcastElementMinimumAutoupdateVersion, parent: item) {
minimumAutoupdateVersion = minimumAutoupdateVersionElement.stringValue
} else {
minimumAutoupdateVersion = nil
}
let sparkleChannel: String?
if let sparkleChannelElement = findElement(name: SUAppcastElementChannel, parent: item) {
sparkleChannel = sparkleChannelElement.stringValue
} else {
sparkleChannel = nil
}
let updateBranch = UpdateBranch(minimumSystemVersion: minimumSystemVersion, maximumSystemVersion: maximumSystemVersion, minimumAutoupdateVersion: minimumAutoupdateVersion, channel: sparkleChannel)
updateBranches[version] = updateBranch
}
return updateBranches
}
func writeAppcast(appcastDestPath: URL, appcast: Appcast, fullReleaseNotesLink: String?, preferToEmbedReleaseNotes: Bool, link: String?, newChannel: String?, majorVersion: String?, ignoreSkippedUpgradesBelowVersion: String?, phasedRolloutInterval: Int?, criticalUpdateVersion: String?, informationalUpdateVersions: [String]?) throws -> (numNewUpdates: Int, numExistingUpdates: Int, numUpdatesRemoved: Int) {
let appBaseName = appcast.inferredAppName
let sparkleNS = "http://www.andymatuschak.org/xml-namespaces/sparkle"
var doc: XMLDocument
do {
let options: XMLNode.Options = [
XMLNode.Options.nodeLoadExternalEntitiesNever,
XMLNode.Options.nodePreserveCDATA,
XMLNode.Options.nodePreserveWhitespace,
]
doc = try XMLDocument(contentsOf: appcastDestPath, options: options)
} catch {
let root = XMLElement(name: "rss")
root.addAttribute(XMLNode.attribute(withName: "xmlns:sparkle", stringValue: sparkleNS) as! XMLNode)
root.addAttribute(XMLNode.attribute(withName: "version", stringValue: "2.0") as! XMLNode)
doc = XMLDocument(rootElement: root)
doc.isStandalone = true
}
var channel: XMLElement
let rootNodes = try doc.nodes(forXPath: "/rss")
if rootNodes.count != 1 {
throw makeError(code: .appcastError, "Weird XML? \(appcastDestPath.path)")
}
let root = rootNodes[0] as! XMLElement
let channelNodes = try root.nodes(forXPath: "channel")
var numUpdatesRemoved: Int = 0
if channelNodes.count > 0 {
channel = channelNodes[0] as! XMLElement
// Enumerate through all existing update items and remove any that we aren't going to keep
let versionsInFeedSet = Set(appcast.versionsInFeed)
var nodesToRemove: [XMLElement] = []
if let itemNodes = try? channel.nodes(forXPath: "item") {
for item in itemNodes {
guard let item = item as? XMLElement else {
continue
}
let version: String?
if let versionElement = findElement(name: SUAppcastElementVersion, parent: item) {
version = versionElement.stringValue
} else if let enclosure = findElement(name: "enclosure", parent: item), let versionAttribute = enclosure.attribute(forName: SUAppcastAttributeVersion) {
version = versionAttribute.stringValue
} else {
version = nil
}
guard let version = version else {
continue
}
if !versionsInFeedSet.contains(version) {
nodesToRemove.append(item)
}
}
// Remove old nodes from highest-to-lowest index order
for node in nodesToRemove.reversed() {
channel.removeChild(at: node.index)
}
numUpdatesRemoved = nodesToRemove.count
}
} else {
channel = XMLElement(name: "channel")
channel.addChild(XMLElement.element(withName: "title", stringValue: appBaseName) as! XMLElement)
root.addChild(channel)
}
var numNewUpdates = 0
var numExistingUpdates = 0
let versionComparator = SUStandardVersionComparator()
var numItems = 0
for version in appcast.versionsInFeed {
guard let update = appcast.archives[version] else {
continue
}
var item: XMLElement
var existingItems = try channel.nodes(forXPath: "item[enclosure[@\(SUAppcastAttributeVersion)=\"\(update.version)\"]]")
if existingItems.count == 0 {
// Fall back to see if any items are using the element version variant
existingItems = try channel.nodes(forXPath: "item[\(SUAppcastElementVersion)=\"\(update.version)\"]")
}
let createNewItem = (existingItems.count == 0)
if createNewItem {
numNewUpdates += 1
} else {
numExistingUpdates += 1
}
numItems += 1
if createNewItem {
item = XMLElement.element(withName: "item") as! XMLElement
// When we insert a new item, find the best place to insert the new update item in
// This takes account of existing items and even ones that we don't have existing info on
var foundBestUpdateInsertion = false
if let itemNodes = try? channel.nodes(forXPath: "item") {
for childItemNode in itemNodes {
guard let childItemNode = childItemNode as? XMLElement else {
continue
}
guard let childItemVersion = extractVersion(parent: childItemNode) else {
continue
}
if versionComparator.compareVersion(update.version, toVersion: childItemVersion) == .orderedDescending {
channel.insertChild(item, at: childItemNode.index)
foundBestUpdateInsertion = true
break
}
}
}
if !foundBestUpdateInsertion {
channel.addChild(item)
}
} else {
item = existingItems[0] as! XMLElement
}
if nil == findElement(name: "title", parent: item) {
item.addChild(XMLElement.element(withName: "title", stringValue: update.shortVersion) as! XMLElement)
}
if nil == findElement(name: "pubDate", parent: item) {
item.addChild(XMLElement.element(withName: "pubDate", stringValue: update.pubDate) as! XMLElement)
}
if createNewItem {
// Set link
if let link = link,
let linkElement = XMLElement.element(withName: SURSSElementLink, uri: sparkleNS) as? XMLElement {
linkElement.setChildren([text(link)])
item.addChild(linkElement)
}
if let fullReleaseNotesLink = fullReleaseNotesLink,
let fullReleaseNotesElement = XMLElement.element(withName: SUAppcastElementFullReleaseNotesLink, uri: sparkleNS) as? XMLElement {
fullReleaseNotesElement.setChildren([text(fullReleaseNotesLink)])
item.addChild(fullReleaseNotesElement)
}
// Set new channel name
if let newChannelName = newChannel,
let channelNameElement = XMLElement.element(withName: SUAppcastElementChannel, uri: sparkleNS) as? XMLElement {
channelNameElement.setChildren([text(newChannelName)])
item.addChild(channelNameElement)
}
// Set last major version
if let minimumAutoupdateVersion = majorVersion,
let minimumAutoupdateVersionElement = XMLElement.element(withName: SUAppcastElementMinimumAutoupdateVersion, uri: sparkleNS) as? XMLElement {
minimumAutoupdateVersionElement.setChildren([text(minimumAutoupdateVersion)])
item.addChild(minimumAutoupdateVersionElement)
}
// Set ignore skipped upgrades below version
if let ignoreSkippedUpgradesBelowVersion = ignoreSkippedUpgradesBelowVersion, let ignoreSkippedUpgradesBelowVersionElement = XMLElement.element(withName: SUAppcastElementIgnoreSkippedUpgradesBelowVersion, uri: sparkleNS) as? XMLElement {
ignoreSkippedUpgradesBelowVersionElement.setChildren([text(ignoreSkippedUpgradesBelowVersion)])
item.addChild(ignoreSkippedUpgradesBelowVersionElement)
}
// Set phased rollout interval
if let phasedRolloutInterval = phasedRolloutInterval,
let phasedRolloutIntervalElement = XMLElement.element(withName: SUAppcastElementPhasedRolloutInterval, uri: sparkleNS) as? XMLElement {
phasedRolloutIntervalElement.setChildren([text(String(phasedRolloutInterval))])
item.addChild(phasedRolloutIntervalElement)
}
// Set last critical update version
if let criticalUpdateVersion = criticalUpdateVersion,
let criticalUpdateElement = XMLElement.element(withName: SUAppcastElementCriticalUpdate, uri: sparkleNS) as? XMLElement {
if criticalUpdateVersion.count > 0 {
criticalUpdateElement.setAttributesWith([SUAppcastAttributeVersion: criticalUpdateVersion])
}
item.addChild(criticalUpdateElement)
}
// Set informational update versions
if let informationalUpdateVersions = informationalUpdateVersions,
let informationalUpdateElement = XMLElement.element(withName: SUAppcastElementInformationalUpdate, uri: sparkleNS) as? XMLElement {
let versionElements: [XMLElement] = informationalUpdateVersions.compactMap({ informationalUpdateVersion in
let element: XMLElement?
let informationalVersionText: String
if informationalUpdateVersion.hasPrefix("<") {
element = XMLElement.element(withName: SUAppcastElementBelowVersion, uri: sparkleNS) as? XMLElement
informationalVersionText = String(informationalUpdateVersion.dropFirst())
} else {
element = XMLElement.element(withName: SUAppcastElementVersion, uri: sparkleNS) as? XMLElement
informationalVersionText = informationalUpdateVersion
}
element?.setChildren([text(informationalVersionText)])
return element
})
informationalUpdateElement.setChildren(versionElements)
item.addChild(informationalUpdateElement)
}
}
var versionElement = findElement(name: SUAppcastElementVersion, parent: item)
if nil == versionElement {
versionElement = XMLElement.element(withName: SUAppcastElementVersion, uri: sparkleNS) as? XMLElement
item.addChild(versionElement!)
}
versionElement?.setChildren([text(update.version)])
var shortVersionElement = findElement(name: SUAppcastElementShortVersionString, parent: item)
if nil == shortVersionElement {
shortVersionElement = XMLElement.element(withName: SUAppcastElementShortVersionString, uri: sparkleNS) as? XMLElement
item.addChild(shortVersionElement!)
}
shortVersionElement?.setChildren([text(update.shortVersion)])
// Override the minimum system version with the version from the archive,
// only if an existing item doesn't specify one
let minimumSystemVersion: String
var minVer = findElement(name: SUAppcastElementMinimumSystemVersion, parent: item)
if let minVer = minVer {
minimumSystemVersion = minVer.stringValue ?? update.minimumSystemVersion
} else {
minVer = XMLElement.element(withName: SUAppcastElementMinimumSystemVersion, uri: sparkleNS) as? XMLElement
item.addChild(minVer!)
minimumSystemVersion = update.minimumSystemVersion
}
minVer?.setChildren([text(minimumSystemVersion)])
// Look for an existing release notes element
let releaseNotesXpath = "\(SUAppcastElementReleaseNotesLink)"
let results = ((try? item.nodes(forXPath: releaseNotesXpath)) as? [XMLElement])?
.filter { !($0.attributes ?? [])
.contains(where: { $0.name == SUXMLLanguage }) }
let relElement = results?.first
// If an existing item has a release notes item, don't automatically embed release notes even if the user
// prefers to embed release notes (we only respect this choice for updates without a release notes item or a new item)
let embedReleaseNotesAlways = preferToEmbedReleaseNotes && (relElement == nil)
if let (descriptionContents, descriptionFormat) = update.releaseNotesContent(embedReleaseNotesAlways: embedReleaseNotesAlways) {
let descElement = findOrCreateElement(name: "description", parent: item)
let cdata = XMLNode(kind: .text, options: .nodeIsCDATA)
cdata.stringValue = descriptionContents
descElement.setChildren([cdata])
if descriptionFormat != "html" {
descElement.addAttribute(XMLNode.attribute(withName: SUAppcastAttributeFormat, stringValue: descriptionFormat) as! XMLNode)
}
} else if let existingDescriptionElement = findElement(name: "description", parent: item) {
// The update doesn't include embedded release notes. Remove it.
item.removeChild(at: existingDescriptionElement.index)
}
if let url = update.releaseNotesURL(embedReleaseNotesAlways: embedReleaseNotesAlways) {
// The update includes a valid release notes URL
if let existingReleaseNotesElement = relElement {
// The existing item includes a release notes element. Update it.
existingReleaseNotesElement.stringValue = url.absoluteString
} else {
// The existing item doesn't have a release notes element. Add one.
item.addChild(XMLElement.element(withName: SUAppcastElementReleaseNotesLink, stringValue: url.absoluteString) as! XMLElement)
}
} else if let childIndex = relElement?.index {
// The update doesn't include a release notes URL. Remove it.
item.removeChild(at: childIndex)
}
let languageNotesNodes = ((try? item.nodes(forXPath: releaseNotesXpath)) as? [XMLElement])?
.map { ($0, $0.attribute(forName: SUXMLLanguage)?.stringValue )}
.filter { $0.1 != nil } ?? []
for (node, language) in languageNotesNodes.reversed()
where !update.localizedReleaseNotes().contains(where: { $0.0 == language }) {
item.removeChild(at: node.index)
}
for (language, url) in update.localizedReleaseNotes() {
if !languageNotesNodes.contains(where: { $0.1 == language }) {
let localizedNode = XMLNode.element(
withName: SUAppcastElementReleaseNotesLink,
children: [XMLNode.text(withStringValue: url.absoluteString) as! XMLNode],
attributes: [XMLNode.attribute(withName: SUXMLLanguage, stringValue: language) as! XMLNode])
item.addChild(localizedNode as! XMLNode)
}
}
var enclosure = findElement(name: "enclosure", parent: item)
if nil == enclosure {
enclosure = XMLElement.element(withName: "enclosure") as? XMLElement
item.addChild(enclosure!)
}
guard let archiveURL = update.archiveURL?.absoluteString else {
throw makeError(code: .appcastError, "Bad archive name or feed URL")
}
var attributes = [
XMLNode.attribute(withName: "url", stringValue: archiveURL) as! XMLNode,
XMLNode.attribute(withName: "length", stringValue: String(update.fileSize)) as! XMLNode,
XMLNode.attribute(withName: "type", stringValue: update.mimeType) as! XMLNode,
]
if let sig = update.edSignature {
attributes.append(XMLNode.attribute(withName: SUAppcastAttributeEDSignature, uri: sparkleNS, stringValue: sig) as! XMLNode)
}
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
if let sig = update.dsaSignature {
attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDSASignature, uri: sparkleNS, stringValue: sig) as! XMLNode)
}
#endif
enclosure!.attributes = attributes
if update.deltas.count > 0 {
var deltas = findElement(name: SUAppcastElementDeltas, parent: item)
if nil == deltas {
deltas = XMLElement.element(withName: SUAppcastElementDeltas, uri: sparkleNS) as? XMLElement
item.addChild(deltas!)
} else {
deltas!.setChildren([])
}
for delta in update.deltas {
var attributes = [
XMLNode.attribute(withName: "url", stringValue: URL(string: delta.archivePath.lastPathComponent.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed)!, relativeTo: update.archiveURL)!.absoluteString) as! XMLNode,
XMLNode.attribute(withName: SUAppcastAttributeDeltaFrom, uri: sparkleNS, stringValue: delta.fromVersion) as! XMLNode,
XMLNode.attribute(withName: "length", stringValue: String(delta.fileSize)) as! XMLNode,
XMLNode.attribute(withName: "type", stringValue: "application/octet-stream") as! XMLNode,
]
if let sparkleExecutableFileSize = delta.sparkleExecutableFileSize {
attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDeltaFromSparkleExecutableSize, stringValue: String(sparkleExecutableFileSize)) as! XMLNode)
}
if let sparkleLocales = delta.sparkleLocales {
attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDeltaFromSparkleLocales, stringValue: sparkleLocales) as! XMLNode)
}
if let sig = delta.edSignature {
attributes.append(XMLNode.attribute(withName: SUAppcastAttributeEDSignature, uri: sparkleNS, stringValue: sig) as! XMLNode)
}
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
if let sig = delta.dsaSignature {
attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDSASignature, uri: sparkleNS, stringValue: sig) as! XMLNode)
}
#endif
deltas!.addChild(XMLNode.element(withName: "enclosure", children: nil, attributes: attributes) as! XMLElement)
}
}
}
let options: XMLNode.Options = [.nodeCompactEmptyElement, .nodePrettyPrint]
let docData = doc.xmlData(options: options)
_ = try XMLDocument(data: docData, options: XMLNode.Options()); // Verify that it was generated correctly, which does not always happen!
try docData.write(to: appcastDestPath)
return (numNewUpdates, numExistingUpdates, numUpdatesRemoved)
}
<file_sep>/generate_appcast/Signatures.swift
//
// Created by Kornel on 23/12/2016.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
import Foundation
struct PrivateKeys {
var privateDSAKey: SecKey?
var privateEdKey: Data?
var publicEdKey: Data?
init(privateDSAKey: SecKey?, privateEdKey: Data?, publicEdKey: Data?) {
self.privateDSAKey = privateDSAKey
self.privateEdKey = privateEdKey
self.publicEdKey = publicEdKey
}
}
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
func loadPrivateDSAKey(at privateKeyURL: URL) throws -> SecKey {
let data = try Data(contentsOf: privateKeyURL)
var cfitems: CFArray?
var format = SecExternalFormat.formatOpenSSL
var type = SecExternalItemType.itemTypePrivateKey
let status = SecItemImport(data as CFData, nil, &format, &type, SecItemImportExportFlags(rawValue: UInt32(0)), nil, nil, &cfitems)
if status != errSecSuccess || cfitems == nil {
print("Private DSA key file", privateKeyURL.path, "exists, but it could not be read. SecItemImport error", status)
throw NSError(domain: SUSparkleErrorDomain, code: Int(OSStatus(SUError.signatureError.rawValue)), userInfo: nil)
}
if format != SecExternalFormat.formatOpenSSL || type != SecExternalItemType.itemTypePrivateKey {
throw makeError(code: .signatureError, "Not an OpensSSL private key \(format) \(type)")
}
return (cfitems! as NSArray)[0] as! SecKey
}
func loadPrivateDSAKey(named keyName: String, fromKeychainAt keychainURL: URL) throws -> SecKey {
var keychain: SecKeychain?
guard SecKeychainOpen(keychainURL.path, &keychain) == errSecSuccess, keychain != nil else {
throw NSError(domain: SUSparkleErrorDomain, code: Int(OSStatus(SUError.signatureError.rawValue)), userInfo: nil)
}
let query: [CFString: CFTypeRef] = [
kSecClass: kSecClassKey,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecAttrLabel: keyName as CFString,
kSecMatchLimit: kSecMatchLimitOne,
kSecUseKeychain: keychain!,
kSecReturnRef: kCFBooleanTrue,
]
var item: CFTypeRef?
guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess, item != nil else {
throw NSError(domain: SUSparkleErrorDomain, code: Int(OSStatus(SUError.signatureError.rawValue)), userInfo: nil)
}
return item! as! SecKey
}
func dsaSignature(path: URL, privateDSAKey: SecKey) throws -> String {
var error: Unmanaged<CFError>?
let stream = InputStream(fileAtPath: path.path)!
let dataReadTransform = SecTransformCreateReadTransformWithReadStream(stream)
let dataDigestTransform = SecDigestTransformCreate(kSecDigestSHA1, 20, nil)
guard let dataSignTransform = SecSignTransformCreate(privateDSAKey, &error) else {
print("can't use the key")
throw error!.takeRetainedValue()
}
let group = SecTransformCreateGroupTransform()
SecTransformConnectTransforms(dataReadTransform, kSecTransformOutputAttributeName, dataDigestTransform, kSecTransformInputAttributeName, group, &error)
if error != nil {
throw error!.takeRetainedValue()
}
SecTransformConnectTransforms(dataDigestTransform, kSecTransformOutputAttributeName, dataSignTransform, kSecTransformInputAttributeName, group, &error)
if error != nil {
throw error!.takeRetainedValue()
}
let result = SecTransformExecute(group, &error)
if error != nil {
throw error!.takeRetainedValue()
}
guard let resultData = result as? Data else {
throw makeError(code: .signatureError, "SecTransformExecute returned non-data")
}
return resultData.base64EncodedString()
}
#endif
func edSignature(path: URL, publicEdKey: Data, privateEdKey: Data) throws -> String {
assert(publicEdKey.count == 32)
assert(privateEdKey.count == 64)
let data = Array(try Data.init(contentsOf: path, options: .mappedIfSafe))
var output = Array<UInt8>(repeating: 0, count: 64)
let pubkey = Array(publicEdKey), privkey = Array(privateEdKey)
ed25519_sign(&output, data, data.count, pubkey, privkey)
return Data(output).base64EncodedString()
}
<file_sep>/Configurations/make-release-package.sh
#!/bin/bash
set -e
# Tests the code signing validity of the extracted products within the provided path.
# This guards against our archives being corrupt / created incorrectly.
function verify_code_signatures() {
verification_directory="$1"
check_aux_apps="$2"
if [[ -z "$verification_directory" ]]; then
echo "Provided verification directory does not exist" >&2
exit 1
fi
# Search the current directory for all instances of the framework to verify them (XCFrameworks can have multiple copies of a framework for different platforms).
find "${verification_directory}" -name "Sparkle.framework" -type d -exec codesign --verify -vvv --deep {} \;
if [ "$check_aux_apps" = true ] ; then
codesign --verify -vvv --deep "${verification_directory}/sparkle.app"
codesign --verify -vvv --deep "${verification_directory}/Sparkle Test App.app"
fi
codesign --verify -vvv --deep "${verification_directory}/bin/BinaryDelta"
codesign --verify -vvv --deep "${verification_directory}/bin/generate_appcast"
codesign --verify -vvv --deep "${verification_directory}/bin/sign_update"
codesign --verify -vvv --deep "${verification_directory}/bin/generate_keys"
}
if [ "$ACTION" = "" ] ; then
rm -rf "$CONFIGURATION_BUILD_DIR/staging"
rm -rf "$CONFIGURATION_BUILD_DIR/staging-spm"
rm -f "Sparkle-$MARKETING_VERSION.tar.xz"
rm -f "Sparkle-$MARKETING_VERSION.tar.bz2"
rm -f "Sparkle-for-Swift-Package-Manager.zip"
mkdir -p "$CONFIGURATION_BUILD_DIR/staging"
mkdir -p "$CONFIGURATION_BUILD_DIR/staging-spm"
cp "$SRCROOT/CHANGELOG" "$SRCROOT/LICENSE" "$SRCROOT/INSTALL" "$SRCROOT/Resources/SampleAppcast.xml" "$CONFIGURATION_BUILD_DIR/staging"
cp "$SRCROOT/CHANGELOG" "$SRCROOT/LICENSE" "$SRCROOT/INSTALL" "$SRCROOT/Resources/SampleAppcast.xml" "$CONFIGURATION_BUILD_DIR/staging-spm"
cp -R "$SRCROOT/bin" "$CONFIGURATION_BUILD_DIR/staging"
cp "$CONFIGURATION_BUILD_DIR/BinaryDelta" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp "$CONFIGURATION_BUILD_DIR/generate_appcast" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp "$CONFIGURATION_BUILD_DIR/generate_keys" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp "$CONFIGURATION_BUILD_DIR/sign_update" "$CONFIGURATION_BUILD_DIR/staging/bin"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/sparkle.app" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework" "$CONFIGURATION_BUILD_DIR/staging"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.xcframework" "$CONFIGURATION_BUILD_DIR/staging-spm"
if [[ "$SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE" -eq 1 ]]; then
mkdir -p "$CONFIGURATION_BUILD_DIR/staging/Entitlements"
mkdir -p "$CONFIGURATION_BUILD_DIR/staging-spm/Entitlements"
cp -R "$SRCROOT/Downloader/org.sparkle-project.Downloader.entitlements" "$CONFIGURATION_BUILD_DIR/staging/Entitlements/$DOWNLOADER_NAME.entitlements"
cp -R "$SRCROOT/Downloader/org.sparkle-project.Downloader.entitlements" "$CONFIGURATION_BUILD_DIR/staging-spm/Entitlements/$DOWNLOADER_NAME.entitlements"
fi
mkdir -p "$CONFIGURATION_BUILD_DIR/staging/Symbols"
# Only copy dSYMs for Release builds, but don't check for the presence of the actual files
# because missing dSYMs in a release build SHOULD trigger a build failure
if [ "$CONFIGURATION" = "Release" ] ; then
cp -R "$CONFIGURATION_BUILD_DIR/BinaryDelta.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
cp -R "$CONFIGURATION_BUILD_DIR/generate_appcast.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
cp -R "$CONFIGURATION_BUILD_DIR/generate_keys.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
cp -R "$CONFIGURATION_BUILD_DIR/sign_update.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle Test App.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
cp -R "$CONFIGURATION_BUILD_DIR/sparkle.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
cp -R "$CONFIGURATION_BUILD_DIR/Sparkle.framework.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
cp -R "$CONFIGURATION_BUILD_DIR/Autoupdate.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
cp -R "$CONFIGURATION_BUILD_DIR/Updater.app.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
cp -R "$CONFIGURATION_BUILD_DIR/${INSTALLER_LAUNCHER_NAME}.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
cp -R "$CONFIGURATION_BUILD_DIR/${DOWNLOADER_NAME}.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/Symbols"
fi
cp -R "$CONFIGURATION_BUILD_DIR/staging/bin" "$CONFIGURATION_BUILD_DIR/staging-spm"
cd "$CONFIGURATION_BUILD_DIR/staging"
if [ -x "$(command -v xz)" ]; then
XZ_EXISTS=1
else
XZ_EXISTS=0
fi
rm -rf "/tmp/sparkle-extract"
mkdir -p "/tmp/sparkle-extract"
# Sorted file list groups similar files together, which improves tar compression
if [ "$XZ_EXISTS" -eq 1 ] ; then
find . \! -type d | rev | sort | rev | tar cv --files-from=- | xz -9 > "../Sparkle-$MARKETING_VERSION.tar.xz"
# Copy archived distribution for CI
cp -f "../Sparkle-$MARKETING_VERSION.tar.xz" "../sparkle-dist.tar.xz"
# Extract archive for testing binary validity
tar -xf "../Sparkle-$MARKETING_VERSION.tar.xz" -C "/tmp/sparkle-extract"
else
# Fallback to bz2 compression if xz utility is not available
find . \! -type d | rev | sort | rev | tar cjvf "../Sparkle-$MARKETING_VERSION.tar.bz2" --files-from=-
# Extract archive for testing binary validity
tar -xf "../Sparkle-$MARKETING_VERSION.tar.bz2" -C "/tmp/sparkle-extract"
fi
# Test code signing validity of the extracted products
# This guards against our archives being corrupt / created incorrectly
verify_code_signatures "/tmp/sparkle-extract" true
rm -rf "/tmp/sparkle-extract"
rm -rf "$CONFIGURATION_BUILD_DIR/staging"
# Get latest git tag
cd "$SRCROOT"
latest_git_tag=$( git describe --tags --abbrev=0 || true )
if [ -n "$latest_git_tag" ] ; then
# Generate zip containing the xcframework for SPM
rm -rf "/tmp/sparkle-spm-extract"
mkdir -p "/tmp/sparkle-spm-extract"
cd "$CONFIGURATION_BUILD_DIR/staging-spm"
# rm -rf "$CONFIGURATION_BUILD_DIR/Sparkle.xcarchive"
ditto -c -k --zlibCompressionLevel 9 --rsrc . "../Sparkle-for-Swift-Package-Manager.zip"
# Test code signing validity of the extracted Swift package
# This guards against our archives being corrupt / created incorrectly
ditto -x -k "../Sparkle-for-Swift-Package-Manager.zip" "/tmp/sparkle-spm-extract"
verify_code_signatures "/tmp/sparkle-spm-extract" false
rm -rf "/tmp/sparkle-spm-extract"
rm -rf "$CONFIGURATION_BUILD_DIR/staging-spm"
cd "$SRCROOT"
# Check semantic versioning
if [[ $latest_git_tag =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(\\+([0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*))?$ ]]; then
echo "Tag $latest_git_tag follows semantic versioning"
else
echo "ERROR: Tag $latest_git_tag does not follow semantic versioning! SPM will not be able to resolve the repository" >&2
exit 1
fi
# Generate new Package manifest, podspec, and carthage files
cd "$CONFIGURATION_BUILD_DIR"
cp "$SRCROOT/Package.swift" "$CONFIGURATION_BUILD_DIR"
cp "$SRCROOT/Sparkle.podspec" "$CONFIGURATION_BUILD_DIR"
cp "$SRCROOT/Carthage-dev.json" "$CONFIGURATION_BUILD_DIR"
fi
if [ -z "$latest_git_tag" ] ; then
echo "warning: No git repository found so skipping updating package management files"
elif [ "$XCODE_VERSION_MAJOR" -ge "1200" ]; then
# is equivalent to shasum -a 256 FILE
spm_checksum=$(swift package compute-checksum "Sparkle-for-Swift-Package-Manager.zip")
rm -rf ".build"
sed -E -i '' -e "/let tag/ s/\".+\"/\"$latest_git_tag\"/" -e "/let version/ s/\".+\"/\"$MARKETING_VERSION\"/" -e "/let checksum/ s/[[:xdigit:]]{64}/$spm_checksum/" "Package.swift"
cp "Package.swift" "$SRCROOT"
echo "Package.swift updated with the following values:"
echo "Version: $MARKETING_VERSION"
echo "Tag: $latest_git_tag"
echo "Checksum: $spm_checksum"
sed -E -i '' -e "/s\.version.+=/ s/\".+\"/\"$MARKETING_VERSION\"/" "Sparkle.podspec"
"$SRCROOT/Configurations/update-carthage.py" "Carthage-dev.json" "$MARKETING_VERSION"
cp "Sparkle.podspec" "$SRCROOT"
# Note the Carthage-dev.json file will finally be copied to the website repo in Carthage/Sparkle.json in the end
cp "Carthage-dev.json" "$SRCROOT"
echo "Sparkle.podspec and Carthage-dev.json updated with following values:"
echo "Version: $MARKETING_VERSION"
else
echo "warning: Xcode version $XCODE_VERSION_ACTUAL does not support computing checksums for Swift Packages. Please update the Package manifest manually."
fi
if [ "$XZ_EXISTS" -ne 1 ] ; then
echo "WARNING: xz compression is used for official releases but bz2 is being used instead because xz tool is not installed on your system."
fi
rm -rf "$CONFIGURATION_BUILD_DIR/staging-spm"
fi
<file_sep>/Tests/SUUnarchiverTest.swift
//
// SUUnarchiverTest.swift
// Sparkle
//
// Created by <NAME> on 9/4/15.
// Copyright © 2015 Sparkle Project. All rights reserved.
//
import XCTest
class SUUnarchiverTest: XCTestCase
{
func unarchiveTestAppWithExtension(_ archiveExtension: String, password: String? = nil, resourceName: String = "SparkleTestCodeSignApp", extractedAppName: String = "SparkleTestCodeSignApp", expectingInstallationType installationType: String = SPUInstallationTypeApplication, expectingSuccess: Bool = true) {
let appName = resourceName
let archiveResourceURL = Bundle(for: type(of: self)).url(forResource: appName, withExtension: archiveExtension)!
let fileManager = FileManager.default
// Do not remove this temporary directory
// If we do want to clean up and remove it (which isn't necessary but nice), we'd have to remove it
// after *both* our unarchive success and failure calls below finish (they both have async completion blocks inside their implementation)
let tempDirectoryURL = try! fileManager.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: URL(fileURLWithPath: NSHomeDirectory()), create: true)
let unarchivedSuccessExpectation = super.expectation(description: "Unarchived Success (format: \(archiveExtension))")
let unarchivedFailureExpectation = super.expectation(description: "Unarchived Failure (format: \(archiveExtension))")
let tempArchiveURL = tempDirectoryURL.appendingPathComponent(archiveResourceURL.lastPathComponent)
let extractedAppURL = tempDirectoryURL.appendingPathComponent(extractedAppName).appendingPathExtension("app")
self.unarchiveTestAppWithExtension(archiveExtension, appName: appName, tempDirectoryURL: tempDirectoryURL, tempArchiveURL: tempArchiveURL, archiveResourceURL: archiveResourceURL, password: <PASSWORD>, expectingInstallationType: installationType, expectingSuccess: expectingSuccess, testExpectation: unarchivedSuccessExpectation)
self.unarchiveNonExistentFileTestFailureAppWithExtension(archiveExtension, tempDirectoryURL: tempDirectoryURL, password: <PASSWORD>, expectingInstallationType: installationType, testExpectation: unarchivedFailureExpectation)
super.waitForExpectations(timeout: 30.0, handler: nil)
if !archiveExtension.hasSuffix("pkg") && expectingSuccess {
XCTAssertTrue(fileManager.fileExists(atPath: extractedAppURL.path))
XCTAssertEqual("6a60ab31430cfca8fb499a884f4a29f73e59b472", hashOfTree(extractedAppURL.path))
}
}
func unarchiveNonExistentFileTestFailureAppWithExtension(_ archiveExtension: String, tempDirectoryURL: URL, password: String?, expectingInstallationType installationType: String, testExpectation: XCTestExpectation) {
let tempArchiveURL = tempDirectoryURL.appendingPathComponent("error-invalid").appendingPathExtension(archiveExtension)
let unarchiver = SUUnarchiver.unarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, decryptionPassword: <PASSWORD>, expectingInstallationType: installationType)!
unarchiver.unarchive(completionBlock: {(error: Error?) -> Void in
XCTAssertNotNil(error)
testExpectation.fulfill()
}, progressBlock: nil)
}
// swiftlint:disable function_parameter_count
func unarchiveTestAppWithExtension(_ archiveExtension: String, appName: String, tempDirectoryURL: URL, tempArchiveURL: URL, archiveResourceURL: URL, password: String?, expectingInstallationType installationType: String, expectingSuccess: Bool, testExpectation: XCTestExpectation) {
let fileManager = FileManager.default
try! fileManager.copyItem(at: archiveResourceURL, to: tempArchiveURL)
let unarchiver = SUUnarchiver.unarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, decryptionPassword: password, expectingInstallationType: installationType)!
unarchiver.unarchive(completionBlock: {(error: Error?) -> Void in
if expectingSuccess {
XCTAssertNil(error)
} else {
XCTAssertNotNil(error)
}
testExpectation.fulfill()
}, progressBlock: nil)
}
func testUnarchivingZip()
{
self.unarchiveTestAppWithExtension("zip")
}
// This zip file has extraneous zero bytes added at the very end
func testUnarchivingBadZipWithExtaneousTrailingBytes() {
// We may receive a SIGPIPE error when writing data to a pipe
// The Autoupdate installer ignores SIGPIPE too
// We need to ignore it otherwise the xctest will terminate unexpectedly with exit code 13
signal(SIGPIPE, SIG_IGN)
self.unarchiveTestAppWithExtension("zip", resourceName: "SparkleTestCodeSignApp_bad_extraneous", extractedAppName: "SparkleTestCodeSignApp", expectingSuccess: false)
signal(SIGPIPE, SIG_DFL)
}
func testUnarchivingBadZipWithMissingHeaderBytes() {
// We may receive a SIGPIPE error when writing data to a pipe
// The Autoupdate installer ignores SIGPIPE too
// We need to ignore it otherwise the xctest will terminate unexpectedly with exit code 13
signal(SIGPIPE, SIG_IGN)
self.unarchiveTestAppWithExtension("zip", resourceName: "SparkleTestCodeSignApp_bad_header", extractedAppName: "SparkleTestCodeSignApp", expectingSuccess: false)
signal(SIGPIPE, SIG_DFL)
}
func testUnarchivingTarDotGz()
{
self.unarchiveTestAppWithExtension("tar.gz")
}
func testUnarchivingTar()
{
self.unarchiveTestAppWithExtension("tar")
}
func testUnarchivingTarDotBz2()
{
self.unarchiveTestAppWithExtension("tar.bz2")
}
func testUnarchivingTarDotXz()
{
self.unarchiveTestAppWithExtension("tar.xz")
}
#if SPARKLE_BUILD_DMG_SUPPORT
func testUnarchivingHFSDmgWithLicenseAgreement()
{
self.unarchiveTestAppWithExtension("dmg")
}
func testUnarchivingEncryptedDmgWithLicenseAgreement()
{
self.unarchiveTestAppWithExtension("enc.dmg", password: "<PASSWORD>")
}
func testUnarchivingAPFSDMG()
{
self.unarchiveTestAppWithExtension("dmg", resourceName: "SparkleTestCodeSign_apfs")
}
#endif
#if SPARKLE_BUILD_PACKAGE_SUPPORT
func testUnarchivingFlatPackage()
{
self.unarchiveTestAppWithExtension("pkg", resourceName: "test", expectingInstallationType: SPUInstallationTypeGuidedPackage)
self.unarchiveTestAppWithExtension("pkg", resourceName: "test", expectingInstallationType: SPUInstallationTypeInteractivePackage, expectingSuccess: false)
self.unarchiveTestAppWithExtension("pkg", resourceName: "test", expectingInstallationType: SPUInstallationTypeApplication, expectingSuccess: false)
}
#endif
}
<file_sep>/Tests/SUAppcastTest.swift
//
// SUAppcastTest.swift
// Sparkle
//
// Created by Kornel on 17/02/2016.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
import XCTest
class SUAppcastTest: XCTestCase {
func testParseAppcast() {
let testURL = Bundle(for: SUAppcastTest.self).url(forResource: "testappcast", withExtension: "xml")!
do {
let testData = try Data(contentsOf: testURL)
let versionComparator = SUStandardVersionComparator.default
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
let items = appcast.items
XCTAssertEqual(4, items.count)
XCTAssertEqual("Version 2.0", items[0].title)
XCTAssertEqual("desc", items[0].itemDescription)
XCTAssertEqual("plain-text", items[0].itemDescriptionFormat)
XCTAssertEqual("Sat, 26 Jul 2014 15:20:11 +0000", items[0].dateString)
XCTAssertTrue(items[0].isCriticalUpdate)
XCTAssertEqual(items[0].versionString, "2.0")
// This is the best release matching our system version
XCTAssertEqual("Version 3.0", items[1].title)
XCTAssertEqual("desc3", items[1].itemDescription)
XCTAssertEqual("html", items[1].itemDescriptionFormat)
XCTAssertNil(items[1].dateString)
XCTAssertTrue(items[1].isCriticalUpdate)
XCTAssertEqual(items[1].phasedRolloutInterval, 86400)
XCTAssertEqual(items[1].versionString, "3.0")
XCTAssertEqual("Version 4.0", items[2].title)
XCTAssertNil(items[2].itemDescription)
XCTAssertEqual("Sat, 26 Jul 2014 15:20:13 +0000", items[2].dateString)
XCTAssertFalse(items[2].isCriticalUpdate)
XCTAssertEqual("Version 5.0", items[3].title)
XCTAssertNil(items[3].itemDescription)
XCTAssertNil(items[3].dateString)
XCTAssertFalse(items[3].isCriticalUpdate)
// Test best appcast item & a delta update item
let currentDate = Date()
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
let supportedAppcastItems = supportedAppcast.items
var deltaItem: SUAppcastItem?
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcastItems, getDeltaItem: &deltaItem, withHostVersion: "1.0", comparator: SUStandardVersionComparator())
XCTAssertEqual(bestAppcastItem, items[1])
XCTAssertEqual(deltaItem!.fileURL!.lastPathComponent, "3.0_from_1.0.patch")
XCTAssertEqual(deltaItem!.versionString, "3.0")
// Test latest delta update item available
var latestDeltaItem: SUAppcastItem?
SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcastItems, getDeltaItem: &latestDeltaItem, withHostVersion: "2.0", comparator: SUStandardVersionComparator())
XCTAssertEqual(latestDeltaItem!.fileURL!.lastPathComponent, "3.0_from_2.0.patch")
// Test a delta item that does not exist
var nonexistantDeltaItem: SUAppcastItem?
SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcastItems, getDeltaItem: &nonexistantDeltaItem, withHostVersion: "2.1", comparator: SUStandardVersionComparator())
XCTAssertNil(nonexistantDeltaItem)
} catch let err as NSError {
NSLog("%@", err)
XCTFail(err.localizedDescription)
}
}
func testChannelsAndMacOSReleases() {
let testURL = Bundle(for: SUAppcastTest.self).url(forResource: "testappcast_channels", withExtension: "xml")!
do {
let testData = try Data(contentsOf: testURL)
let versionComparator = SUStandardVersionComparator.default
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertEqual(6, appcast.items.count)
do {
let filteredAppcast = SUAppcastDriver.filterAppcast(appcast, forMacOSAndAllowedChannels: ["beta", "nightly"])
XCTAssertEqual(4, filteredAppcast.items.count)
XCTAssertEqual("2.0", filteredAppcast.items[0].versionString)
XCTAssertEqual("3.0", filteredAppcast.items[1].versionString)
XCTAssertEqual("4.0", filteredAppcast.items[2].versionString)
XCTAssertEqual("5.0", filteredAppcast.items[3].versionString)
}
do {
let filteredAppcast = SUAppcastDriver.filterAppcast(appcast, forMacOSAndAllowedChannels: [])
XCTAssertEqual(2, filteredAppcast.items.count)
XCTAssertEqual("2.0", filteredAppcast.items[0].versionString)
XCTAssertEqual("3.0", filteredAppcast.items[1].versionString)
}
do {
let filteredAppcast = SUAppcastDriver.filterAppcast(appcast, forMacOSAndAllowedChannels: ["beta"])
XCTAssertEqual(3, filteredAppcast.items.count)
XCTAssertEqual("2.0", filteredAppcast.items[0].versionString)
XCTAssertEqual("3.0", filteredAppcast.items[1].versionString)
XCTAssertEqual("4.0", filteredAppcast.items[2].versionString)
}
do {
let filteredAppcast = SUAppcastDriver.filterAppcast(appcast, forMacOSAndAllowedChannels: ["nightly"])
XCTAssertEqual(3, filteredAppcast.items.count)
XCTAssertEqual("2.0", filteredAppcast.items[0].versionString)
XCTAssertEqual("3.0", filteredAppcast.items[1].versionString)
XCTAssertEqual("5.0", filteredAppcast.items[2].versionString)
}
do {
let filteredAppcast = SUAppcastDriver.filterAppcast(appcast, forMacOSAndAllowedChannels: ["madeup"])
XCTAssertEqual("2.0", filteredAppcast.items[0].versionString)
XCTAssertEqual("3.0", filteredAppcast.items[1].versionString)
XCTAssertEqual(2, filteredAppcast.items.count)
}
} catch let err as NSError {
NSLog("%@", err)
XCTFail(err.localizedDescription)
}
}
func testCriticalUpdateVersion() {
let testURL = Bundle(for: SUAppcastTest.self).url(forResource: "testappcast", withExtension: "xml")!
do {
let testData = try Data(contentsOf: testURL)
let versionComparator = SUStandardVersionComparator.default
// If critical update version is 1.5 and host version is 1.0, update should be marked critical
do {
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertTrue(appcast.items[0].isCriticalUpdate)
}
// If critical update version is 1.5 and host version is 1.5, update should not be marked critical
do {
let hostVersion = "1.5"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertFalse(appcast.items[0].isCriticalUpdate)
}
// If critical update version is 1.5 and host version is 1.6, update should not be marked critical
do {
let hostVersion = "1.6"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertFalse(appcast.items[0].isCriticalUpdate)
}
} catch let err as NSError {
NSLog("%@", err)
XCTFail(err.localizedDescription)
}
}
func testInformationalUpdateVersions() {
let testURL = Bundle(for: SUAppcastTest.self).url(forResource: "testappcast_info_updates", withExtension: "xml")!
do {
let testData = try Data(contentsOf: testURL)
let versionComparator = SUStandardVersionComparator.default
// Test informational updates from version 1.0
do {
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertFalse(appcast.items[0].isInformationOnlyUpdate)
XCTAssertFalse(appcast.items[1].isInformationOnlyUpdate)
XCTAssertTrue(appcast.items[2].isInformationOnlyUpdate)
XCTAssertTrue(appcast.items[3].isInformationOnlyUpdate)
// Test delta updates inheriting informational only updates
do {
let deltaUpdate = appcast.items[2].deltaUpdates!["2.0"]!
XCTAssertTrue(deltaUpdate.isInformationOnlyUpdate)
}
}
// Test informational updates from version 2.3
do {
let hostVersion = "2.3"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertFalse(appcast.items[1].isInformationOnlyUpdate)
}
// Test informational updates from version 2.4
do {
let hostVersion = "2.4"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertTrue(appcast.items[1].isInformationOnlyUpdate)
}
// Test informational updates from version 2.5
do {
let hostVersion = "2.5"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertTrue(appcast.items[1].isInformationOnlyUpdate)
}
// Test informational updates from version 2.6
do {
let hostVersion = "2.6"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertFalse(appcast.items[1].isInformationOnlyUpdate)
}
// Test informational updates from version 0.5
do {
let hostVersion = "0.5"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertFalse(appcast.items[1].isInformationOnlyUpdate)
}
// Test informational updates from version 0.4
do {
let hostVersion = "0.4"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertTrue(appcast.items[1].isInformationOnlyUpdate)
}
// Test informational updates from version 0.0
do {
let hostVersion = "0.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertTrue(appcast.items[1].isInformationOnlyUpdate)
}
} catch let err as NSError {
NSLog("%@", err)
XCTFail(err.localizedDescription)
}
}
func testMinimumAutoupdateVersion() {
let testURL = Bundle(for: SUAppcastTest.self).url(forResource: "testappcast_minimumAutoupdateVersion", withExtension: "xml")!
do {
let testData = try Data(contentsOf: testURL)
let versionComparator = SUStandardVersionComparator()
do {
// Test appcast without a filter
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertEqual(2, appcast.items.count)
}
let currentDate = Date()
// Because 3.0 has minimum autoupdate version of 2.0, we should be offered 2.0
do {
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "2.0")
}
// We should be offered 3.0 if host version is 2.0
do {
let hostVersion = "2.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(2, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "3.0")
}
// We should be offered 3.0 if host version is 2.5
do {
let hostVersion = "2.5"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(2, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "3.0")
}
// Because 3.0 has minimum autoupdate version of 2.0, we would be be offered 2.0, but not if it has been skipped
do {
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
// There should be no items if 2.0 is skipped from 1.0 and 3.0 fails minimum autoupdate version
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: "2.0", majorVersion: nil, majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(0, supportedAppcast.items.count)
}
// Try again but allowing minimum autoupdate version to fail
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: "2.0", majorVersion: nil, majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(1, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "3.0")
}
// Allow minimum autoupdate version to fail and only skip 3.0
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: nil, majorVersion: "3.0", majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(1, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "2.0")
}
// Allow minimum autoupdate version to fail skipping both 2.0 and 3.0
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: "2.0", majorVersion: "3.0", majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(0, supportedAppcast.items.count)
}
// Allow minimum autoupdate version to fail and only skip "2.5"
// This should implicitly only skip 2.0
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: "2.5", majorVersion: nil, majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(1, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "3.0")
}
// This should not skip anything but require passing minimum autoupdate version
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: "1.5", majorVersion: nil, majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "2.0")
}
// This should not skip anything but allow failing minimum autoupdate version
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: "1.5", majorVersion: nil, majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(2, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "3.0")
}
// This should not skip anything but require passing minimum autoupdate version
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: "1.5", majorVersion: "1.0", majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "2.0")
}
// This should not skip anything but allow failing minimum autoupdate version
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: "1.5", majorVersion: "1.0", majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(2, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "3.0")
}
}
} catch let err as NSError {
NSLog("%@", err)
XCTFail(err.localizedDescription)
}
}
func testMinimumAutoupdateVersionAdvancedSkipping() {
let testURL = Bundle(for: SUAppcastTest.self).url(forResource: "testappcast_minimumAutoupdateVersionSkipping", withExtension: "xml")!
do {
let testData = try Data(contentsOf: testURL)
let versionComparator = SUStandardVersionComparator()
do {
// Test appcast without a filter
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
XCTAssertEqual(5, appcast.items.count)
}
let currentDate = Date()
// Because 3.0 has minimum autoupdate version of 3.0, and 4.0 has minimum autoupdate version of 4.0, we should be offered 2.0
do {
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "2.0")
}
// Allow minimum autoupdate version to fail and only skip major version "3.0"
// This should skip all 3.x versions, but not 4.x versions nor 2.x versions
do {
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
let skippedUpdate = SPUSkippedUpdate(minorVersion: nil, majorVersion: "3.0", majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(3, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "4.1")
}
// Allow minimum autoupdate version to pass and only skip major version "3.0"
// This should only return back the latest minor version available
do {
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
let skippedUpdate = SPUSkippedUpdate(minorVersion: nil, majorVersion: "3.0", majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "2.0")
}
// Allow minimum autoupdate version to fail and only skip major version "4.0"
// This should skip all 3.x versions and 4.x versions but not 2.x versions
do {
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
let skippedUpdate = SPUSkippedUpdate(minorVersion: nil, majorVersion: "4.0", majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(1, supportedAppcast.items.count)
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "2.0")
}
} catch let err as NSError {
NSLog("%@", err)
XCTFail(err.localizedDescription)
}
}
func testMinimumAutoupdateVersionIgnoringSkipping() {
let testURL = Bundle(for: SUAppcastTest.self).url(forResource: "testappcast_minimumAutoupdateVersionSkipping2", withExtension: "xml")!
do {
let testData = try Data(contentsOf: testURL)
let versionComparator = SUStandardVersionComparator()
let currentDate = Date()
do {
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
// Allow minimum autoupdate version to fail and only skip major version "3.0" with no subrelease version
// This should skip all 3.x versions except for 3.9 which ignores skipped upgrades below 3.5, but not 4.x versions nor 2.x versions
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: nil, majorVersion: "3.0", majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(4, supportedAppcast.items.count)
XCTAssertEqual(supportedAppcast.items[0].versionString, "4.1")
XCTAssertEqual(supportedAppcast.items[1].versionString, "4.0")
XCTAssertEqual(supportedAppcast.items[2].versionString, "3.9")
XCTAssertEqual(supportedAppcast.items[3].versionString, "2.0")
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "4.1")
}
// Allow minimum autoupdate version to fail and only skip major version "3.0" with subrelease version 3.4
// This should skip all 3.x versions except for 3.9 which ignores skipped upgrades below 3.5, but not 4.x versions nor 2.x versions
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: nil, majorVersion: "3.4", majorSubreleaseVersion: nil)
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(4, supportedAppcast.items.count)
XCTAssertEqual(supportedAppcast.items[0].versionString, "4.1")
XCTAssertEqual(supportedAppcast.items[1].versionString, "4.0")
XCTAssertEqual(supportedAppcast.items[2].versionString, "3.9")
XCTAssertEqual(supportedAppcast.items[3].versionString, "2.0")
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "4.1")
}
// Allow minimum autoupdate version to fail and only skip major version "3.0" with subrelease version 3.5
// This should skip all 3.x versions, but not 4.x versions nor 2.x versions
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: nil, majorVersion: "3.0", majorSubreleaseVersion: "3.5")
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(3, supportedAppcast.items.count)
XCTAssertEqual(supportedAppcast.items[0].versionString, "4.1")
XCTAssertEqual(supportedAppcast.items[1].versionString, "4.0")
XCTAssertEqual(supportedAppcast.items[2].versionString, "2.0")
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "4.1")
}
// Allow minimum autoupdate version to fail and only skip major version "3.0" with subrelease version 3.5.1
// This should skip all 3.x versions, but not 4.x versions nor 2.x versions
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: nil, majorVersion: "3.0", majorSubreleaseVersion: "3.5.1")
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(3, supportedAppcast.items.count)
XCTAssertEqual(supportedAppcast.items[0].versionString, "4.1")
XCTAssertEqual(supportedAppcast.items[1].versionString, "4.0")
XCTAssertEqual(supportedAppcast.items[2].versionString, "2.0")
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "4.1")
}
// Allow minimum autoupdate version to fail and only skip major version "4.0" with subrelease version 4.0
// This should skip all 3.x versions and 4.x versions, but not 2.x versions
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: nil, majorVersion: "4.0", majorSubreleaseVersion: "4.0")
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(1, supportedAppcast.items.count)
XCTAssertEqual(supportedAppcast.items[0].versionString, "2.0")
let bestAppcastItem = SUAppcastDriver.bestItem(fromAppcastItems: supportedAppcast.items, getDeltaItem: nil, withHostVersion: hostVersion, comparator: versionComparator)
XCTAssertEqual(bestAppcastItem.versionString, "2.0")
}
// Allow minimum autoupdate version to fail and only skip major version "4.0" with subrelease version 4.0, and skip minor version 2.1
// This should skip everything
do {
let skippedUpdate = SPUSkippedUpdate(minorVersion: "2.1", majorVersion: "4.0", majorSubreleaseVersion: "4.0")
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: skippedUpdate, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: false)
XCTAssertEqual(0, supportedAppcast.items.count)
}
}
} catch let err as NSError {
NSLog("%@", err)
XCTFail(err.localizedDescription)
}
}
func testPhasedGroupRollouts() {
let testURL = Bundle(for: SUAppcastTest.self).url(forResource: "testappcast_phasedRollout", withExtension: "xml")!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E, dd MMM yyyy HH:mm:ss Z"
do {
let testData = try Data(contentsOf: testURL)
let versionComparator = SUStandardVersionComparator()
// Because 3.0 has minimum autoupdate version of 2.0, we should be offered 2.0
do {
let hostVersion = "1.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
do {
// Test no group
let group: NSNumber? = nil
let currentDate = Date()
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
XCTAssertEqual("2.0", supportedAppcast.items[0].versionString)
}
do {
// Test 0 group with current date (way ahead of pubDate)
let group: NSNumber? = nil
let currentDate = Date()
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
}
do {
// Test 6th group with current date (way ahead of pubDate)
let group = 6 as NSNumber
let currentDate = Date()
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
}
do {
let currentDate = dateFormatter.date(from: "Wed, 23 Jul 2014 15:20:11 +0000")!
do {
// Test group 0 with current date 3 days before rollout
// No update should be found
let group = 0 as NSNumber
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(0, supportedAppcast.items.count)
}
do {
// Test group 6 with current date 3 days before rollout
// No update should be found still
let group = 6 as NSNumber
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(0, supportedAppcast.items.count)
}
}
do {
let currentDate = dateFormatter.date(from: "Mon, 28 Jul 2014 15:20:11 +0000")!
do {
// Test group 0 with current date 2 days after rollout
let group = 0 as NSNumber
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
}
do {
// Test group 1 with current date 3 days after rollout
let group = 1 as NSNumber
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
}
do {
// Test group 2 with current date 3 days after rollout
let group = 2 as NSNumber
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
}
do {
// Test group 3 with current date 3 days after rollout
let group = 3 as NSNumber
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(0, supportedAppcast.items.count)
}
do {
// Test group 6 with current date 3 days after rollout
let group = 6 as NSNumber
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(0, supportedAppcast.items.count)
}
}
// Test critical updates which ignore phased rollouts
do {
let hostVersion = "2.0"
let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator)
let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver)
do {
// Test no group
let group: NSNumber? = nil
let currentDate = Date()
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(2, supportedAppcast.items.count)
XCTAssertEqual("3.0", supportedAppcast.items[0].versionString)
}
do {
let currentDate = dateFormatter.date(from: "Wed, 23 Jul 2014 15:20:11 +0000")!
do {
// Test group 0 with current date 3 days before rollout
let group = 0 as NSNumber
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
XCTAssertEqual("3.0", supportedAppcast.items[0].versionString)
}
}
do {
let currentDate = dateFormatter.date(from: "Mon, 28 Jul 2014 15:20:11 +0000")!
do {
// Test group 6 with current date 3 days after rollout
let group = 6 as NSNumber
let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: group, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testOSVersion: true, testMinimumAutoupdateVersion: true)
XCTAssertEqual(1, supportedAppcast.items.count)
XCTAssertEqual("3.0", supportedAppcast.items[0].versionString)
}
}
}
}
} catch let err as NSError {
NSLog("%@", err)
XCTFail(err.localizedDescription)
}
}
func testParseAppcastWithLocalizedReleaseNotes() {
let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "testlocalizedreleasenotesappcast",
ofType: "xml")!
let testFileUrl = URL(fileURLWithPath: testFile)
XCTAssertNotNil(testFileUrl)
do {
let testFileData = try Data(contentsOf: testFileUrl)
let stateResolver = SPUAppcastItemStateResolver(hostVersion: "1.0", applicationVersionComparator: SUStandardVersionComparator.default, standardVersionComparator: SUStandardVersionComparator.default)
let appcast = try SUAppcast(xmlData: testFileData, relativeTo: testFileUrl, stateResolver: stateResolver)
let items = appcast.items
XCTAssertEqual("https://sparkle-project.org/#localized_notes_link_works", items[0].releaseNotesURL!.absoluteString)
} catch let err as NSError {
NSLog("%@", err)
XCTFail(err.localizedDescription)
}
}
func testNamespaces() {
let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "testnamespaces", ofType: "xml")!
let testData = NSData(contentsOfFile: testFile)!
do {
let stateResolver = SPUAppcastItemStateResolver(hostVersion: "1.0", applicationVersionComparator: SUStandardVersionComparator.default, standardVersionComparator: SUStandardVersionComparator.default)
let appcast = try SUAppcast(xmlData: testData as Data, relativeTo: nil, stateResolver: stateResolver)
let items = appcast.items
XCTAssertEqual(2, items.count)
XCTAssertEqual("Version 2.0", items[1].title)
XCTAssertEqual("desc", items[1].itemDescription)
XCTAssertNotNil(items[0].releaseNotesURL)
XCTAssertEqual("https://sparkle-project.org/#works", items[0].releaseNotesURL!.absoluteString)
} catch let err as NSError {
NSLog("%@", err)
XCTFail(err.localizedDescription)
}
}
func testLinks() {
let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "test-links", ofType: "xml")!
let testData = NSData(contentsOfFile: testFile)!
do {
let baseURL: URL? = nil
let stateResolver = SPUAppcastItemStateResolver(hostVersion: "1.0", applicationVersionComparator: SUStandardVersionComparator.default, standardVersionComparator: SUStandardVersionComparator.default)
let appcast = try SUAppcast(xmlData: testData as Data, relativeTo: baseURL, stateResolver: stateResolver)
let items = appcast.items
XCTAssertEqual(3, items.count)
// Test https
XCTAssertEqual("https://sparkle-project.org/notes/relnote-3.0.txt", items[0].releaseNotesURL?.absoluteString)
XCTAssertEqual("https://sparkle-project.org/fullnotes.txt", items[0].fullReleaseNotesURL?.absoluteString)
XCTAssertEqual("https://sparkle-project.org", items[0].infoURL?.absoluteString)
XCTAssertEqual("https://sparkle-project.org/release-3.0.zip", items[0].fileURL?.absoluteString)
// Test http
XCTAssertEqual("http://sparkle-project.org/notes/relnote-2.0.txt", items[1].releaseNotesURL?.absoluteString)
XCTAssertEqual("http://sparkle-project.org/fullnotes.txt", items[1].fullReleaseNotesURL?.absoluteString)
XCTAssertEqual("http://sparkle-project.org", items[1].infoURL?.absoluteString)
XCTAssertEqual("http://sparkle-project.org/release-2.0.zip", items[1].fileURL?.absoluteString)
// Test bad file URLs
XCTAssertEqual(nil, items[2].releaseNotesURL?.absoluteString)
XCTAssertEqual(nil, items[2].fullReleaseNotesURL?.absoluteString)
XCTAssertEqual(nil, items[2].infoURL?.absoluteString)
XCTAssertEqual("https://sparkle-project.org/release-1.0.zip", items[2].fileURL?.absoluteString)
} catch let err as NSError {
NSLog("%@", err)
XCTFail(err.localizedDescription)
}
}
func testRelativeURLs() {
let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "test-relative-urls", ofType: "xml")!
let testData = NSData(contentsOfFile: testFile)!
do {
let baseURL = URL(string: "https://fake.sparkle-project.org/updates/index.xml")!
let stateResolver = SPUAppcastItemStateResolver(hostVersion: "1.0", applicationVersionComparator: SUStandardVersionComparator.default, standardVersionComparator: SUStandardVersionComparator.default)
let appcast = try SUAppcast(xmlData: testData as Data, relativeTo: baseURL, stateResolver: stateResolver)
let items = appcast.items
XCTAssertEqual(4, items.count)
XCTAssertEqual("https://fake.sparkle-project.org/updates/release-3.0.zip", items[0].fileURL?.absoluteString)
XCTAssertEqual("https://fake.sparkle-project.org/updates/notes/relnote-3.0.txt", items[0].releaseNotesURL?.absoluteString)
XCTAssertEqual("https://fake.sparkle-project.org/info/info-2.0.txt", items[1].infoURL?.absoluteString)
XCTAssertEqual("https://fake.sparkle-project.org/updates/notes/fullnotes.txt", items[2].fullReleaseNotesURL?.absoluteString)
// If a different base URL is in the feed, we should respect the base URL in the feed
XCTAssertEqual("https://sparkle-project.org/releasenotes.html", items[3].fullReleaseNotesURL?.absoluteString)
} catch let err as NSError {
NSLog("%@", err)
XCTFail(err.localizedDescription)
}
}
func testDangerousLink() {
let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "test-dangerous-link", ofType: "xml")!
let testData = NSData(contentsOfFile: testFile)!
do {
let baseURL: URL? = nil
let stateResolver = SPUAppcastItemStateResolver(hostVersion: "1.0", applicationVersionComparator: SUStandardVersionComparator.default, standardVersionComparator: SUStandardVersionComparator.default)
let _ = try SUAppcast(xmlData: testData as Data, relativeTo: baseURL, stateResolver: stateResolver)
XCTFail("Appcast creation should fail when encountering dangerous link")
} catch let err as NSError {
NSLog("Expected error: %@", err)
XCTAssertNotNil(err)
}
}
}
<file_sep>/generate_appcast/Unarchive.swift
//
// Created by Kornel on 22/12/2016.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
import Foundation
func unarchive(itemPath: URL, archiveDestDir: URL, callback: @escaping (Error?) -> Void) {
let fileManager = FileManager.default
let tempDir = archiveDestDir.appendingPathExtension("tmp")
let itemCopy = tempDir.appendingPathComponent(itemPath.lastPathComponent)
_ = try? fileManager.createDirectory(at: tempDir, withIntermediateDirectories: true, attributes: [:])
do {
do {
try fileManager.linkItem(at: itemPath, to: itemCopy)
} catch {
try fileManager.copyItem(at: itemPath, to: itemCopy)
}
if let unarchiver = SUUnarchiver.unarchiver(forPath: itemCopy.path, updatingHostBundlePath: nil, decryptionPassword: nil, expectingInstallationType: SPUInstallationTypeApplication) {
unarchiver.unarchive(completionBlock: { (error: Error?) in
if error != nil {
callback(error)
return
}
_ = try? fileManager.removeItem(at: itemCopy)
do {
try fileManager.moveItem(at: tempDir, to: archiveDestDir)
callback(nil)
} catch {
callback(error)
}
}, progressBlock: nil)
} else {
_ = try? fileManager.removeItem(at: itemCopy)
callback(makeError(code: .unarchivingError, "Not a supported archive format: \(itemCopy)"))
}
} catch {
_ = try? fileManager.removeItem(at: tempDir)
callback(error)
}
}
func unarchiveUpdates(archivesSourceDir: URL, archivesDestDir: URL, disableNestedCodeCheck: Bool, verbose: Bool) throws -> [ArchiveItem] {
if verbose {
print("Unarchiving to temp directory", archivesDestDir.path)
}
let group = DispatchGroup()
let fileManager = FileManager.default
// Create a dictionary of archive destination directories -> archive source path
// so we can ignore duplicate archive entries before trying to unarchive archives in parallel
var fileEntries: [URL: URL] = [:]
let dir = try fileManager.contentsOfDirectory(atPath: archivesSourceDir.path)
for item in dir.filter({ !$0.hasPrefix(".") && !$0.hasSuffix(".delta") && !$0.hasSuffix(".xml") && !$0.hasSuffix(".html") && !$0.hasSuffix(".txt") }) {
let itemPath = archivesSourceDir.appendingPathComponent(item)
// Ignore directories
var isDir: ObjCBool = false
if fileManager.fileExists(atPath: itemPath.path, isDirectory: &isDir) && isDir.boolValue {
continue
}
let archiveDestDir: URL
if let hash = itemPath.sha256String() {
archiveDestDir = archivesDestDir.appendingPathComponent(hash)
} else {
archiveDestDir = archivesDestDir.appendingPathComponent(itemPath.lastPathComponent)
}
// Ignore duplicate archives
if let existingItemPath = fileEntries[archiveDestDir] {
throw makeError(code: .appcastError, "Duplicate update archives are not supported. Found '\(existingItemPath.lastPathComponent)' and '\(itemPath.lastPathComponent)'. Please remove one of them from the appcast generation directory.")
}
fileEntries[archiveDestDir] = itemPath
}
var unarchived: [String: ArchiveItem] = [:]
var updateParseError: Error? = nil
var running = 0
for (archiveDestDir, itemPath) in fileEntries {
let addItem = { (validateBundle: Bool) in
do {
let item = try ArchiveItem(fromArchive: itemPath, unarchivedDir: archiveDestDir, validateBundle: validateBundle, disableNestedCodeCheck: disableNestedCodeCheck)
if verbose {
print("Found archive", item)
}
objc_sync_enter(unarchived)
// Make sure different archives don't contain the same update too
if let existingArchive = unarchived[item.version] {
updateParseError = makeError(code: .appcastError, "Duplicate updates are not supported. Found archives '\(existingArchive.archivePath.lastPathComponent)' and '\(itemPath.lastPathComponent)' which contain the same bundle version. Please remove one of these archives from the appcast generation directory.")
} else {
unarchived[item.version] = item
}
objc_sync_exit(unarchived)
} catch {
print("Skipped", itemPath.lastPathComponent, error)
}
}
if fileManager.fileExists(atPath: archiveDestDir.path) {
addItem(false)
} else {
group.enter()
unarchive(itemPath: itemPath, archiveDestDir: archiveDestDir) { (error: Error?) in
if let error = error {
print("Could not unarchive", itemPath.path, error)
} else {
addItem(true)
}
group.leave()
}
}
// Crude limit of concurrency
running += 1
if running >= 8 {
running = 0
group.wait()
}
}
group.wait()
if let updateParseError = updateParseError {
throw updateParseError
}
return Array(unarchived.values)
}
<file_sep>/generate_appcast/main.swift
//
// main.swift
// Appcast
//
// Created by Kornel on 20/12/2016.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
import Foundation
import ArgumentParser
func loadPrivateKeys(_ account: String, _ privateDSAKey: SecKey?, _ privateEdString: String?) -> PrivateKeys {
var privateEdKey: Data?
var publicEdKey: Data?
var item: CFTypeRef?
var keys: Data?
// private + public key is provided as argument
if let privateEdString = privateEdString {
if privateEdString.count == 128, let data = Data(base64Encoded: privateEdString) {
keys = data
} else {
print("Warning: Private key not found in the argument. Please provide a valid key.")
}
}
// get keys from kechain instead
else {
let res = SecItemCopyMatching([
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "https://sparkle-project.org",
kSecAttrAccount as String: account,
kSecAttrProtocol as String: kSecAttrProtocolSSH,
kSecReturnData as String: kCFBooleanTrue!,
] as CFDictionary, &item)
if res == errSecSuccess, let encoded = item as? Data, let data = Data(base64Encoded: encoded) {
keys = data
} else {
print("Warning: Private key for account \(account) not found in the Keychain (\(res)). Please run the generate_keys tool")
}
}
if let keys = keys {
privateEdKey = keys[0..<64]
publicEdKey = keys[64...]
}
return PrivateKeys(privateDSAKey: privateDSAKey, privateEdKey: privateEdKey, publicEdKey: publicEdKey)
}
let DEFAULT_MAX_CDATA_THRESHOLD = 1000
struct GenerateAppcast: ParsableCommand {
static let programName = "generate_appcast"
static let programNamePath: String = CommandLine.arguments.first ?? "./\(programName)"
static let cacheDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("Sparkle_generate_appcast")
static let oldFilesDirectoryName = "old_updates"
static let DEFAULT_MAX_VERSIONS_PER_BRANCH_IN_FEED = 3
static let DEFAULT_MAXIMUM_DELTAS = 5
@Option(help: ArgumentHelp("The account name in your keychain associated with your private EdDSA (ed25519) key to use for signing new updates."))
var account : String = "ed25519"
@Option(name: .customLong("ed-key-file"), help: ArgumentHelp("Path to the private EdDSA key file. If not specified, the private EdDSA key will be read from the Keychain instead. '-' can be used to echo the EdDSA key from a 'secret' environment variable to the standard input stream. For example: echo \"$PRIVATE_KEY_SECRET\" | ./\(programName) --ed-key-file -", valueName: "private-EdDSA-key-file"))
var privateEdKeyPath: String?
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
@Option(name: .customShort("f"), help: ArgumentHelp("Path to the private DSA key file. Only use this option for transitioning to EdDSA from older updates.", valueName: "private-dsa-key-file"), transform: { URL(fileURLWithPath: $0) })
var privateDSAKeyURL: URL?
@Option(name: .customShort("n"), help: ArgumentHelp("The name of the private DSA key. This option must be used together with `-k`. Only use this option for transitioning to EdDSA from older updates.", valueName: "dsa-key-name"))
var privateDSAKeyName: String?
#endif
@Option(name: .customShort("s"), help: ArgumentHelp("(DEPRECATED): The private EdDSA string (128 characters). This option is deprecated. Please use the Keychain, or pass the key as standard input when using the --ed-key-file - option instead.", valueName: "private-EdDSA-key"))
var privateEdString : String?
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
@Option(name: .customShort("k"), help: ArgumentHelp("The path to the keychain to look up the private DSA key. This option must be used together with `-n`. Only use this option for transitioning to EdDSA from older updates.", valueName: "keychain-for-dsa"), transform: { URL(fileURLWithPath: $0) })
var keychainURL: URL?
#endif
@Option(name: .customLong("download-url-prefix"), help: ArgumentHelp("A URL that will be used as prefix for the URL from where updates will be downloaded.", valueName: "url"), transform: { URL(string: $0) })
var downloadURLPrefix : URL?
@Option(name: .customLong("release-notes-url-prefix"), help: ArgumentHelp("A URL that will be used as prefix for constructing URLs for release notes.", valueName: "url"), transform: { URL(string: $0) })
var releaseNotesURLPrefix : URL?
@Flag(name: .customLong("embed-release-notes"), help: ArgumentHelp("Embed release notes in a new update's description. By default, release note files are only embedded if they are HTML and do not include DOCTYPE or body tags. This flag forces release note files for newly created updates to always be embedded."))
var embedReleaseNotes : Bool = false
@Option(name: .customLong("full-release-notes-url"), help: ArgumentHelp("A URL that will be used for the full release notes.", valueName: "url"))
var fullReleaseNotesURL: String?
@Option(name: .long, help: ArgumentHelp("A URL to the application's website which Sparkle may use for directing users to if they cannot download a new update from within the application. This will be used for new generated update items. By default, no product link is used.", valueName: "link"))
var link: String?
@Option(name: .long, help: ArgumentHelp("An optional comma delimited list of application versions (specified by CFBundleVersion) to generate new update items for. By default, new update items are inferred from the available archives and current feed. Use this option if you need to insert only a specific new version or insert an old update in the feed at a different branch point (e.g. with a different minimum OS version or channel).", valueName: "versions"), transform: { Set($0.components(separatedBy: ",")) })
var versions: Set<String>?
@Option(name: .customLong("maximum-versions"), help: ArgumentHelp("The maximum number of versions to preserve in the generated appcast for each branch point (e.g. with a different minimum OS requirement). If this value is 0, then all items in the appcast are preserved.", valueName: "maximum-versions"), transform: { value -> Int in
if let intValue = Int(value) {
return (intValue <= 0) ? Int.max : intValue
} else {
return DEFAULT_MAX_VERSIONS_PER_BRANCH_IN_FEED
}
})
var maxVersionsPerBranchInFeed: Int = DEFAULT_MAX_VERSIONS_PER_BRANCH_IN_FEED
@Option(name: .long, help: ArgumentHelp("The maximum number of delta items to create for the latest update for each branch point (e.g. with a different minimum OS requirement).", valueName: "maximum-deltas"))
var maximumDeltas: Int = DEFAULT_MAXIMUM_DELTAS
@Option(name: .long, help: ArgumentHelp(COMPRESSION_METHOD_ARGUMENT_DESCRIPTION, valueName: "delta-compression"))
var deltaCompression: String = "default"
@Option(name: .long, help: .hidden)
var deltaCompressionLevel: UInt8 = 0
@Option(name: .long, help: ArgumentHelp("The Sparkle channel name that will be used for generating new updates. By default, no channel is used. Old applications need to be using Sparkle 2 to use this feature.", valueName: "channel-name"))
var channel: String?
@Option(name: .long, help: ArgumentHelp("The last major or minimum autoupdate sparkle:version that will be used for generating new updates. By default, no last major version is used.", valueName: "major-version"))
var majorVersion: String?
@Option(name: .long, help: ArgumentHelp("Ignore skipped major upgrades below this specified version. Only applicable for major upgrades.", valueName: "below-version"))
var ignoreSkippedUpgradesBelowVersion: String?
@Option(name: .long, help: ArgumentHelp("The phased rollout interval in seconds that will be used for generating new updates. By default, no phased rollout interval is used.", valueName: "phased-rollout-interval"), transform: { Int($0) })
var phasedRolloutInterval: Int?
@Option(name: .long, help: ArgumentHelp("The last critical update sparkle:version that will be used for generating new updates. An empty string argument will treat this update as critical coming from any application version. By default, no last critical update version is used. Old applications need to be using Sparkle 2 to use this feature.", valueName: "critical-update-version"))
var criticalUpdateVersion: String?
@Option(name: .long, help: ArgumentHelp("A comma delimited list of application sparkle:version's that will see newly generated updates as being informational only. An empty string argument will treat this update as informational coming from any application version. Prefix a version string with '<' to indicate (eg \"<2.5\") to indicate older versions than the one specified should treat the update as informational only. By default, updates are not informational only. --link must also be provided. Old applications need to be using Sparkle 2 to use this feature, and 2.1 or later to use the '<' upper bound feature.", valueName: "informational-update-versions"), transform: { $0.components(separatedBy: ",").filter({$0.count > 0}) })
var informationalUpdateVersions: [String]?
@Flag(name: .customLong("auto-prune-update-files"), help: ArgumentHelp("Automatically remove old update files in \(oldFilesDirectoryName) that haven't been touched in 2 weeks"))
var autoPruneUpdates: Bool = false
@Option(name: .customShort("o"), help: ArgumentHelp("Path to filename for the generated appcast (allowed when only one will be created).", valueName: "output-path"), transform: { URL(fileURLWithPath: $0) })
var outputPathURL: URL?
@Argument(help: "The path to the directory containing the update archives and delta files.", transform: { URL(fileURLWithPath: $0, isDirectory: true) })
var archivesSourceDir: URL
@Flag(help: .hidden)
var verbose: Bool = false
@Flag(name: .customLong("disable-nested-code-check"), help: .hidden)
var disableNestedCodeCheck: Bool = false
static var configuration = CommandConfiguration(
abstract: "Generate appcast from a directory of Sparkle update archives.",
discussion: """
Appcast files and deltas will be written to the archives directory.
If an appcast file is already present in the archives directory, that file will be re-used and updated with new entries.
Otherwise, a new appcast file will be generated and written.
Old updates are automatically removed from the generated appcast feed and their update files are moved to \(oldFilesDirectoryName)/
If --auto-prune-update-files is passed, old update files in this directory are deleted after 2 weeks.
You may want to exclude files from this directory from being uploaded.
Use the --versions option if you need to insert an update that is older than the latest update in your feed, or
if you need to insert only a specific new version with certain parameters.
.html or .txt files that have the same filename as an archive (except for the file extension) will be used for release notes for that item.
For HTML release notes, if the contents of these files do not include a DOCTYPE or body tags, they will be treated as embedded CDATA release notes.
Release notes for new items can be forced to be embedded by passing --embed-release-notes
For new update entries, Sparkle infers the minimum system OS requirement based on your update's LSMinimumSystemVersion provided
by your application's Info.plist. If none is found, \(programName) defaults to Sparkle's own minimum system requirement (macOS 10.13).
An example of an archives directory may look like:
./my-app-release-zipfiles/
MyApp 1.0.zip
MyApp 1.0.html
MyApp 1.1.zip
MyApp 1.1.html
appcast.xml
\(oldFilesDirectoryName)/
EXAMPLES:
\(programNamePath) ./my-app-release-zipfiles/
\(programNamePath) -o appcast-name.xml ./my-app-release-zipfiles/
For more advanced options that can be used for publishing updates, see https://sparkle-project.org/documentation/publishing/ for further documentation.
Extracted archives that are needed are cached in \((cacheDirectory.path as NSString).abbreviatingWithTildeInPath) to avoid re-computation in subsequent runs.
Note that \(programName) does not support package-based (.pkg) updates.
""")
func validate() throws {
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
guard (keychainURL == nil) == (privateDSAKeyName == nil) else {
throw ValidationError("Both -n <dsa-key-name> and -k <keychain> options must be provided together, or neither should be provided.")
}
// Both keychain/dsa key name options, and private dsa key file options cannot coexist
guard (keychainURL == nil) || (privateDSAKeyURL == nil) else {
throw ValidationError("-f <private-dsa-key-file> cannot be provided if -n <dsa-key-name> and -k <keychain> is provided")
}
#endif
guard (privateEdKeyPath == nil) || (privateEdString == nil) else {
throw ValidationError("--ed-key-file <private-EdDSA-key-file> cannot be provided if -s <private-EdDSA-key> is provided")
}
if let versions = versions {
guard versions.count > 0 else {
throw ValidationError("--versions must specify at least one application version.")
}
}
guard (informationalUpdateVersions == nil) || (link != nil) else {
throw ValidationError("--link must be specified if --informational-update-versions is specified.")
}
guard deltaCompressionLevel >= 0 && deltaCompressionLevel <= 9 else {
throw ValidationError("Invalid --delta-compression-level value was passed.")
}
var validCompression: ObjCBool = false
let _ = deltaCompressionModeFromDescription(deltaCompression, &validCompression)
if !validCompression.boolValue {
throw ValidationError("Invalid --delta-compression \(deltaCompression) was passed.")
}
}
func run() throws {
// Extract the keys
let privateDSAKey : SecKey?
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
if let privateDSAKeyURL = privateDSAKeyURL {
do {
privateDSAKey = try loadPrivateDSAKey(at: privateDSAKeyURL)
} catch {
print("Unable to load DSA private key from", privateDSAKeyURL.path, "\n", error)
throw ExitCode(1)
}
} else if let keychainURL = keychainURL, let privateDSAKeyName = privateDSAKeyName {
do {
privateDSAKey = try loadPrivateDSAKey(named: privateDSAKeyName, fromKeychainAt: keychainURL)
} catch {
print("Unable to load DSA private key '\(privateDSAKeyName)' from keychain at", keychainURL.path, "\n", error)
throw ExitCode(1)
}
} else {
privateDSAKey = nil
}
#else
privateDSAKey = nil
#endif
let privateEdKeyString: String?
if let privateEdString = privateEdString {
privateEdKeyString = privateEdString
print("Warning: The -s option for passing the private EdDSA key is insecure and deprecated. Please see its help usage for more information.")
} else if let privateEdKeyPath = privateEdKeyPath {
do {
let privateKeyString: String
if privateEdKeyPath == "-" && !FileManager.default.fileExists(atPath: privateEdKeyPath) {
if let line = readLine(strippingNewline: true) {
privateKeyString = line
} else {
print("Unable to read EdDSA private key from standard input")
throw ExitCode(1)
}
} else {
privateKeyString = try String(contentsOf: URL(fileURLWithPath: privateEdKeyPath))
}
privateEdKeyString = privateKeyString
} catch {
print("Unable to load EdDSA private key from", privateEdKeyPath, "\n", error)
throw ExitCode(1)
}
} else {
privateEdKeyString = nil
}
let keys = loadPrivateKeys(account, privateDSAKey, privateEdKeyString)
do {
let appcastsByFeed = try makeAppcasts(archivesSourceDir: archivesSourceDir, outputPathURL: outputPathURL, cacheDirectory: GenerateAppcast.cacheDirectory, keys: keys, versions: versions, maxVersionsPerBranchInFeed: maxVersionsPerBranchInFeed, newChannel: channel, majorVersion: majorVersion, maximumDeltas: maximumDeltas, deltaCompressionModeDescription: deltaCompression, deltaCompressionLevel: deltaCompressionLevel, disableNestedCodeCheck: disableNestedCodeCheck, downloadURLPrefix: downloadURLPrefix, releaseNotesURLPrefix: releaseNotesURLPrefix, verbose: verbose)
let oldFilesDirectory = archivesSourceDir.appendingPathComponent(GenerateAppcast.oldFilesDirectoryName)
let pluralizeWord = { $0 == 1 ? $1 : "\($1)s" }
for (appcastFile, appcast) in appcastsByFeed {
// If an output filename was specified, use it.
// Otherwise, use the name of the appcast file found in the archive.
let appcastDestPath = outputPathURL ?? URL(fileURLWithPath: appcastFile,
relativeTo: archivesSourceDir)
// Write the appcast
let (numNewUpdates, numExistingUpdates, numUpdatesRemoved) = try writeAppcast(appcastDestPath: appcastDestPath, appcast: appcast, fullReleaseNotesLink: fullReleaseNotesURL, preferToEmbedReleaseNotes: embedReleaseNotes, link: link, newChannel: channel, majorVersion: majorVersion, ignoreSkippedUpgradesBelowVersion: ignoreSkippedUpgradesBelowVersion, phasedRolloutInterval: phasedRolloutInterval, criticalUpdateVersion: criticalUpdateVersion, informationalUpdateVersions: informationalUpdateVersions)
// Inform the user, pluralizing "update" if necessary
let pluralizeUpdates = { pluralizeWord($0, "update") }
let newUpdatesString = pluralizeUpdates(numNewUpdates)
let existingUpdatesString = pluralizeUpdates(numExistingUpdates)
let removedUpdatesString = pluralizeUpdates(numUpdatesRemoved)
print("Wrote \(numNewUpdates) new \(newUpdatesString), updated \(numExistingUpdates) existing \(existingUpdatesString), and removed \(numUpdatesRemoved) old \(removedUpdatesString) in \(appcastFile)")
}
let (moveCount, prunedCount) = moveOldUpdatesFromAppcasts(archivesSourceDir: archivesSourceDir, oldFilesDirectory: oldFilesDirectory, cacheDirectory: GenerateAppcast.cacheDirectory, appcasts: Array(appcastsByFeed.values), autoPruneUpdates: autoPruneUpdates)
if moveCount > 0 {
print("Moved \(moveCount) old update \(pluralizeWord(moveCount, "file")) to \(oldFilesDirectory.lastPathComponent)")
}
if prunedCount > 0 {
print("Pruned \(prunedCount) old update \(pluralizeWord(prunedCount, "file"))")
}
} catch {
print("Error generating appcast from directory", archivesSourceDir.path, "\n", error)
throw ExitCode(1)
}
}
}
DispatchQueue.global().async(execute: {
GenerateAppcast.main()
CFRunLoopStop(CFRunLoopGetMain())
})
CFRunLoopRun()
<file_sep>/generate_appcast/Appcast.swift
//
// Created by Kornel on 23/12/2016.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
import Foundation
func makeError(code: SUError, _ description: String) -> NSError {
return NSError(domain: SUSparkleErrorDomain, code: Int(OSStatus(code.rawValue)), userInfo: [
NSLocalizedDescriptionKey: description,
])
}
typealias UpdateVersion = String
typealias FeedName = String
struct Appcast {
let inferredAppName: String
let versionsInFeed: [UpdateVersion]
let ignoredVersionsToInsert: Set<UpdateVersion>
let archives: [UpdateVersion: ArchiveItem]
let deltaPathsUsed: Set<String>
let deltaFromVersionsUsed: Set<UpdateVersion>
}
func makeAppcasts(archivesSourceDir: URL, outputPathURL: URL?, cacheDirectory cacheDir: URL, keys: PrivateKeys, versions: Set<String>?, maxVersionsPerBranchInFeed: Int, newChannel: String?, majorVersion: String?, maximumDeltas: Int, deltaCompressionModeDescription: String, deltaCompressionLevel: UInt8, disableNestedCodeCheck: Bool, downloadURLPrefix: URL?, releaseNotesURLPrefix: URL?, verbose: Bool) throws -> [FeedName: Appcast] {
let standardComparator = SUStandardVersionComparator()
let descendingVersionComparator: (String, String) -> Bool = {
return standardComparator.compareVersion($0, toVersion: $1) == .orderedDescending
}
let allUpdates = (try unarchiveUpdates(archivesSourceDir: archivesSourceDir, archivesDestDir: cacheDir, disableNestedCodeCheck: disableNestedCodeCheck, verbose: verbose))
.sorted(by: { descendingVersionComparator($0.version, $1.version) })
if allUpdates.count == 0 {
throw makeError(code: .noUpdateError, "No usable archives found in \(archivesSourceDir.path)")
}
// Apply download and release notes prefixes
for update in allUpdates {
update.downloadUrlPrefix = downloadURLPrefix
update.releaseNotesURLPrefix = releaseNotesURLPrefix
}
// Group updates by appcast feed
var updatesByAppcast: [FeedName: [ArchiveItem]] = [:]
for update in allUpdates {
let appcastFile = update.feedURL?.lastPathComponent ?? "appcast.xml"
updatesByAppcast[appcastFile, default: []].append(update)
}
// If a (single) output filename was specified on the command-line, but more than one
// appcast file was found in the archives, then it's an error.
if let outputPathURL = outputPathURL, updatesByAppcast.count > 1 {
throw makeError(code: .appcastError, "Cannot write to \(outputPathURL.path): multiple appcasts found")
}
let group = DispatchGroup()
var updateArchivesToSign: [ArchiveItem] = []
var appcastByFeed: [FeedName: Appcast] = [:]
for (feed, updates) in updatesByAppcast {
var archivesTable: [UpdateVersion: ArchiveItem] = [:]
for update in updates {
archivesTable[update.version] = update
}
let feedURL = outputPathURL ?? archivesSourceDir.appendingPathComponent(feed)
// Find all the update versions & branches from our existing feed (if available)
let feedUpdateBranches: [UpdateVersion: UpdateBranch]
if let reachable = try? feedURL.checkResourceIsReachable(), reachable {
feedUpdateBranches = try readAppcast(archives: archivesTable, appcastURL: feedURL)
} else {
feedUpdateBranches = [:]
}
// Find which versions are new and old but aren't in the feed and that we should ignore/skip
var ignoredVersionsToInsert: Set<UpdateVersion> = Set()
var ignoredOldVersions: Set<UpdateVersion> = Set()
if let versions = versions {
// Note for this path we may be adding old updates to ignoredVersionsToInsert too.
// It is difficult to differentiate between old and potential new updates that aren't in the feed
// As a consequence, some old updates may not be pruned with this option.
for update in updates {
if feedUpdateBranches[update.version] == nil && !versions.contains(update.version) {
ignoredVersionsToInsert.insert(update.version)
}
}
} else {
// If the user doesn't specify which versions to generate updates for,
// then by default we ignore generating updates that are less than the latest update in the existing feed
// The reason why we need to do this is because new branch-specific flags the user can specify like the channel
// or the major version will be applied to new unknown updates. We can only absolutely be sure to apply this to
// updates that are greater in version than the top of the current feed, or if the user uses --versions.
for latestUpdateCandidate in updates {
if feedUpdateBranches[latestUpdateCandidate.version] != nil {
// Found the latest update in the feed
let latestUpdateVersionInFeed = latestUpdateCandidate.version
// Filter out any new potential updates that are less than our latest update in our existing feed
for update in updates {
if feedUpdateBranches[update.version] == nil && descendingVersionComparator(latestUpdateVersionInFeed, update.version) {
ignoredOldVersions.insert(update.version)
}
}
break
}
}
}
// Find new update versions and their branches
var newUpdateBranches: [UpdateVersion: UpdateBranch] = [:]
do {
for update in updates {
if !ignoredOldVersions.contains(update.version) && !ignoredVersionsToInsert.contains(update.version) && feedUpdateBranches[update.version] == nil {
newUpdateBranches[update.version] = UpdateBranch(minimumSystemVersion: update.minimumSystemVersion, maximumSystemVersion: nil, minimumAutoupdateVersion: majorVersion, channel: newChannel)
}
}
}
// Compute latest versions per distinct branch we need to keep
// Also compute the batch of recent versions we should preserve/add in the feed
let versionsPreservedInFeed: [UpdateVersion]
var latestVersionPerBranch: Set<UpdateVersion> = []
do {
// Group update versions by branch
var updatesGroupedByBranch: [UpdateBranch: [UpdateVersion]] = [:]
for (version, branch) in feedUpdateBranches {
updatesGroupedByBranch[branch, default: []].append(version)
}
for (version, branch) in newUpdateBranches {
updatesGroupedByBranch[branch, default: []].append(version)
}
// Grab latest batch of versions per branch
for (branch, versions) in updatesGroupedByBranch {
updatesGroupedByBranch[branch] = Array(versions.sorted(by: descendingVersionComparator).prefix(maxVersionsPerBranchInFeed))
}
// Remove extraneous versions for branches that have converged,
// as long as the user doesn't opt into keeping all versions in the feed
if maxVersionsPerBranchInFeed < Int.max {
for (branch, versions) in updatesGroupedByBranch {
guard branch.channel != nil else {
continue
}
let defaultChannelBranch = UpdateBranch(minimumSystemVersion: branch.minimumSystemVersion, maximumSystemVersion: branch.maximumSystemVersion, minimumAutoupdateVersion: branch.minimumAutoupdateVersion, channel: nil)
guard let defaultChannelVersions = updatesGroupedByBranch[defaultChannelBranch] else {
continue
}
if descendingVersionComparator(defaultChannelVersions[0], versions[0]) {
updatesGroupedByBranch[branch] = [versions[0]]
}
}
}
// Grab latest versions per branch
var latestBatchOfVersionsPerBranch: Set<UpdateVersion> = []
for (_, versions) in updatesGroupedByBranch {
latestBatchOfVersionsPerBranch.formUnion(versions)
latestVersionPerBranch.insert(versions[0])
}
versionsPreservedInFeed = Array(latestBatchOfVersionsPerBranch).sorted(by: descendingVersionComparator)
}
// Update signatures for the latest updates we keep in the feed
for version in versionsPreservedInFeed {
guard let update = archivesTable[version] else {
continue
}
updateArchivesToSign.append(update)
group.enter()
DispatchQueue.global().async {
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
if let privateDSAKey = keys.privateDSAKey {
do {
update.dsaSignature = try dsaSignature(path: update.archivePath, privateDSAKey: privateDSAKey)
} catch {
print(update, error)
}
} else if update.supportsDSA {
print("Note: did not sign with legacy DSA \(update.archivePath.path) because private DSA key file was not specified")
}
#endif
if let publicEdKey = update.publicEdKey {
if let privateEdKey = keys.privateEdKey, let expectedPublicKey = keys.publicEdKey {
if publicEdKey == expectedPublicKey {
do {
update.edSignature = try edSignature(path: update.archivePath, publicEdKey: publicEdKey, privateEdKey: privateEdKey)
} catch {
update.signingError = error
print(update, error)
}
} else {
print("Warning: SUPublicEDKey in the app \(update.archivePath.path) does not match key EdDSA in the Keychain. Run generate_keys and update Info.plist to match")
}
} else {
let error = makeError(code: .insufficientSigningError, "Could not sign \(update.archivePath.path) due to lack of private EdDSA key")
update.signingError = error
print("Error: could not sign \(update.archivePath.path) due to lack of private EdDSA key")
}
}
group.leave()
}
}
// Generate delta updates from the latest updates we keep
// Keep track of which delta archives we need referenced in the appcast still
var deltaPathsUsed: Set<String> = []
var deltaFromVersionsUsed: Set<UpdateVersion> = []
for version in versionsPreservedInFeed {
guard let latestItem = archivesTable[version] else {
continue
}
// We only generate deltas for the latest version per branch,
// but we still wanted to record the used delta updates for a batch of recent updates
// This is to support rollback in case the top newly generated update isn't exactly what the user wants
let generatingDeltas = latestVersionPerBranch.contains(version)
var numDeltas = 0
let appBaseName = latestItem.appPath.deletingPathExtension().lastPathComponent
for item in updates {
if numDeltas >= maximumDeltas {
break
}
// No downgrades
if .orderedAscending != standardComparator.compareVersion(item.version, toVersion: latestItem.version) {
continue
}
// Old version will not be able to verify the new version
if !item.supportsDSA && item.publicEdKey == nil {
continue
}
let deltaBaseName = appBaseName + latestItem.version + "-" + item.version
let deltaPath = archivesSourceDir.appendingPathComponent(deltaBaseName).appendingPathExtension("delta")
deltaPathsUsed.insert(deltaPath.path)
deltaFromVersionsUsed.insert(item.version)
numDeltas += 1
if !generatingDeltas {
continue
}
var delta: DeltaUpdate
let ignoreMarkerPath = cacheDir.appendingPathComponent(deltaPath.lastPathComponent).appendingPathExtension(".ignore")
let fm = FileManager.default
if fm.fileExists(atPath: ignoreMarkerPath.path) {
continue
}
if !fm.fileExists(atPath: deltaPath.path) {
// Test if old and new app have the same code signing signature. If not, omit a warning.
// This is a good time to do this check because our delta handling code sets a marker
// to avoid this path each time generate_appcast is called.
let oldAppCodeSigned = SUCodeSigningVerifier.bundle(atURLIsCodeSigned: item.appPath)
let newAppCodeSigned = SUCodeSigningVerifier.bundle(atURLIsCodeSigned: latestItem.appPath)
if oldAppCodeSigned != newAppCodeSigned && !newAppCodeSigned {
print("Warning: New app is not code signed but older version (\(item)) is: \(latestItem)")
} else if oldAppCodeSigned && newAppCodeSigned {
do {
try SUCodeSigningVerifier.codeSignatureIsValid(atBundleURL: latestItem.appPath, andMatchesSignatureAtBundleURL: item.appPath)
} catch {
print("Warning: found mismatch code signing identity between \(item) and \(latestItem)")
}
}
do {
// Decide the most appropriate delta version
let deltaVersion: SUBinaryDeltaMajorVersion
if let frameworkVersion = item.frameworkVersion {
switch standardComparator.compareVersion(frameworkVersion, toVersion: "2010") {
case .orderedSame:
fallthrough
case .orderedDescending:
deltaVersion = .version3
case .orderedAscending:
deltaVersion = .version2
}
} else {
deltaVersion = SUBinaryDeltaMajorVersionDefault
print("Warning: Sparkle.framework version for \(item.appPath.lastPathComponent) (\(item.shortVersion) (\(item.version))) was not found. Falling back to generating delta using default delta version..")
}
let requestedDeltaCompressionMode = deltaCompressionModeFromDescription(deltaCompressionModeDescription, nil)
// Version 2 formats only support bzip2, none, and default options
let deltaCompressionMode: SPUDeltaCompressionMode
if deltaVersion == .version2 {
switch requestedDeltaCompressionMode {
case .LZFSE:
fallthrough
case .LZ4:
fallthrough
case .LZMA:
fallthrough
case .ZLIB:
deltaCompressionMode = .bzip2
print("Warning: Delta compression mode '\(deltaCompressionModeDescription)' was requested but using default compression instead because version 2 delta file from version \(item.version) needs to be generated..")
case SPUDeltaCompressionModeDefault:
fallthrough
case .none:
fallthrough
case .bzip2:
deltaCompressionMode = requestedDeltaCompressionMode
@unknown default:
// This shouldn't happen
print("Warning: failed to parse delta compression mode \(deltaCompressionModeDescription). There is a logic bug in generate_appcast.")
deltaCompressionMode = SPUDeltaCompressionModeDefault
}
} else {
deltaCompressionMode = requestedDeltaCompressionMode
}
delta = try DeltaUpdate.create(from: item, to: latestItem, deltaVersion: deltaVersion, deltaCompressionMode: deltaCompressionMode, deltaCompressionLevel: deltaCompressionLevel, archivePath: deltaPath)
} catch {
print("Could not create delta update", deltaPath.path, error)
continue
}
} else {
delta = DeltaUpdate(fromVersion: item.version, archivePath: deltaPath, sparkleExecutableFileSize: item.sparkleExecutableFileSize, sparkleLocales: item.sparkleLocales)
}
// Require delta to be a bit smaller
if delta.fileSize / 7 > latestItem.fileSize / 8 {
markDeltaAsIgnored(delta: delta, markerPath: ignoreMarkerPath)
continue
}
group.enter()
DispatchQueue.global().async {
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
if item.supportsDSA, let privateDSAKey = keys.privateDSAKey {
do {
delta.dsaSignature = try dsaSignature(path: deltaPath, privateDSAKey: privateDSAKey)
} catch {
print(delta.archivePath.lastPathComponent, error)
}
}
#endif
if let publicEdKey = item.publicEdKey, let privateEdKey = keys.privateEdKey {
do {
delta.edSignature = try edSignature(path: deltaPath, publicEdKey: publicEdKey, privateEdKey: privateEdKey)
} catch {
print(delta.archivePath.lastPathComponent, error)
}
}
do {
var hasAnyDSASignature = (delta.edSignature != nil)
#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT
hasAnyDSASignature = hasAnyDSASignature || (delta.dsaSignature != nil)
#endif
if hasAnyDSASignature {
latestItem.deltas.append(delta)
} else {
markDeltaAsIgnored(delta: delta, markerPath: ignoreMarkerPath)
print("Delta \(delta.archivePath.path) ignored, because it could not be signed")
}
}
group.leave()
}
}
}
let inferredAppName = updates[0].appPath.deletingPathExtension().lastPathComponent
let appcast = Appcast(inferredAppName: inferredAppName, versionsInFeed: versionsPreservedInFeed, ignoredVersionsToInsert: ignoredVersionsToInsert, archives: archivesTable, deltaPathsUsed: deltaPathsUsed, deltaFromVersionsUsed: deltaFromVersionsUsed)
appcastByFeed[feed] = appcast
}
group.wait()
// Check for fatal signing errors
for update in updateArchivesToSign {
if let signingError = update.signingError {
throw signingError
}
}
return appcastByFeed
}
func moveOldUpdatesFromAppcasts(archivesSourceDir: URL, oldFilesDirectory: URL, cacheDirectory: URL, appcasts: [Appcast], autoPruneUpdates: Bool) -> (movedCount: Int, prunedCount: Int) {
let fileManager = FileManager.default
let suFileManager = SUFileManager()
// Create old files updates directory if needed
var createdOldFilesDirectory = false
let makeOldFilesDirectory: () -> Bool = {
guard !createdOldFilesDirectory else {
return true
}
if fileManager.fileExists(atPath: oldFilesDirectory.path) {
createdOldFilesDirectory = true
return true
}
do {
try fileManager.createDirectory(at: oldFilesDirectory, withIntermediateDirectories: false)
createdOldFilesDirectory = true
return true
} catch {
print("Warning: failed to create \(oldFilesDirectory.lastPathComponent) in \(archivesSourceDir.lastPathComponent): \(error)")
return false
}
}
var movedItemsCount = 0
// Move aside all old unused update items
for appcast in appcasts {
let versionsInFeedSet = Set(appcast.versionsInFeed)
for (version, update) in appcast.archives {
guard !versionsInFeedSet.contains(version) && !appcast.deltaFromVersionsUsed.contains(version) && !appcast.ignoredVersionsToInsert.contains(version) else {
continue
}
let archivePath = update.archivePath
guard makeOldFilesDirectory() else {
return (movedItemsCount, 0)
}
do {
try suFileManager.updateModificationAndAccessTimeOfItem(at: archivePath)
} catch {
print("Warning: failed to update modification time for \(archivePath.path): \(error)")
}
do {
try fileManager.moveItem(at: archivePath, to: oldFilesDirectory.appendingPathComponent(archivePath.lastPathComponent))
movedItemsCount += 1
// Remove cache for the update
let appCachePath = update.appPath.deletingLastPathComponent()
let _ = try? fileManager.removeItem(at: appCachePath)
} catch {
print("Warning: failed to move \(archivePath.lastPathComponent) to \(oldFilesDirectory.lastPathComponent): \(error)")
}
let htmlReleaseNotesFile = archivePath.deletingPathExtension().appendingPathExtension("html")
let plainTextReleaseNotesFile = archivePath.deletingPathExtension().appendingPathExtension("txt")
let releaseNotesFile: URL?
if fileManager.fileExists(atPath: htmlReleaseNotesFile.path) {
releaseNotesFile = htmlReleaseNotesFile
} else if fileManager.fileExists(atPath: plainTextReleaseNotesFile.path) {
releaseNotesFile = plainTextReleaseNotesFile
} else {
releaseNotesFile = nil
}
if let releaseNotesFile = releaseNotesFile {
do {
try suFileManager.updateModificationAndAccessTimeOfItem(at: releaseNotesFile)
} catch {
print("Warning: failed to update modification time for \(releaseNotesFile.path): \(error)")
}
do {
try fileManager.moveItem(at: releaseNotesFile, to: oldFilesDirectory.appendingPathComponent(releaseNotesFile.lastPathComponent))
movedItemsCount += 1
} catch {
print("Warning: failed to move \(releaseNotesFile.lastPathComponent) to \(oldFilesDirectory.lastPathComponent): \(error)")
}
}
}
}
// Move aside all unused delta items in the archives directory
// We will be missing out on ignore markers in the cache for delta items because they're difficult to fetch
// However they are zero-sized so they don't take much space anyway
do {
let directoryContents = try fileManager.contentsOfDirectory(atPath: archivesSourceDir.path)
for filename in directoryContents {
guard filename.hasSuffix(".delta") else {
continue
}
let deltaURL = archivesSourceDir.appendingPathComponent(filename)
do {
var foundDeltaItemUsage = false
for appcast in appcasts {
if appcast.deltaPathsUsed.contains(deltaURL.path) {
foundDeltaItemUsage = true
break
}
}
guard !foundDeltaItemUsage else {
continue
}
}
guard makeOldFilesDirectory() else {
return (movedItemsCount, 0)
}
movedItemsCount += 1
do {
try suFileManager.updateModificationAndAccessTimeOfItem(at: deltaURL)
} catch {
print("Warning: Failed to update modification time for \(deltaURL.lastPathComponent): \(error)")
}
do {
try fileManager.moveItem(at: deltaURL, to: oldFilesDirectory.appendingPathComponent(filename))
} catch {
print("Warning: failed to move \(deltaURL.lastPathComponent) to \(oldFilesDirectory.lastPathComponent): \(error)")
}
}
} catch {
print("Warning: failed to list contents of \(archivesSourceDir.lastPathComponent) during pruning: \(error)")
}
var pruneCount = 0
if autoPruneUpdates {
// Garbage collect the old updates directory
do {
let directoryContents = try fileManager.contentsOfDirectory(atPath: oldFilesDirectory.path)
// Delete files that have roughly not been touched for 14 days
let prunedFileDeletionInterval: TimeInterval = 86400 * 14
let currentDate = Date()
for filename in directoryContents {
guard !filename.hasPrefix(".") else {
continue
}
let fileURL = oldFilesDirectory.appendingPathComponent(filename)
if let resourceValues = try? fileURL.resourceValues(forKeys: [.contentModificationDateKey]),
let lastModificationDate = resourceValues.contentModificationDate {
if currentDate.timeIntervalSince(lastModificationDate) >= prunedFileDeletionInterval {
do {
try fileManager.removeItem(at: fileURL)
pruneCount += 1
} catch {
print("Warning: failed to delete old update file \(oldFilesDirectory.lastPathComponent)/\(fileURL.lastPathComponent): \(error)")
}
}
}
}
} catch {
// Nothing to log for failing to fetch prunedDirectory
}
}
return (movedItemsCount, pruneCount)
}
func markDeltaAsIgnored(delta: DeltaUpdate, markerPath: URL) {
_ = try? FileManager.default.removeItem(at: delta.archivePath)
_ = try? Data.init().write(to: markerPath); // 0-sized file
}
<file_sep>/BinaryDelta/main.swift
//
// main.swift
// BinaryDelta
//
// Created by <NAME> on 1/3/22.
// Copyright © 2022 Sparkle Project. All rights reserved.
//
import Foundation
import ArgumentParser
// Create a patch from an old and new bundle
struct Create: ParsableCommand {
@Option(name: .long, help: ArgumentHelp("The major version of the patch to generate. Defaults to the latest stable version. Older versions will need to be specified for updating from applications using older versions of Sparkle.", valueName: "version"))
var version: Int = Int(SUBinaryDeltaMajorVersionDefault.rawValue)
@Flag(name: .customLong("verbose"), help: ArgumentHelp("Enable logging of the changes being archived into the generated patch."))
var verbose: Bool = false
@Option(name: .long, help: ArgumentHelp(COMPRESSION_METHOD_ARGUMENT_DESCRIPTION, valueName: "compression"))
var compression: String = "default"
@Option(name: .long, help: .hidden)
var compressionLevel: UInt8 = 0
@Argument(help: ArgumentHelp("Path to original bundle to create a patch from."))
var beforeTree: String
@Argument(help: ArgumentHelp("Path to new bundle to create a patch from."))
var afterTree: String
@Argument(help: ArgumentHelp("Path to new patch file to create."))
var patchFile: String
func validate() throws {
var validCompression: ObjCBool = false
let compressionMode = deltaCompressionModeFromDescription(compression, &validCompression)
guard validCompression.boolValue else {
fputs("Error: unrecognized compression \(compression)\n", stderr)
throw ExitCode(1)
}
switch compressionMode {
case SPUDeltaCompressionModeDefault:
fallthrough
case .none:
guard compressionLevel == 0 else {
fputs("Error: compression level must be 0 for compression \(compression)\n", stderr)
throw ExitCode(1)
}
break
case .bzip2:
guard compressionLevel >= 0 && compressionLevel <= 9 else {
fputs("Error: compression level \(compressionLevel) is not valid.\n", stderr)
throw ExitCode(1)
}
break
case .LZMA:
fallthrough
case .LZFSE:
fallthrough
case .LZ4:
fallthrough
case .ZLIB:
guard version >= 3 else {
fputs("Error: version \(version) patch files do not support compression \(compression)\n", stderr)
throw ExitCode(1)
}
guard compressionLevel == 0 else {
fputs("Error: compression level provided must be 0 for compression \(compression)\n", stderr)
throw ExitCode(1)
}
break
@unknown default:
fputs("Error: unrecognized compression \(compression)\n", stderr)
throw ExitCode(1)
}
guard version >= SUBinaryDeltaMajorVersionFirst.rawValue else {
fputs("Error: version provided \(version) is not valid.\n", stderr)
throw ExitCode(1)
}
guard version >= SUBinaryDeltaMajorVersionFirstSupported.rawValue else {
fputs("Error: creating version \(version) patches is no longer supported.\n", stderr)
throw ExitCode(1)
}
guard version <= SUBinaryDeltaMajorVersionLatest.rawValue else {
fputs("Error: this program is too old to create a version \(version) patch, or the version number provided is invalid.\n", stderr)
throw ExitCode(1)
}
let fileManager = FileManager.default
var isDirectory: ObjCBool = false
if !fileManager.fileExists(atPath: beforeTree, isDirectory: &isDirectory) || !isDirectory.boolValue {
fputs("Error: before-tree must be a directory\n", stderr)
throw ExitCode(1)
}
if !fileManager.fileExists(atPath: afterTree, isDirectory: &isDirectory) || !isDirectory.boolValue {
fputs("Error: after-tree must be a directory\n", stderr)
throw ExitCode(1)
}
}
func run() throws {
let compressionMode = deltaCompressionModeFromDescription(compression, nil)
guard let majorDeltaVersion = SUBinaryDeltaMajorVersion(rawValue: UInt16(version)) else {
// We shouldn't reach here
fputs("Error: failed to retrieve major version from provided version: \(version)\n", stderr)
throw ExitCode(1)
}
var createDiffError: NSError? = nil
if !createBinaryDelta(beforeTree, afterTree, patchFile, majorDeltaVersion, compressionMode, compressionLevel, verbose, &createDiffError) {
if let error = createDiffError {
fputs("\(error.localizedDescription)\n", stderr)
} else {
fputs("Error: Failed to create patch due to unknown reason.\n", stderr)
}
throw ExitCode(1)
}
}
}
// Apply a patch from an old bundle to generate a new bundle
struct Apply: ParsableCommand {
static let configuration = CommandConfiguration(abstract: "Apply a patch against an original bundle to generate a new bundle.")
@Flag(name: .customLong("verbose"), help: ArgumentHelp("Enable logging of changes being applied from the patch."))
var verbose: Bool = false
@Argument(help: ArgumentHelp("Path to original bundle to patch."))
var beforeTree: String
@Argument(help: ArgumentHelp("Path to new bundle to create."))
var afterTree: String
@Argument(help: ArgumentHelp("Path to patch file to apply."))
var patchFile: String
func validate() throws {
let fileManager = FileManager.default
var isDirectory: ObjCBool = false
if !fileManager.fileExists(atPath: beforeTree, isDirectory: &isDirectory) || !isDirectory.boolValue {
fputs("Error: before-tree must be a directory\n", stderr)
throw ExitCode(1)
}
if !fileManager.fileExists(atPath: patchFile, isDirectory: &isDirectory) || isDirectory.boolValue {
fputs("Error: patch-file must be a file\n", stderr)
throw ExitCode(1)
}
}
func run() throws {
var applyDiffError: NSError?
if (!applyBinaryDelta(beforeTree, afterTree, patchFile, verbose, { _ in }, &applyDiffError)) {
if let error = applyDiffError {
fputs("\(error.localizedDescription)\n", stderr)
} else {
fputs("Error: patch failed to apply for unknown reason\n", stderr)
}
throw ExitCode(1)
}
}
}
// Output information for BinaryDelta or from a patch file
struct Info: ParsableCommand {
@Argument(help: ArgumentHelp("Path to patch file to extract information from."))
var patchFile : String?
func run() throws {
if let patchFile = patchFile {
// Print version of patch file
var header: SPUDeltaArchiveHeader? = nil
let archive = SPUDeltaArchiveReadPatchAndHeader(patchFile, &header)
if let error = archive.error {
fputs("Error: Unable to open patch \(patchFile): \(error.localizedDescription)\n", stderr)
throw ExitCode(1)
}
if let header = header {
if header.majorVersion < SUBinaryDeltaMajorVersionFirst.rawValue {
fputs("Error: major version \(header.majorVersion) is invalid.\n", stderr)
throw ExitCode(1)
}
fputs("Patch version \(header.majorVersion).\(header.minorVersion)", stdout)
// Print out compression info only if it's available
// We can't get compression info from version 2 files
if header.compression != SPUDeltaCompressionModeDefault, let compressionDescription = deltaCompressionStringFromMode(header.compression) {
fputs(" using \(compressionDescription) compression", stdout)
// Compression level isn't available or applicable for all formats
if header.compressionLevel != 0 {
fputs(" with level \(header.compressionLevel)", stdout)
}
}
fputs("\n", stdout)
} else {
fputs("Error: Failed to retrieve header due to unknown reason.\n", stderr)
throw ExitCode(1)
}
} else {
// Print version of program
fputs("BinaryDelta version \(SUBinaryDeltaMajorVersionLatest.rawValue).\(latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersionLatest))\n", stdout)
}
}
}
struct BinaryDelta: ParsableCommand {
static let configuration = CommandConfiguration(commandName: "BinaryDelta", abstract: "Create and apply small and efficient delta patches between an old and new version of a bundle.", subcommands: [Create.self, Apply.self, Info.self])
}
DispatchQueue.global().async(execute: {
BinaryDelta.main()
CFRunLoopStop(CFRunLoopGetMain())
})
CFRunLoopRun()
<file_sep>/Configurations/make-xcframework.sh
#!/bin/bash
# Deleting old products
rm -rd "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive"
rm -rd "$BUILT_PRODUCTS_DIR/Sparkle.xcframework"
xcodebuild archive -scheme Sparkle -archivePath "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive" BUILD_LIBRARY_FOR_DISTRIBUTION=YES SKIP_INSTALL=NO
if [ $XCODE_VERSION_MAJOR -ge "1200" ]; then
xcodebuild -create-xcframework -framework "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/Products/Library/Frameworks/Sparkle.framework" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Sparkle.framework.dSYM" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Autoupdate.dSYM" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Updater.app.dSYM" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Installer.xpc.dSYM" -debug-symbols "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Downloader.xpc.dSYM" -output "$BUILT_PRODUCTS_DIR/Sparkle.xcframework"
else
echo "warning: Your Xcode version does not support bundling dSYMs in XCFrameworks directly. You should copy them manually into the XCFramework."
echo "note: cp '$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/dSYMs/Sparkle.framework.dSYM' '$BUILT_PRODUCTS_DIR/Sparkle.xcframework/your_architecture/dSYMs'"
xcodebuild -create-xcframework -framework "$BUILT_PRODUCTS_DIR/Sparkle.xcarchive/Products/Library/Frameworks/Sparkle.framework" -output "$BUILT_PRODUCTS_DIR/Sparkle.xcframework"
fi
| 8664823644e2240b7819c4f53e05e3de0085cd51 | [
"Markdown",
"Shell",
"Ruby",
"Swift"
]
| 17 | Markdown | sparkle-project/Sparkle | 4abbb2b4f17437c46be45cc9e012c002823b4697 | e8cf603387e5101be8d53ea37332506238a34316 |
refs/heads/master | <repo_name>msgpo/SRadio<file_sep>/src/gui/box.go
package gui
import (
"log"
"github.com/gotk3/gotk3/gtk"
)
func NewHBox(spacing int) *gtk.Box {
box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, spacing)
if err != nil {
log.Println("Error create hbox", err)
return nil
}
box.SetVExpand(true)
return box
}
func NewVBox(spacing int) *gtk.Box {
box, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, spacing)
if err != nil {
log.Println("Error create vbox", err)
return nil
}
box.SetHExpand(true)
return box
}
<file_sep>/src/SRadio/main.go
package main
import (
"config"
"gui"
"log"
"radio"
"runtime"
)
func main() {
log.Println("Start SRadio", config.Version)
runtime.LockOSThread()
config.Init()
radDef := config.GetSelectedRadio()
rList := config.GetRadios()
rad := radio.NewRadio()
if radDef >= 0 && radDef < len(rList) {
rad.SetRadio(&rList[radDef])
} else if len(rList) > 0 {
rad.SetRadio(&rList[0])
}
gui.Init(rad)
rad.Stop()
}
<file_sep>/src/gui/app.go
package gui
import (
"github.com/gotk3/gotk3/glib"
)
var (
app *glib.Application
)
func InitApp() {
app = glib.ApplicationNew("ru.YouROK.SRadio", glib.APPLICATION_FLAGS_NONE)
}
func RunApp(f func()) {
app.Connect("activate", f)
app.Run(nil)
}
<file_sep>/src/gui/listBox.go
package gui
import (
"log"
"strconv"
"github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk"
)
type ListBox struct {
treeView *gtk.TreeView
listStore *gtk.ListStore
selIndex int
funOnClick func(ind int)
funOnDblClick func(ind int)
}
func NewListBox() *ListBox {
lb := &ListBox{}
render, err := gtk.CellRendererTextNew()
if err != nil {
log.Println("Error create CellRendererTextNew", err)
return nil
}
columns, err := gtk.TreeViewColumnNewWithAttribute("Radio stations", render, "text", 0)
if err != nil {
log.Println("Error create TreeViewColumnNewWithAttribute", err)
return nil
}
lb.treeView, err = gtk.TreeViewNew()
if err != nil {
log.Println("Error create TreeViewNew", err)
return nil
}
lb.treeView.AppendColumn(columns)
lb.listStore, err = gtk.ListStoreNew(glib.TYPE_STRING)
if err != nil {
log.Fatal("Error create ListStoreNew", err)
}
lb.treeView.SetModel(lb.listStore)
lb.treeView.Connect("cursor-changed", func() {
if lb.funOnClick != nil {
lb.funOnClick(lb.GetSelected())
}
})
lb.treeView.Connect("row_activated", func() {
if lb.funOnDblClick != nil {
lb.funOnDblClick(lb.GetSelected())
}
})
return lb
}
/*
If path.GetIndices is undefined add this func to gtk.go
// GetIndices is a wrapper around gtk_tree_path_get_indices_with_depth
func (v *TreePath) GetIndices() []int {
var depth C.gint
var goindices []int
var ginthelp C.gint
indices := uintptr(unsafe.Pointer(C.gtk_tree_path_get_indices_with_depth(v.native(), &depth)))
size := unsafe.Sizeof(ginthelp)
for i := 0; i < int(depth); i++ {
goind := int(*((*C.gint)(unsafe.Pointer(indices))))
goindices = append(goindices, goind)
indices += size
}
return goindices
}
*/
func (l *ListBox) GetSelected() int {
path, _ := l.treeView.GetCursor()
if path != nil {
inds := path.GetIndices()
if len(inds) > 0 {
return inds[0]
}
}
return -1
}
func (l *ListBox) SetSelected(ind int) {
if ind == -1 {
return
}
path, err := gtk.TreePathNewFromString(strconv.Itoa(ind))
if err == nil {
l.treeView.SetCursor(path, nil, false)
}
}
func (l *ListBox) Update(list []string) {
l.listStore.Clear()
for _, s := range list {
l.listStore.SetValue(l.listStore.Append(), 0, s)
}
}
func (l *ListBox) OnClick(cb func(ind int)) {
l.funOnClick = cb
}
func (l *ListBox) OnDblClick(cb func(ind int)) {
l.funOnDblClick = cb
}
func (l *ListBox) GetWidget() gtk.IWidget {
return l.treeView
}
<file_sep>/src/gui/notify.go
package gui
import (
"github.com/gotk3/gotk3/glib"
)
func Notify(txt string) {
nn := glib.NotificationNew("SRadio")
nn.SetBody(txt)
app.SendNotification("SRadio", nn)
}
<file_sep>/src/gui/guiEvents.go
package gui
import (
"config"
"log"
"radio"
"github.com/gotk3/gotk3/gtk"
)
func updateRadioList() {
index := radioList.GetSelected()
var items []string
radios := config.GetRadios()
for _, r := range radios {
items = append(items, r.Name)
}
radioList.Update(items)
radioList.SetSelected(index)
}
func eventsHandler() {
radioChanEvent := rad.GetEvents()
for true {
radioEvent := <-radioChanEvent
switch radioEvent.Type {
case radio.RE_CHANGE_TITLE:
{
if radioEvent.Val != "" {
mainWnd.SetTitle("SRadio - " + radioEvent.Val)
statusLabel.SetLabel("Song: " + radioEvent.Val)
trayIcon.SetTitle(radioEvent.Val)
Notify(radioEvent.Val)
}
}
case radio.RE_STOP:
{
mainWnd.SetTitle("SRadio")
bottomBtn[0].SetLabel("Play")
statusLabel.SetLabel("Stopped")
if trayAnim != nil {
trayAnim.SetAnimation(TA_STOPPED)
}
}
case radio.RE_START, radio.RE_UNPAUSE:
{
if trayAnim != nil {
trayAnim.SetAnimation(TA_PLAYING)
}
statusLabel.SetLabel("Playing... " + rad.GetRadio().Name)
}
case radio.RE_ERROR:
{
if trayAnim != nil {
trayAnim.SetAnimation(TA_STOPPED)
}
log.Println("Error:", radioEvent.Val)
bottomBtn[0].SetLabel("Play")
statusLabel.SetLabel("Error: " + radioEvent.Val)
}
case radio.RE_PAUSE:
{
if trayAnim != nil {
trayAnim.SetAnimation(TA_LOADING)
}
statusLabel.SetLabel("Loading...")
}
}
}
}
func btnPlayClick() {
if rad.IsPlaying() {
rad.Stop()
} else {
rad.Play()
}
defer updTrayMenu()
if mainWnd.IsVisible() {
if rad.IsPlaying() {
bottomBtn[0].SetLabel("Stop")
} else {
bottomBtn[0].SetLabel("Play")
}
}
}
func btnAboutClick() {
about, _ := gtk.AboutDialogNew()
about.SetVersion(config.Version)
about.SetProgramName("SRadio")
about.SetComments("SRadio - Simple Radio\nprogram for listen online radio\nAuthor: YouROK")
about.SetWebsite("https://github.com/YouROK")
about.Run()
about.Hide()
}
func btnExitClick() {
gtk.MainQuit()
}
func radioListClick(radInd int) {
if radInd == -1 {
return
}
radSel := config.GetRadios()[radInd]
radioEdit[0].SetText(radSel.Name)
radioEdit[1].SetText(radSel.Url)
}
func radioListDblClick(radInd int) {
if radInd == -1 {
return
}
defer updTrayMenu()
radSel := config.GetRadios()[radInd]
if radSel.Url == "separator" {
return
}
config.SetSelectedRadio(radInd)
if rad.GetRadio() == nil || radSel.Url != rad.GetRadio().Url {
rad.Stop()
rad.SetRadio(&radSel)
}
rad.Play()
if mainWnd.IsVisible() {
if rad.IsPlaying() {
bottomBtn[0].SetLabel("Stop")
} else {
bottomBtn[0].SetLabel("Play")
}
}
}
func btnUp() {
pos := radioList.GetSelected()
if pos > 0 {
up := config.GetRadios()[pos]
upper := config.GetRadios()[pos-1]
config.SetRadio(up, pos-1)
config.SetRadio(upper, pos)
updateRadioList()
radioList.SetSelected(pos - 1)
}
}
func btnDown() {
pos := radioList.GetSelected()
if pos < len(config.GetRadios())-1 {
down := config.GetRadios()[pos]
downer := config.GetRadios()[pos+1]
config.SetRadio(down, pos+1)
config.SetRadio(downer, pos)
updateRadioList()
radioList.SetSelected(pos + 1)
}
}
func btnAdd() {
rc := config.RadioCfg{}
rc.Name, _ = radioEdit[0].GetText()
rc.Url, _ = radioEdit[1].GetText()
if rc.Name != "" && rc.Url != "" {
config.AddRadio(rc)
updateRadioList()
}
}
func btnEdit() {
rc := config.RadioCfg{}
rc.Name, _ = radioEdit[0].GetText()
rc.Url, _ = radioEdit[1].GetText()
pos := radioList.GetSelected()
if rc.Name != "" && rc.Url != "" && pos != -1 {
config.SetRadio(rc, pos)
updateRadioList()
}
}
func btnRemove() {
pos := radioList.GetSelected()
if pos != -1 {
config.DelRadio(pos)
updateRadioList()
}
}
func btnSeparator() {
rc := config.RadioCfg{Name: "-------------------", Url: "separator"}
config.AddRadio(rc)
updateRadioList()
}
func updTrayMenu() {
if trayIcon == nil {
return
}
trayIcon.NewMenu()
sel := config.GetSelectedRadio()
defRadio := config.GetRadios()[sel]
btnPlStName := "Play"
if rad.IsPlaying() {
btnPlStName = "Stop"
}
trayIcon.AddMenuItem(btnPlStName+" "+defRadio.Name, func(interface{}) { btnPlayClick() }, nil)
trayIcon.AddMenuItem("Show settings", func(interface{}) {
mainWnd.ShowAll()
//TODO иногда не показывает контент
}, nil)
trayIcon.AddMenuItem("", nil, nil)
for i, r := range config.GetRadios() {
if r.Url == "separator" {
trayIcon.AddMenuItem("", nil, nil)
} else {
trayIcon.AddMenuItem(r.Name, playRadio, i)
}
}
trayIcon.AddMenuItem("", nil, nil)
trayIcon.AddMenuItem("Exit", func(interface{}) { gtk.MainQuit() }, nil)
}
func playRadio(menuItm interface{}, i interface{}) {
if ind, ok := i.(int); ok {
radioListDblClick(ind)
}
}
<file_sep>/src/player/player.go
package player
// #include <locale.h>
import "C"
import (
"config"
"log"
"time"
"unsafe"
"github.com/yourok/go-mpv/mpv"
)
type EventCallback func(*mpv.Event, *Player)
type Player struct {
mp *mpv.Mpv
isPlay bool
fileName string
cache int
cacheSeek int
volume int
eventFunc EventCallback
}
func NewPlayer() *Player {
p := &Player{}
p.cache = config.GetCache()
p.cacheSeek = config.GetCacheSeek()
p.volume = 100
return p
}
func (p *Player) Init() error {
if p.mp == nil {
buf := []byte("C")
C.setlocale(C.LC_NUMERIC, (*C.char)(unsafe.Pointer(&buf[0])))
m := mpv.Create()
m.SetOption("no-resume-playback", mpv.FORMAT_FLAG, true)
m.SetOption("volume", mpv.FORMAT_INT64, p.volume)
m.SetOptionString("terminal", "yes")
m.SetOptionString("softvol", "auto")
m.SetOption("no-video", mpv.FORMAT_FLAG, true)
m.SetOption("cache", mpv.FORMAT_INT64, p.cache)
m.SetOption("cache-seek-min", mpv.FORMAT_INT64, p.cacheSeek)
m.SetOption("volume", mpv.FORMAT_INT64, 0)
err := m.Initialize()
if err != nil {
log.Println("Error init mpv", err)
return err
}
p.mp = m
}
return nil
}
func (p *Player) Play(fileName string) error {
if p.isPlay {
return nil
}
var err error
if fileName != p.fileName {
p.Stop()
}
if p.mp == nil {
err = p.Init()
}
if err != nil {
return err
}
err = p.mp.Command([]string{"loadfile", fileName})
if err != nil {
p.Stop()
return err
}
p.fileName = fileName
p.isPlay = true
go p.handler()
return nil
}
func (p *Player) Stop() error {
p.isPlay = false
p.fileName = ""
if p.mp != nil {
p.mp.Command([]string{"stop"})
p.mp.DetachDestroy()
p.mp = nil
}
return nil
}
func (p *Player) Restart() error {
fn := p.fileName
p.Stop()
return p.Play(fn)
}
func (p *Player) FadeIn() {
//vol up
for i := 0; i <= p.volume; i++ {
if p.mp == nil {
return
}
p.mp.SetProperty("volume", mpv.FORMAT_INT64, i)
time.Sleep(time.Millisecond * 1)
}
}
func (p *Player) FadeOut() {
//vol down
for i := p.volume; i >= 0; i-- {
if p.mp == nil {
return
}
p.mp.SetProperty("volume", mpv.FORMAT_INT64, i)
time.Sleep(time.Millisecond * 1)
}
}
func (p *Player) SetVolume(vol int) {
if vol > 100 {
vol = 100
}
if vol < 0 {
vol = 0
}
p.volume = vol
if p.mp == nil {
return
}
p.mp.SetProperty("volume", mpv.FORMAT_INT64, vol)
}
func (p *Player) IsPlaying() bool {
return p.isPlay
}
func (p *Player) SetEventCallback(fun EventCallback) {
p.eventFunc = fun
}
func (p *Player) handler() {
for p.isPlay {
if p.eventFunc != nil {
ev := p.mp.WaitEvent(-1)
if ev.Event_Id != mpv.EVENT_NONE {
p.eventFunc(ev, p)
}
}
time.Sleep(time.Millisecond * 500)
}
}
<file_sep>/src/radio/events.go
package radio
type RadioEvents struct {
Type EventType
Val string
}
type EventType int
const (
RE_START EventType = iota
RE_STOP
RE_ERROR
RE_CHANGE_TITLE
RE_PAUSE
RE_UNPAUSE
)
func (e EventType) String() string {
switch e {
case RE_START:
return "RE_START"
case RE_STOP:
return "RE_STOP"
case RE_ERROR:
return "RE_ERROR"
case RE_CHANGE_TITLE:
return "RE_CHANGE_TITLE"
case RE_PAUSE:
return "RE_PAUSE"
case RE_UNPAUSE:
return "RE_UNPAUSE"
default:
return "RE_UNKNOWN"
}
}
<file_sep>/src/gui/button.go
package gui
import (
"log"
"sync"
"github.com/gotk3/gotk3/gtk"
)
type Button struct {
btn *gtk.Button
mutex sync.Mutex
}
func NewButton(label string) *Button {
btn := &Button{}
var err error
btn.btn, err = gtk.ButtonNewWithLabel(label)
if err != nil {
log.Println("Error create button", err)
return nil
}
return btn
}
func (b *Button) SetLabel(label string) {
b.mutex.Lock()
defer b.mutex.Unlock()
b.btn.SetLabel(label)
}
func (b *Button) SetSize(width, height int) {
b.mutex.Lock()
defer b.mutex.Unlock()
b.btn.SetSizeRequest(width, height)
}
func (b *Button) OnClick(f func()) {
b.mutex.Lock()
defer b.mutex.Unlock()
b.btn.Connect("clicked", f)
}
func (b *Button) GetWidget() *gtk.Button {
return b.btn
}
<file_sep>/src/gui/gui.go
package gui
import (
"log"
"os"
"path/filepath"
"radio"
"github.com/gotk3/gotk3/gtk"
)
var (
mainWnd *gtk.Window
radioEdit []*gtk.Entry
updwBtn []*Button
mainBtn []*Button
bottomBtn []*Button
radioList *ListBox
statusLabel *gtk.Label
trayAnim *TrayAnimation
trayIcon *TrayIcon
rad *radio.Radio
)
//TODO normal gui interface
func Init(r *radio.Radio) {
rad = r
gtk.Init(nil)
InitApp()
RunApp(initWnd)
}
func initWnd() {
var err error
mainWnd, err = gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
if err != nil {
log.Println("Error create window", err)
return
}
mainWnd.SetPosition(gtk.WIN_POS_CENTER)
mainWnd.SetTitle("SRadio")
trayIcon = NewTrayIcon(filepath.Join(filepath.Dir(os.Args[0]), "radiotray3.png"))
if trayIcon != nil {
icons := []string{filepath.Join(filepath.Dir(os.Args[0]), "radiotray1.png"),
filepath.Join(filepath.Dir(os.Args[0]), "radiotray2.png"),
filepath.Join(filepath.Dir(os.Args[0]), "radiotray3.png")}
trayIcon.SetIconList(icons)
trayIcon.SetIcon(0)
trayAnim = NewTrayAnimation(trayIcon)
trayAnim.SetAnimation(TA_STOPPED)
mainWnd.Connect("destroy", func() {
mainWnd.Hide()
})
updTrayMenu()
} else {
mainWnd.Connect("destroy", func() {
gtk.MainQuit()
})
}
mainWnd.Add(buildMainWnd())
mainWnd.SetSizeRequest(600, 400)
if trayIcon == nil {
mainWnd.ShowAll()
}
go eventsHandler()
app.Hold()
gtk.Main()
trayAnim.Close()
app.Release()
}
/*
********************************
* List R * Add *
* ------ * Import *
* ------ * Export *
* ------ * Edit *
* ------ * Remove *
* ------ * Separator *
****************************** *
* Play * About * Exit *
* Stop * * *
********************************
*/
func buildMainWnd() gtk.IWidget {
mainVBox, _ := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1)
{
hbox := NewHBox(1)
{ //Tree
vboxleft := NewVBox(1)
radioList = NewListBox()
radioList.OnClick(radioListClick)
radioList.OnDblClick(radioListDblClick)
updateRadioList()
hboxud := NewHBox(1)
hboxud.SetVExpand(false)
updwBtn := make([]*Button, 2)
updwBtn[0] = NewButton("Up")
updwBtn[0].SetSize(-1, 25)
updwBtn[1] = NewButton("Down")
updwBtn[1].SetSize(-1, 25)
updwBtn[0].OnClick(btnUp)
updwBtn[1].OnClick(btnDown)
hboxud.PackStart(updwBtn[0].GetWidget(), true, true, 1)
hboxud.PackEnd(updwBtn[1].GetWidget(), true, true, 1)
scroll, _ := gtk.ScrolledWindowNew(nil, nil)
scroll.SetPolicy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
scroll.Add(radioList.GetWidget())
vboxleft.PackStart(scroll, true, true, 1)
vboxleft.PackEnd(hboxud, false, false, 1)
hbox.PackStart(vboxleft, true, true, 1)
}
{ // menu buttons
radioEdit = make([]*gtk.Entry, 2)
radioEdit[0], _ = gtk.EntryNew()
radioEdit[1], _ = gtk.EntryNew()
mainBtn = make([]*Button, 4)
mainBtn[0] = NewButton("Add")
mainBtn[1] = NewButton("Edit")
mainBtn[2] = NewButton("Remove")
mainBtn[3] = NewButton("Separator")
vbox := NewVBox(2)
for i := 0; i < len(radioEdit); i++ {
vbox.PackStart(radioEdit[i], false, false, 1)
}
for i := 0; i < len(mainBtn); i++ {
vbox.PackStart(mainBtn[i].GetWidget(), true, true, 1)
}
hbox.Add(vbox)
mainBtn[0].OnClick(btnAdd)
mainBtn[1].OnClick(btnEdit)
mainBtn[2].OnClick(btnRemove)
mainBtn[3].OnClick(btnSeparator)
}
mainVBox.PackStart(hbox, true, true, 1)
}
{ //bottom buttons
hbox := NewHBox(1)
bottomBtn = make([]*Button, 3)
bottomBtn[0] = NewButton("Play")
bottomBtn[1] = NewButton("About")
bottomBtn[2] = NewButton("Exit")
hbox.SetHomogeneous(true)
for i := 0; i < len(bottomBtn); i++ {
hbox.Add(bottomBtn[i].GetWidget())
bottomBtn[i].SetSize(-1, 50)
}
mainVBox.PackStart(hbox, false, true, 15)
bottomBtn[0].OnClick(btnPlayClick)
bottomBtn[1].OnClick(btnAboutClick)
bottomBtn[2].OnClick(btnExitClick)
}
{ //status label
statusLabel, _ = gtk.LabelNew("")
statusLabel.SetJustify(gtk.JUSTIFY_LEFT)
statusLabel.SetHAlign(gtk.ALIGN_START)
mainVBox.PackEnd(statusLabel, false, true, 2)
statusLabel.SetSizeRequest(-1, -1)
}
return mainVBox
}
<file_sep>/src/radio/radio.go
package radio
import (
"config"
"log"
"player"
"github.com/yourok/go-mpv/mpv"
)
type Callback func(ev *mpv.Event, val interface{})
type Radio struct {
pl *player.Player
playing *config.RadioCfg
events chan RadioEvents
songTitle string
errors int
}
func NewRadio() *Radio {
r := &Radio{}
r.pl = player.NewPlayer()
r.events = make(chan RadioEvents, 255)
r.pl.SetEventCallback(r.eventsHandler)
return r
}
func (r *Radio) SetRadio(rcfg *config.RadioCfg) {
r.playing = rcfg
}
func (r *Radio) GetRadio() *config.RadioCfg {
return r.playing
}
func (r *Radio) GetEvents() chan RadioEvents {
return r.events
}
func (r *Radio) Play() {
if r.playing != nil {
r.songTitle = ""
r.errors = 0
r.pl.Play(r.playing.Url)
r.sendEvent(RE_START, "")
}
}
func (r *Radio) Stop() {
r.pl.FadeOut()
r.pl.Stop()
r.sendEvent(RE_STOP, "")
}
func (r *Radio) Restart() {
r.pl.FadeOut()
r.pl.Stop()
r.songTitle = ""
r.pl.Play(r.playing.Url)
}
func (r *Radio) IsPlaying() bool {
return r.pl.IsPlaying()
}
func (r *Radio) eventsHandler(ev *mpv.Event, pl *player.Player) {
if ev.Event_Id == mpv.EVENT_START_FILE {
pl.FadeIn()
}
if ev.Event_Id == mpv.EVENT_END_FILE {
if r.errors > 5 {
r.pl.Stop()
r.errors = 0
log.Println("So many errors, stop and send error")
var val string
if data, ok := ev.Data.(mpv.EventEndFile); ok {
val = data.ErrCode.Error()
}
r.sendEvent(RE_ERROR, val)
}
if r.IsPlaying() {
r.errors++
r.Restart()
log.Println("Restart player", r.errors)
return
}
}
if ev.Event_Id == mpv.EVENT_METADATA_UPDATE {
title, err := r.pl.GetMediaTitle()
if err == nil && r.songTitle != title {
r.sendEvent(RE_CHANGE_TITLE, title)
r.songTitle = title
}
}
if ev.Event_Id == mpv.EVENT_PAUSE {
r.sendEvent(RE_PAUSE, "")
}
if ev.Event_Id == mpv.EVENT_UNPAUSE {
r.sendEvent(RE_UNPAUSE, "")
}
}
func (r *Radio) sendEvent(t EventType, val string) {
r.events <- RadioEvents{t, val}
}
<file_sep>/src/config/config.go
package config
import (
"encoding/xml"
"io/ioutil"
"log"
"os"
"path/filepath"
)
var (
conf Config
)
const (
Version = "1.0.3"
)
type Config struct {
Volume int
Cache int
CacheSeek int
Radios []RadioCfg
SelectedRadio int
}
type RadioCfg struct {
Name string
Url string
}
func Init() {
conf.Volume = 100
conf.Cache = 1024 * 1024
conf.CacheSeek = 25
conf.Radios = make([]RadioCfg, 0)
conf.SelectedRadio = 0
Load()
if len(conf.Radios) == 0 {
AddRadio(RadioCfg{Name: "Ultra HD", Url: "http://nashe2.hostingradio.ru/ultra-192.mp3"})
}
}
func SetCache(val int) {
conf.Cache = val
Save()
}
func SetCacheSeek(val int) {
conf.CacheSeek = val
Save()
}
func SetSelectedRadio(val int) {
conf.SelectedRadio = val
Save()
}
func GetCache() int {
return conf.Cache
}
func GetCacheSeek() int {
return conf.CacheSeek
}
func GetSelectedRadio() int {
return conf.SelectedRadio
}
func GetRadios() []RadioCfg {
return conf.Radios
}
func AddRadio(r RadioCfg) {
if conf.Radios == nil {
conf.Radios = make([]RadioCfg, 1)
}
conf.Radios = append(conf.Radios, r)
Save()
}
func SetRadio(r RadioCfg, pos int) {
if pos >= 0 && pos < len(conf.Radios) {
conf.Radios[pos] = r
Save()
}
}
func DelRadio(pos int) {
if pos >= 0 && pos < len(conf.Radios) {
conf.Radios = append(conf.Radios[:pos], conf.Radios[pos+1:]...)
Save()
}
}
func Save() {
buf, err := xml.MarshalIndent(conf, "", " ")
if err == nil {
filenamecfg := filepath.Join(filepath.Dir(os.Args[0]), "sradio.cfg")
ff, err := os.Create(filenamecfg)
if err == nil {
_, err := ff.Write(buf)
if err != nil {
log.Println("Error write file", err)
}
} else {
log.Println("Error create cfg file", err)
}
} else {
log.Println("Error make xml", err)
}
}
func Load() {
filenamecfg := filepath.Join(filepath.Dir(os.Args[0]), "sradio.cfg")
buf, err := ioutil.ReadFile(filenamecfg)
if err == nil {
err = xml.Unmarshal(buf, &conf)
if err != nil {
log.Println("Error unmarshal xml", err)
}
} else {
log.Println("Error read cfg file", err)
}
}
/*
<Config>
<Volume>100</Volume>
<Cache>4096</Cache>
<CacheSeek>16</CacheSeek>
<Radios>
<Name>Ultra HD</Name>
<Url>http://nashe2.hostingradio.ru/ultra-192.mp3</Url>
</Radios>
<Radios>
<Name>Ultra</Name>
<Url>http://nashe2.hostingradio.ru/ultra-128.mp3</Url>
</Radios>
<Radios>
<Name><NAME></Name>
<Url>http://nashe1.hostingradio.ru/nashe-128.mp3</Url>
</Radios>
<Radios>
<Name>Наше 2.0</Name>
<Url>http://nashe1.hostingradio.ru/nashe20-128.mp3</Url>
</Radios>
<Radios>
<Name><NAME></Name>
<Url>http://192.168.3.11:8000/play</Url>
</Radios>
<Radios>
<Name>Nomercy Radio</Name>
<Url>http://stream6.radiostyle.ru:8006/nomercy</Url>
</Radios>
<Radios>
<Name>Maximum</Name>
<Url>http://icecast.radiomaximum.cdnvideo.ru/maximum.mp3</Url>
</Radios>
<Radios>
<Name>AvSIM</Name>
<Url>http://radio.avsim.su:8000/stream</Url>
</Radios>
<Radios>
<Name>RockFM</Name>
<Url>http://nashe.streamr.ru/rock-128.mp3</Url>
</Radios>
<SelectedRadio>5</SelectedRadio>
</Config>
*/
<file_sep>/src/player/media.go
package player
import "github.com/yourok/go-mpv/mpv"
func (p *Player) GetMediaTitle() (string, error) {
str, err := p.mp.GetProperty("media-title", mpv.FORMAT_STRING)
return str.(string), err
}
<file_sep>/src/gui/trayAnimation.go
package gui
import (
"time"
)
const (
TA_PLAYING = iota
TA_STOPPED
TA_LOADING
TA_CLOSE
)
type TrayAnimation struct {
animIndex int
frame int
trayicon *TrayIcon
isAnimate bool
isReverse bool
}
func NewTrayAnimation(ti *TrayIcon) *TrayAnimation {
ta := &TrayAnimation{}
ta.trayicon = ti
ta.animIndex = TA_STOPPED
go ta.animation()
return ta
}
func (ta *TrayAnimation) Close() {
ta.animIndex = TA_CLOSE
}
func (ta *TrayAnimation) SetAnimation(index int) {
if ta.animIndex != index {
ta.stopAnimation()
}
ta.animIndex = index
}
func (ta *TrayAnimation) GetTrayIcon() *TrayIcon {
return ta.trayicon
}
func (ta *TrayAnimation) animation() {
for ta.animIndex != TA_CLOSE {
ta.isAnimate = true
switch ta.animIndex {
case TA_PLAYING:
ta.animPlaying()
case TA_LOADING:
ta.animLoading()
default:
ta.animStoped()
}
}
}
func (ta *TrayAnimation) animPlaying() {
ta.trayicon.SetIcon(ta.frame)
if ta.frame == 2 {
ta.sleep(10000)
}
if ta.isReverse {
ta.frame--
} else {
ta.frame++
}
if ta.frame < 1 || ta.frame > 1 {
ta.isReverse = !ta.isReverse
}
ta.sleep(500)
}
func (ta *TrayAnimation) animStoped() {
ta.trayicon.SetIcon(ta.frame)
if ta.isReverse {
ta.frame--
} else {
ta.frame++
}
if ta.frame < 0 {
ta.frame = 0
}
if ta.frame > 1 {
ta.frame = 1
}
if ta.frame == 0 || ta.frame == 1 {
ta.isReverse = !ta.isReverse
}
ta.sleep(1000)
}
func (ta *TrayAnimation) animLoading() {
ta.trayicon.SetIcon(ta.frame)
if ta.isReverse {
ta.frame--
} else {
ta.frame++
}
if ta.frame < 1 || ta.frame > 1 {
ta.isReverse = !ta.isReverse
}
ta.sleep(300)
}
func (t *TrayAnimation) sleep(millisecond int) {
for i := 0; i < millisecond/100; i++ {
if !t.isAnimate {
break
}
time.Sleep(100 * time.Millisecond)
}
}
func (t *TrayAnimation) stopAnimation() {
t.isAnimate = false
}
<file_sep>/README.md
# SRadio
Simple radio for playing online music
<file_sep>/src/gui/tray.go
package gui
import (
"appindicator"
"github.com/gotk3/gotk3/gtk"
)
type TrayIcon struct {
icon *appindicator.AppIndicator
iconsName []string
menu *gtk.Menu
title string
}
func NewTrayIcon(iconName string) *TrayIcon {
ti := &TrayIcon{}
appind := appindicator.NewAppIndicator("example-simple-client", "indicator-messages", appindicator.CategoryOther)
appind.SetStatus(appindicator.StatusActive)
appind.SetIcon(iconName, "SRadio")
ti.icon = appind
return ti
}
func (t *TrayIcon) NewMenu() {
t.menu, _ = gtk.MenuNew()
t.icon.SetMenu(t.menu)
}
func (t *TrayIcon) AddMenuItem(name string, callback interface{}, arg interface{}) {
if name == "" {
sep, _ := gtk.SeparatorMenuItemNew()
sep.Show()
t.menu.Append(sep)
} else {
itm1, _ := gtk.MenuItemNewWithLabel(name)
itm1.Connect("activate", callback, arg)
itm1.Show()
t.menu.Append(itm1)
}
}
func (t *TrayIcon) SetIconList(fileName []string) {
t.iconsName = fileName
}
func (t *TrayIcon) SetTitle(title string) {
t.title = title
t.icon.SetTitle(title)
}
func (t *TrayIcon) SetIcon(index int) {
t.icon.SetIcon(t.iconsName[index], t.iconsName[index])
}
| 86d29008c6178908287dc2708f961557d3c39125 | [
"Markdown",
"Go"
]
| 16 | Go | msgpo/SRadio | 1e24c702cc7296ea768fe74b2defceeac4260e14 | 07b3db65998c2cd9cc0f2eb2f940a128f6da156d |
refs/heads/master | <repo_name>ndtaylor2/monitoring<file_sep>/README.md
# ForceServer and SOQLExplorer -
ForceServer is a simple development server aimed at providing a simple and integrated developer experience when building applications that use Salesforce OAuth and REST services. ForceServer provides two main features:
- **A Proxy Server** to avoid cross-domain policy issues when invoking Salesforce REST services. (The Chatter API supports CORS, but other APIs don’t yet)
- **A Local Web Server** to (1) serve the OAuth callback URL defined in your Connected App, and (2) serve the whole app during development and avoid cross-domain policy issues when loading files (for example, templates) from the local file system.
- **ForceJS provides a simple Javascript library to use in your webpages.
This fork does a couple of things
- **Combined ForceServer and SOQLExplorer - into a single package to make it easier to deploy to Heroku
- **The home page in SOQLExplorer - display recent changes to Contacts and Cases. It refreshes every 60 seconds.
- **The "developer" tab shows the OAuth Token and allows you to
- **This can be installed on localhost or on Heroku. If you are installing on Heroku, you'll need to create a new connected app and update js/app.js.
Code Highlights:
1. The website/application above uses the <a href="">ForceJS</a> library. ForceJS and ForceServer are built to work closely together and provide an integrated developer experience.
1. ForceJS uses a default connected app: No need to create a connected app to start development. You should however create your own connected app for production use.
1. ForceServer automatically serves the OAuth callback URL: No need to create a callback HTML page during development.
## Run the Server
To finish this doc.....
Navigate to the directory and type:
```
node server.js
```
This command will start the server on port 8200, and automatically load your app (http://localhost:8200) in a browser window. You'll see the Salesforce login window, and the list of contacts will appear after you log in.
You can change the port number using this command.
```
node server.js --port 8200
```
## Deploying to Heroku
The ForceServer is CORS-enabled. Instead of running it locally as a development server, you can deploy it to Heroku.
[](https://heroku.com/deploy)
Before you can use the app, you need to make two changes.
### Setup a Salesforce Connected App
1. Create a new Connected App. [Instructions.](https://help.salesforce.com/apex/HTViewHelpDoc?id=connected_app_create.htm&language=en_US)
2. Enable OAuth Settings.
3. After saving, Set the CIt will not work
To use the Proxy Server deployed to Heroku, call the force.init() function before force.login() and specify your Proxy URL. For example, if the Heroku app you just created is **myproxy**:
```
force.init({
proxyURL: 'https://myproxy.herokuapp.com'
});
```
<file_sep>/js/app.js
var querydate=moment();
var refreshSeconds = 60;
var intervalMinutes = 5; //
document.getElementById("queryBtn").addEventListener("click", function () {
var soql = document.getElementById("soql");
var result = document.getElementById("result");
force.query(soql.value,
function (data) {
result.innerHTML = JSON.stringify(data, undefined, 3);
},
function (error) {
alert("Error: " + JSON.stringify(error));
});
}, false);
document.getElementById("refreshBtn").addEventListener("click", refreshData, false);
document.getElementById("loginBtn").addEventListener("click", login, false);
function showToken() {
try {
var tokentext = document.getElementById("oauth-token");
tokentext.innerHTML = JSON.stringify(force.oauthStore());
console.log("Token:" + force.oauthStore());
} catch (e) {
console.error(e);
}
}
function showDate() {
try {
var datetext = document.getElementById("datestamp");
datetext.innerHTML = querydate.format("dddd, MMMM Do YYYY, h:mm:ss a"); ;
} catch (e) {
console.error(e);
}
}
// Need two named areas
// <object_name>_summary (h2)
// <object_name>_changed (h2)
// <object_name>_table (tbody)
function getObjectsChanged(object_name,name_field) {
var date = querydate;
var query = 'select Id,'+name_field+', LastModifiedBy.Name, LastModifiedDate from '+
object_name+' where LastModifiedDate > '+date.format()+' ORDER BY LastModifiedDate DESC limit 200';
var soql = document.getElementById("soql");
soql.innerHTML = query;
force.query(query, function (response) {
var str = '';
for (var i = 0; i < response.records.length; i++) {
str += '<tr>' +
'<td>' + i + '</td>' +
'<td>' + response.records[i].Id + '</td>' +
'<td>' + response.records[i][name_field] + '</td>' +
'<td>' + response.records[i].LastModifiedBy.Name + '</td>' +
'<td>' + response.records[i].LastModifiedDate + '</td>' +
'</tr>';
}
document.getElementById(object_name+'_table').innerHTML = str;
});
var changed = document.getElementById(object_name+"_changed");
var changed2 = document.getElementById(object_name+"_summary");
var query2 = 'select COUNT() from '+object_name+' where LastModifiedDate > '+date.format();
force.query(query2, function (response) {
try {
console.log("Count succeeded.");
if (changed!=null) {
changed.innerHTML = response.totalSize +' '+ object_name+ " changes.";
}
if (changed2!=null) {
changed2.innerHTML = response.totalSize +' '+ object_name+ " changes.";
}
} catch(e) {
console.error(e);
}
});
}
function refreshData() {
querydate=moment().subtract(intervalMinutes,'m');
showToken();
showDate();
getObjectsChanged('Contact','Name');
getObjectsChanged('Case','CaseNumber');
getObjectsChanged('ServiceContract','ContractNumber');
setTimeout(refreshData,refreshSeconds*1000); // Refresh after 1 minute;
}
function login() {
force.login(refreshData);
}
if (window.location.hostname=='salty-gorge-66919.herokuapp.com') {
force.init({appId: '<KEY>'});
// This uses a different OAuth app that is setup for salty-gorge-66919.herokuapp.com
}
// login();
| e093dfb03a65a41a76a6c2bbc65e30512fcf4bc9 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | ndtaylor2/monitoring | 90d7612d3865d553f17ee1170a8450946b47d94e | 470afcf3f936ee4dfe5dcfa39a4fca0c563d2284 |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { Grid } from './shared/grid.model';
import { GridService } from './shared/grid.service';
@Component({
selector: 'grid',
templateUrl: './grid.component.html',
moduleId: module.id,
providers: [GridService],
styleUrls: ["./grid.component.css"]
})
export class GridComponent implements OnInit {
grid: Grid[] = [];
constructor(private gridService: GridService) { }
ngOnInit() {
this.gridService.getList().subscribe((res) => {
this.grid = res;
});
}
}<file_sep>The base command for creating a NativeScript app comes with some predefined templates. For creating base Angular-2 Application you can use
`tns create myApp --ng`
Or you can create your own template like this one and pass it as a param
`tns create myApp --template path-to-template-here`
Or if you are using **VSCode** as your IDE for development then you can add [this extension](https://marketplace.visualstudio.com/items?itemName=joshdsommer.vscode-add-angular-native-files)
And then it is pretty straight forward: right click on app folder >> Add Angular2 Files
The command will prompt for a name and will generate the following (if the name provided is home)
```
home/home.component.ts
home/home.component.html
home/home.component.css
home/home.component.spec.ts
```
https://developer.telerik.com/featured/demystifying-nativescript-layouts/
https://www.npmjs.com/package/nativescript-grid-view
https://github.com/PeterStaev/NativeScript-Grid-View
https://docs.nativescript.org/cookbook/ui/button
https://www.thepolyglotdeveloper.com/2015/12/navigate-between-routes-in-a-nativescript-mobile-app/
https://docs.nativescript.org/angular/core-concepts/angular-navigation.html
https://stackoverflow.com/questions/39204175/nativescript-no-provider-for-http<file_sep>// import { TestBed, inject } from '@angular/core/testing';
// import { HttpModule } from '@angular/http';
// import { Observable } from 'rxjs/Observable';
// import 'rxjs/Rx';
// import { GridComponent } from './grid.component';
// import { GridService } from './shared/grid.service';
// import { Grid } from './shared/grid.model';
// describe('a grid component', () => {
// let component: GridComponent;
// // register all needed dependencies
// beforeEach(() => {
// TestBed.configureTestingModule({
// imports: [HttpModule],
// providers: [
// { provide: GridService, useClass: MockGridService },
// GridComponent
// ]
// });
// });
// // instantiation through framework injection
// beforeEach(inject([GridComponent], (GridComponent) => {
// component = GridComponent;
// }));
// it('should have an instance', () => {
// expect(component).toBeDefined();
// });
// });
// // Mock of the original grid service
// class MockGridService extends GridService {
// getList(): Observable<any> {
// return Observable.from([ { id: 1, name: 'One'}, { id: 2, name: 'Two'} ]);
// }
// }
| 4bae80147204abee06cbd2b6a38b8bca0419d810 | [
"Markdown",
"TypeScript"
]
| 3 | TypeScript | WagnerMoreira/game-store | 3b52786b87837f26441f9971226a9e1004cb78e9 | 4df4a544784ed1d167a1d9968e989cbaf1603b19 |
refs/heads/master | <repo_name>kartikv97/Curve_Fitting_RANSAC<file_sep>/src/demo.py
# Import Dataset and read
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
import random
import utils
data_1 = pd.read_csv(r"..\dataset\data_1.csv")
data_2 = pd.read_csv(r"..\dataset\data_2.csv")
# We convert the dataset into a list and then split the data into separate x and y variable lists.
data_1 = data_1.values.tolist()
data_2 = data_2.values.tolist()
# Split Data
x_data1 = []
y_data1 = []
x_data2 = []
y_data2 = []
for i in range(len(data_1)):
x_data1.append(data_1[i][0])
y_data1.append(data_1[i][1])
for i in range(len(data_2)):
x_data2.append(data_2[i][0])
y_data2.append(data_2[i][1])
print("Processing Output Plots...")
# We plot both the datasets using functions from the matplotlib library.
fig = plt.figure(figsize=(10,5))
(ax1, ax2) = fig.subplots(1, 2)
fig.suptitle('Original Datasets')
ax1.plot(x_data1, y_data1, 'ro', label='dataset1')
ax1.set(xlabel='x-axis', ylabel='y-axis', title="Dataset 1")
ax1.legend()
ax2.plot(x_data2, y_data2, 'bo', label='dataset2')
ax2.set(xlabel='x-axis', ylabel='y-axis', title="Dataset 2")
ax2.legend()
# plt.show()
# Plot the output curve fit using the LMSE method.
fig = plt.figure(figsize=(10,5))
(ax1, ax2) = fig.subplots(1, 2)
fig.suptitle('Least Mean Square Output Curve Fit')
ax1.plot(x_data1, y_data1, 'bo', label=' Dataset 1')
ax1.plot(x_data1, utils.predictOutput(x_data1, y_data1, utils.build_Model(x_data1, y_data1)), color='red', label='Curve Fit')
ax1.set(xlabel='x-axis', ylabel='y-axis', title="Dataset 1")
ax1.legend()
ax2.plot(x_data2, y_data2, 'o', label=' Dataset 2')
ax2.plot(x_data2, utils.predictOutput(x_data2, y_data2, utils.build_Model(x_data2, y_data2)), color='red', label='Curve Fit')
ax2.set(xlabel='x-axis', ylabel='y-axis', title="Dataset 2")
ax2.legend()
# plt.show()
# We plot the output curve fit for the first dataset using the RANSAC algorithm.
utils.ransac(x_data1, y_data1, 10000, 45, 95,1)
# We plot the output curve fit for the second dataset using the RANSAC algorithm.
utils.ransac(x_data2, y_data2, 10000, 45, 95,2)
print("Finished Processing Generating Output...")
plt.show()<file_sep>/src/utils.py
# Import Dataset and read
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
import random
# We define a function to compute the power of a list.
def calc_power(list_val, power):
out = []
for i in range(len(list_val)):
out.append(pow(list_val[i], power))
return out
# We then define a function to determine the model parameters a, b, c of the quadratic equation so that we can predict the output y for any given input x.
def build_Model(x, y):
model_params = []
n = len(x)
X = np.array([[n, sum(x), sum(calc_power(x, 2))],
[sum(x), sum(calc_power(x, 2)), sum(calc_power(x, 3))],
[sum(calc_power(x, 2)), sum(calc_power(x, 3)), sum(calc_power(x, 4))]])
xy = [np.dot(x, y)]
x2y = [np.dot(calc_power(x, 2), y)]
Y = np.array([[(sum(y))], [(sum(xy))], [(sum(x2y))]])
model_params = np.dot(np.linalg.inv(X), Y)
return model_params
# We define a function to predict the output y using the model parameters and the input data x.
def predictOutput(x, y, A1):
y_predict = A1[2] * calc_power(x, 2) + A1[1] * x + A1[0]
return y_predict
# RANSAC algorithm:
# 1. Select three data points randomly from the dataset.
# 2. Determine the model parameters for the quadratic from those three data points.
# 3. Compare all the datapoints with the predicted model equation and classify them as inliers or outliers.
# 4. Select a model that maximizes the ratio of inliers to outliers.
# 5. Generate a curve fit from the final model.
def ransac(x_data, y_data, n, t, success_threshold,dataset_id):
final_inliers_x = []
final_inliers_y = []
final_outliers_x = []
final_outliers_y = []
worstfit = 0
prev_inliers = 0
# Number of iterations
# n=10000
# Threshold value
# t=55
# Worst possible error is infinite error
worst_error = np.inf
for i in range(n):
dataPoints = random.sample(range(len(x_data)), 3)
# print(dataPoints)
possible_inliers_x = []
possible_inliers_y = []
for i in dataPoints:
possible_inliers_x.append(x_data[i])
possible_inliers_y.append(y_data[i])
test_Model = build_Model(possible_inliers_x, possible_inliers_y)
y_predict = predictOutput(x_data, y_data, test_Model)
# print(possible_inliers_x)
# print(possible_inliers_y)
num_inliers = 0
num_outliers = 0
valid_inliers_x = [0]
valid_inliers_y = [0]
valid_outliers_x = [0]
valid_outliers_y = [0]
for i in range(len(x_data)):
if abs(y_data[i] - y_predict[i]) < t:
valid_inliers_x.append(x_data[i])
valid_inliers_y.append(y_data[i])
num_inliers += 1
else:
valid_outliers_x.append(x_data[i])
valid_outliers_y.append(y_data[i])
num_outliers += 1
if num_inliers > worstfit:
worstfit = num_inliers
# print("############################### Better Model Found #####################################")
# Update chosen starting points
input_points_x = possible_inliers_x
input_points_y = possible_inliers_y
# Update the model parameters
update_model = build_Model(valid_inliers_x, valid_inliers_y)
op = predictOutput(valid_inliers_x, valid_inliers_y, update_model)
final_model = update_model
# Update temperary variables to preserve data corresponding to the final chosen model.
fin_inlier = num_inliers
fin_outlier = num_outliers
final_inliers_x = valid_inliers_x.copy()
final_inliers_y = valid_inliers_y.copy()
final_outliers_x = valid_outliers_x.copy()
final_outliers_y = valid_outliers_y.copy()
success_rate = (worstfit / len(x_data)) * 100
if success_rate >= success_threshold:
break
# print(num_inliers, num_outliers)
# print(fin_inlier, fin_outlier)
#
# print('Worstfit=', worstfit)
fig = plt.figure(figsize=(10, 5))
(ax1, ax2) = fig.subplots(1, 2)
fig.suptitle('RANSAC Output Curve Fit')
ax1.plot(x_data, predictOutput(x_data, y_data, final_model), color='red', label='Curve Fit')
ax1.plot(x_data, y_data, 'o', color='blue', label='Input Data')
ax1.set(xlabel='x-axis', ylabel='y-axis', title="Dataset "+str(dataset_id))
ax1.legend()
ax2.plot(x_data, predictOutput(x_data, y_data, final_model), color='red', label='Curve Fit')
ax2.plot(final_inliers_x, final_inliers_y, 'o', color='black', label='Inliers')
ax2.plot(final_outliers_x, final_outliers_y, 'o', color='orange', label='Outliers')
ax2.plot(input_points_x, input_points_y, 'o', color='lime', label='Picked Points')
ax2.set(xlabel='x-axis', ylabel='y-axis', title="Dataset "+str(dataset_id) )
ax2.legend()
# plt.show()
<file_sep>/README.md
## Curve Fitting Using RANSAC and LMSE
The aim of this project is to compare the curve fitting
abilities(Outlier Rejection Capability) of two algorithms
LMSE (Least Mean Squared Error) and RANSAC (Random Sample
Consensus) on two datasets:
- Dataset 1 - No Outliers
- Dataset 2 - With Outliers
---
## Instructions
### Dependencies
- python3
- numpy==1.18.0
- matplotlib
- pandas
### Run using Command Line
```
git clone https://github.com/kartikv97/Curve_Fitting_RANSAC.git
cd Curve_Fitting_RANSAC/src
python demo.py
```
---
## Results
### Input Dataset

### LMSE Curve Fit

### RANSAC Curve Fit


| 0b8ff46448992eb9d3e607157ce054784eaaf939 | [
"Markdown",
"Python"
]
| 3 | Python | kartikv97/Curve_Fitting_RANSAC | a0b9aac29e70f6c746f1484f9c96a19275a753d2 | dc94a0399d168cb207c9bc513d5559a3b6065a4b |
refs/heads/master | <repo_name>nof1000/roadway<file_sep>/index.js
/**
* The simple InputStream with frames to array-like objects.
*
* @module roadway
* @author <NAME> <<EMAIL>> (nofach.co)
* @license MIT
*/
/** Errors */
class BasicError extends Error {
constructor(msg) {
super(msg);
this.name = this.constructor.name;
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = (new Error(msg)).stack;
}
}
}
class EmptyBufferError extends BasicError {
constructor() {
super('before flush the buffer, must start recording');
}
}
class InvalidInputError extends BasicError {
constructor() {
super('expected String, Array or Array-Like Object');
}
}
/** Methods */
function isValidInput(input) {
return input && input[0] !== undefined && typeof (input.length) === 'number';
}
function slice(target, begin, end) {
const result = [];
for (let i = begin; i < end; i += 1) {
result.push(target[i]);
}
return result;
}
/** Implementation */
class Roadway {
constructor(input) {
this.framedSlice = -1;
this.cursor = 0;
if (input && !isValidInput(input)) {
throw new InvalidInputError();
}
this.input = input;
}
reset(input = null) {
if (input !== null) {
if (!isValidInput(input)) {
throw new InvalidInputError();
}
this.input = input;
}
this.framedSlice = -1;
this.cursor = 0;
}
peek(offset = 0) {
if (this.eof(offset)) {
return undefined;
}
return this.input[this.cursor + offset];
}
next(offset = 0) {
const result = this.peek();
if (result !== undefined) {
this.cursor += offset + 1;
}
return result;
}
flush() {
let result = null;
if (this.framedSlice < 0) {
throw new EmptyBufferError();
}
if (this.input.slice) {
result = this.input.slice(this.framedSlice, this.cursor);
} else {
result = slice(this.input, this.framedSlice, this.cursor);
}
this.framedSlice = -1;
return result;
}
record() {
this.framedSlice = this.cursor;
}
eof(offset = 0) {
if (this.input && this.input.length) {
if (this.cursor + offset >= this.input.length) {
return true;
}
}
return false;
}
}
/** Exports */
module.exports = Roadway;
<file_sep>/index.test.js
/** Dependencies */
const assert = require('assert');
const Roadway = require('./index.js');
/** Preparing */
const preString = 'riders on the storm';
const preArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const preObject = ((...items) => {
const result = {};
for (let i = 0; i < items.length; i += 1) {
result[i] = i;
}
result.length = items.length;
return result;
})(...preArray);
/** Testing */
describe('Roadway', () => {
describe('Basic(string)', () => {
it('#reset', () => {
const str1 = preString.slice(Math.floor(preString.length / 2));
const str2 = preString.slice(Math.floor(preString.length / 4));
const rw = new Roadway(str1);
while (!rw.eof()) rw.next();
assert.deepEqual(rw.cursor, str1.length);
rw.reset();
assert.deepEqual(rw.input, str1);
assert.deepEqual(rw.cursor, 0);
rw.reset(str2);
assert.deepEqual(rw.input, str2);
});
it('#flush & #record', () => {
const rw = new Roadway(preString, {
framed: true,
});
rw.record();
rw.next(5);
assert.deepEqual(rw.flush(), preString.slice(0, 6));
rw.next();
rw.record();
rw.next(1);
assert.deepEqual(rw.flush(), preString.slice(7, 9));
});
it('#peek', () => {
const rw = new Roadway(preString);
for (let i = 0; i < preString.length; i += 1) {
assert.deepEqual(rw.peek(i), preString[i]);
}
});
it('#next', () => {
const rw = new Roadway(preString);
for (let i = 0; i < preString.length; i += 1) {
assert.deepEqual(rw.next(), preString[i]);
}
});
it('#eof', () => {
const rw = new Roadway(preString);
while (!rw.eof()) {
rw.next();
}
assert.deepEqual(rw.cursor, preString.length);
assert.deepEqual(rw.next(), undefined);
});
});
it('Array', () => {
const rw = new Roadway(preArray, {
framed: true,
});
// peek
assert.deepEqual(rw.peek(), preArray[0]);
// next
assert.deepEqual(rw.peek(), rw.next());
assert.deepEqual(rw.peek(), preArray[1]);
// record & flush
rw.record();
rw.next(1);
assert.deepEqual(rw.flush(), preArray.slice(1, 3));
// reset
rw.reset();
assert.deepEqual(rw.cursor, 0);
assert.deepEqual(rw.input, preArray);
// eof
while (!rw.eof()) rw.next();
assert.deepEqual(rw.cursor, preArray.length);
assert.deepEqual(rw.next(), undefined);
});
it('Object', () => {
const rw = new Roadway(preObject, {
framed: true,
});
// peek
assert.deepEqual(rw.peek(), preObject[0]);
// next
assert.deepEqual(rw.peek(), rw.next());
assert.deepEqual(rw.peek(), preObject[1]);
// record & flush
rw.record();
rw.next(1);
assert.deepEqual(rw.flush(), [1, 2]);
// reset
rw.reset();
assert.deepEqual(rw.cursor, 0);
assert.deepEqual(rw.input, preObject);
// eof
while (!rw.eof()) rw.next();
assert.deepEqual(rw.cursor, preObject.length);
assert.deepEqual(rw.next(), undefined);
});
});
<file_sep>/README.md
### 🛣 The simple InputStream with frames to array-like objects.
> Current status: in development. 🔴
## What is it?
> Coming soon...
## Install
npm
```
$ npm install roadway
```
yarn
```
$ yarn add roadway
```
## How it use?
> Coming soon...
## Documentation
> Coming soon...
## LICENSE
[MIT](./LICENSE "The MIT License") © [<NAME>](https://github.com/nof1000 "Author")
| c39f6f6188c942d38bc2276643efae357fd0dda7 | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | nof1000/roadway | b65e9574ddf10337037a807eede8ffaa0de6d36e | 455696f45dbc9d2da2f4c9d0e393a5ca9c149637 |
refs/heads/master | <repo_name>rizkanfirmansyah/socket-aroma<file_sep>/index.js
const express = require("express");
const socketio = require("socket.io");
const http = require("http");
const cors = require("cors");
var url = require("url");
var mysql = require("mysql");
var fs = require("fs");
var gString = require("querystring");
var Router = require('routes')()
var connection = mysql.createConnection({
host: "localhost",
port: 3306,
database: "erparoma_demo",
user: "root",
password: "",
});
const PORT = process.env.PORT || 5050;
const router = require("./router");
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.get('/', function(request, res){
res.sendFile(__dirname + '/templates/index.html');
});
io.on("connection", (socket) => {
socket.on("join", ({ name, socketId }) => {
// socket.emit('connect', {name, socketId});
// socket.broadcast.to(socketId).emit('pesan', name);
// socket.join(socketId);
// let datas = [name, socket.id]
connection.query(
"SELECT COUNT(*) AS rcount FROM usr_auth_log where ?", {name : name},
function (err, rows, field) {
if (err) throw err;
if (rows[0].rcount > 0) {
connection.query("UPDATE usr_auth_log set ? where ?",[{socket:socket.id}, {name:name} ], function(err, rows, field){
if(err) throw err;
})
} else {
let datalog = [name, socket.id]
connection.query("INSERT INTO usr_auth_log (name, socket) VALUES(?,?)", datalog, function(err, rows, field){
if(err) throw err;
})
}
// console.log(rows[0].rcount);
}
);
console.log("user has been connect " + socketId);
// callback();
});
socket.on("send", ({ name, message, room }) => {
console.log(name, message, room);
// io.emit('accept', {name, message});
socket.broadcast.to(room).emit("accept", { name, type: "chat", message });
});
socket.on("disconnect", () => {
connection.query(
"SELECT * from usr_auth_log where ?",
{ socket: socket.id },
function (err, rows, field) {
if (err) throw err;
let name = rows[0].name;
// console.log(name);
// console.log();
connection.query(
"DELETE from usr_auth_pos where ?",
{ usr: name },
function (err, rows, field) {
if (err) throw err;
console.log(rows);
}
);
connection.query(
"DELETE from usr_auth_log where ?",
{ name: name},
function (err, rows, field) {
if (err) throw err;
console.log(rows);
}
);
}
);
console.log("user has been disconnect " + socket.id);
});
});
app.use(router);
app.use(cors());
server.listen(PORT, () => console.log(`Server has started on port ${PORT}`));
<file_sep>/algoritma.js
let name = '<NAME>';
let as = '';
let dataname = name.split(" ");
dataname.forEach(value => {
as += value.charAt(0);
});
console.log(name)
console.log(as);
| 874433058db3fdfb83fce209e5b745ca6c128b31 | [
"JavaScript"
]
| 2 | JavaScript | rizkanfirmansyah/socket-aroma | afe1ab27a2d4acc795b0eef315648bb0bdaa03dd | e7b36dde81d06ccff58b1780d8d795500b423503 |
refs/heads/master | <repo_name>usedlobster/CarND-T2-P4<file_sep>/src/PID.cpp
#include "PID.h"
// include for debugging.
#include <iostream>
using namespace std;
PID::PID() {}
PID::~PID() {}
void PID::Init(double Kp, double Ki, double Kd) {
// save given pid constants
this->Kp = Kp ;
this->Ki = Ki ;
this->Kd = Kd ;
// initialise error totals to zero
p_error = 0.0 ;
i_error = 0.0 ;
d_error = 0.0 ;
}
void PID::UpdateError(double cte) {
// d_error is current - previous
d_error = ( cte - p_error ) ;
// just current error
p_error = cte ;
// sum of errors
i_error += cte ;
}
// return total error multipled by respective gains.
double PID::TotalError() {
return ( p_error * Kp ) + ( i_error * Ki ) + ( d_error * Kd ) ;
}
// my auto-tuner
PidAutoTuner::PidAutoTuner() {
// skip first nSkip readings
nSkip = 200 ;
nRun = 800 ;
delta[0] = 1.0 ;
delta[1] = 1.0 ;
delta[2] = 1.0 ;
best_error_so_far = 1e100;
twiddle_step = 1 ;
twiddle_param = 0 ;
//
iter = 0 ;
error_sum_squared = 0.0 ;
}
bool PidAutoTuner::Update( double e, PID &pid ) {
iter++ ;
// skip the first nSkip samples
if ( iter < nSkip )
return false ;
if ( iter == nSkip )
error_sum_squared = e ; // first sample
else if ( ( e < -5.0 ) && ( e > 5.0 )) {
error_sum_squared = best_error_so_far + 1.0 ; // force opt out early if e is between these
} else
error_sum_squared += e ; // sum error so far ( we assume only passed e > 0 )
// have we twiddled enougth
if ( ( delta[0] + delta[1] + delta[2] ) < 0.01 ) {
iter = 0 ;
std::cout << "-DONE-" << std::endl ;
return false ;
}
if ( error_sum_squared > best_error_so_far )
iter = nSkip + nRun ; // skip summing error and go to next twiddle step.
else if ( iter < nSkip + nRun )
return false ; // keep collection samples
double p[3] ;
p[0] = pid.Kp ;
p[1] = pid.Ki ;
p[2] = pid.Kd ;
for(;;) {
if ( twiddle_step == 0 ) {
p[ twiddle_param ] += delta[ twiddle_param ] ;
twiddle_step = 1 ;
break ;
}
if ( error_sum_squared < best_error_so_far ) {
best_error_so_far = error_sum_squared ;
delta[ twiddle_param ] *= 1.1 ;
std::cout << "BEST SO FAR: " << best_error_so_far << ":" << pid.Kp << ":" << pid.Ki << ":" << pid.Kd << std::endl ;
} else {
if ( twiddle_step == 1 ) {
p[ twiddle_param ] -= 2.0*delta[ twiddle_param ] ;
twiddle_step = 2 ;
break ; // wait for another error estimate
} else {
p[ twiddle_param ] += delta [ twiddle_param ] ;
delta[ twiddle_param ] *= 0.9 ;
}
}
twiddle_param = ( twiddle_param + 1 ) % 3 ;
twiddle_step = 0 ;
}
// change pid parameters
pid.Init( p[0], p[1], p[2] ) ;
// reset step count
std::cout << "[" << best_error_so_far << ":" << pid.Kp << ":" << pid.Ki << ":" << pid.Kd << "]" << std::endl ;
iter = 0.0 ;
//
return true ;
}
<file_sep>/src/PID.h
#ifndef PID_H
#define PID_H
class PID {
public:
/*
* Errors
*/
double p_error;
double i_error;
double d_error;
/*
* Coefficients
*/
double Kp;
double Ki;
double Kd;
/*
* Constructor
*/
PID();
/*
* Destructor.
*/
virtual ~PID();
/*
* Initialize PID.
*/
void Init(double Kp, double Ki, double Kd);
/*
* Update the PID error variables given cross track error.
*/
void UpdateError(double cte);
/*
* Calculate the total PID error.
*/
double TotalError();
};
class PidAutoTuner {
private:
int iter ;
int nSkip ;
int nRun ;
int twiddle_step ;
int twiddle_param ;
double error_sum_squared ;
double err ;
double best_error_so_far ;
double delta[3] ;
double delta_sum ;
private:
void StartTune() ;
public:
PidAutoTuner() ;
bool Update( double e, PID &pid ) ;
} ;
#endif /* PID_H */
<file_sep>/README.md
# CarND-Controls-PI
Self-Driving Car Engineer Nanodegree Program
## Reflection
#### *Describe the effect each of the P, I, D components had in your implementation.*
For this project, we have implemented a classic Proportional-Integral-Derivative ( or PID controller for short ) in C++ code. The PID controller is continuously passed the cross track error ( or c.t.e for short ) from the simulator and produces an output that is used to set the cars steering angle. The output of the controller is the negative of the sum of three components P, I and D.
* The P-Term is for the "Proportional" part of the PID controller. The P contribution to the output is proportional to the c.t.e by an amount given by the hyperparameter Kp. If we set the Kp value too high, the car can overshoot the required trajectory. If too low then the car may not respond quickly enough to fast-changing cross-track errors, such as when going around a sharp bend.
The chart below shows the cross track error from the simulator for the first 250 samples, showing the results when Kp is equal to both 0.1 and 0.2, the other components set to 0. The chart shows that when Kp=0.1, it takes longer for the error to reach 0, but the error magnitude is lower.


* The I-Term is for the "Integral" part of the PID controller. The I contribution to this output is the sum of all previous errors weighted by Ki. So if the car had a systematic drift to one side or the other, eventually the sum of this errors would be large enough to force it back on course. The chart below shows 3 different Ki coefficients with a fixed Kp=0.1. The I term has caused the errors to be spread more evenly over positive and negative errors, at the cost of higher magnitude.


* The D-Term or "Derivative" term. The D-Term in this code is the previous error minus the current error multiplied by the Kd parameter. Thus when the rate of change is small, the D-Term would also be negligible, but when the change in error rate is more significant, then a more significant D action gets applied. So the D term helps dampen out the c.t.e. The chart below shows the output with Kp=0.1, Ki=0.0005 and Kd at 1,2 and 4.


#### * Describe how the final hyperparameters, were chosen. *
Not being very ambitious, I set the throttle always to be at 0.4, and would manually tune with this in mind. As we also knew that the cross track error when the car was driving nicely, was roughly in the range [-10,+10]. It is reasonably apparent that Kp should be small say in the range [0,1], and Ki should be tiny if not 0 and Kd would probably be around 0-10. We then tried various combinations of these.
I then decided to try and implement the twiddle algorithm; this was more complex than I had hoped. It required a quick peek of the Udacity simulator code, to see that it provided a "reset" message which would cause a reload of the Unity scene to the start of the track ( simulator should be run with root privileges - otherwise it may crash out after a couple of reloads ). My auto-tuner class, would ignore the first 200 samples, then sum the next 1800, twiddle the parameters, compare to its best found so far, reset the simulator and then run another 2000 steps, and repeat. I used as a cost function "c.t.e^2 + (100.0-speed)/100.0" the additional speed term helps if / when the car crashes out and stops but points in the right direction going 0 mph, and it is also an indication of quality - the firster the car goes the smoother the steering must be.
After running for a few hours, the algorithm came up with the following as the best it could find was:-
### Kp = 0.43463 , Ki = 0.00104 , Kd = 7.28484
The chart below shows how these parameters try to keep the c.t.e at 0.

A video of the car running with these parameters is
[video](https://youtu.be/g9eLASW-bus)
| 757f2ef87208c5589728922a9d8cb7cb5db3b6a7 | [
"Markdown",
"C++"
]
| 3 | C++ | usedlobster/CarND-T2-P4 | 1aee105015a9e4f9326f49af44814459522d10aa | 633f291a740da4d7900b1336b2998db444e4575f |
refs/heads/main | <file_sep># ****************************************************************************
# @coord_calculations.py
#
# @copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
import pandas as pd
import math
import pyproj
from pyproj import Geod
import numpy as np
import warnings
def transform_lanes_rel2abs(df: pd.DataFrame, data_type: str) -> pd.DataFrame:
"""
Transforms lane coordinates in absolut coordinate system
Args:
df: Input dataframe
data_type: Input file type (csv or osi)
Returns:
object (pd.DataFrame): Transformed dataframe
"""
if not isinstance(df, pd.DataFrame):
raise TypeError("input must be a pd.DataFrame")
if not isinstance(data_type, str):
raise TypeError("input must be a str")
def find_curve(begin_x: float, begin_y: float, k: float, end_x: float) -> np.ndarray:
"""
Helper function for rel2abs. Creates an array containing a 2D curve represented by x and y values.
Args:
begin_x: x coordinate of the curve starting point
begin_y: y coordinate of the curve starting point
k: curvature of the curve
end_x: x coordinate of the curve ending point (may not be represented with a point of the array)
Returns:
object (np.ndarray): array containing a 2D curve represented by x and y values
"""
points = []
x = 0
x_increment = 2
while x <= end_x:
if k == 0:
points.append((x, begin_y))
else:
y = (k * begin_y + 1 - math.sqrt(1 - (k ** 2) * ((x - begin_x) ** 2))) / k
points.append((x, y))
x += x_increment
return np.array(points)
def calc_new_geopos_from_2d_vector(lat: float, lon: float, head: float, x: float, y: float, g: Geod) -> tuple:
"""
Helper function for rel2abs. calculates a new geo position based on a start position, heading and a 2d movement
vector from object perspective
Args:
lat: Latitude of starting position
lon: Longitude of starting position
head: Starting heading
x: X component of movement vector from object starting perspective
y: Y component of movement vector from object starting perspective
g (pyproj.geod): Geodetic
Returns:
object (tuple): Latitude and longitude of new geo position
"""
d = math.sqrt(x ** 2 + y ** 2)
# When Azimuth to calculate, it is important to consider heading of ego vehicle
q = head - math.degrees(math.atan2(y, x))
endlon, endlat, backaz = g.fwd(lon, lat, q, d, radians=False)
return endlat, endlon
length = len(df.index) - 1
df_crv = df.dropna(subset=['lin_right_beginn_x', 'lin_left_beginn_x'])
length_crv = len(df_crv.index) - 1
if data_type == 'csv':
points_right = find_curve(df_crv['lin_right_beginn_x'][length_crv],
df_crv['lin_right_y_abstand'][length_crv],
df_crv['lin_right_kruemm'][length_crv],
df_crv['lin_right_ende_x'][length_crv])
points_left = find_curve(df_crv['lin_left_beginn_x'][length_crv],
df_crv['lin_left_y_abstand'][length_crv],
df_crv['lin_left_kruemm'][length_crv],
df_crv['lin_left_ende_x'][length_crv])
df_temp_1 = pd.DataFrame(columns=['lin_right_beginn_x'])
df_temp_1['lin_right_beginn_x'] = points_right[:, 0]
df_temp_1['lin_right_y_abstand'] = points_right[:, 1]
df_temp_2 = pd.DataFrame(columns=['lin_left_beginn_x'])
df_temp_2['lin_left_beginn_x'] = points_left[:, 0]
df_temp_2['lin_left_y_abstand'] = points_left[:, 1]
df_temp_1 = pd.concat([df_temp_1, df_temp_2], axis=1)
df_temp_1 = df_temp_1.dropna()
df = pd.concat([df, df_temp_1], ignore_index=True)
else:
pass
geodetic = Geod(ellps='WGS84')
r_lane_lat_list = []
r_lane_lon_list = []
l_lane_lat_list = []
l_lane_lon_list = []
for i in range(len(df.index)):
if i < length:
r_lane_lat, r_lane_lon = calc_new_geopos_from_2d_vector(df['lat'][i], df['long'][i], df['heading'][i],
df['lin_right_beginn_x'][i],
df['lin_right_y_abstand'][i], geodetic)
l_lane_lat, l_lane_lon = calc_new_geopos_from_2d_vector(df['lat'][i], df['long'][i], df['heading'][i],
df['lin_left_beginn_x'][i],
df['lin_left_y_abstand'][i], geodetic)
else:
r_lane_lat, r_lane_lon = calc_new_geopos_from_2d_vector(df['lat'][length], df['long'][length], df['heading'][length],
df['lin_right_beginn_x'][i],
df['lin_right_y_abstand'][i], geodetic)
l_lane_lat, l_lane_lon = calc_new_geopos_from_2d_vector(df['lat'][length], df['long'][length], df['heading'][length],
df['lin_left_beginn_x'][i],
df['lin_left_y_abstand'][i], geodetic)
r_lane_lat_list.append(r_lane_lat)
r_lane_lon_list.append(r_lane_lon)
l_lane_lat_list.append(l_lane_lat)
l_lane_lon_list.append(l_lane_lon)
# Give each line an ID:
left = []
right = []
# Detect lane change for id change
for i in range(length):
index = i + 1
if df['lin_left_y_abstand'][index] < 0:
left.append(index)
if df['lin_right_y_abstand'][index] > 0:
right.append(index)
left_index = []
right_index = []
# Delete consecutive values
for i in range(len(left) - 1):
if left[i] == left[i + 1] - 1:
left_index.append(left[i])
for i in range(len(left_index)):
left.remove(left_index[i])
for i in range(len(right) - 1):
if right[i] == right[i + 1] - 1:
right_index.append(right[i])
for i in range(len(right_index)):
right.remove(right_index[i])
# Create single list with respective label list
left_right = left + right
left_right = sorted(left_right)
left_right_label = []
for i in range(len(left_right)):
if left_right[i] in left:
left_right_label.append('left')
if left_right[i] in right:
left_right_label.append('right')
df_out = pd.DataFrame()
if len(left_right) == 0:
df_out['right_lane_lat'] = r_lane_lat_list
df_out['right_lane_lon'] = r_lane_lon_list
df_out['left_lane_lat'] = l_lane_lat_list
df_out['left_lane_lon'] = l_lane_lon_list
else:
array = np.empty(len(r_lane_lat_list))
array[:] = np.NaN
df_out['0lat'] = array
df_out['0lon'] = array
df_out['1lat'] = array
df_out['1lon'] = array
for i in range(len(left_right)):
df_out[str(i + 2) + 'lat'] = array
df_out[str(i + 2) + 'lon'] = array
df_out.iloc[0:left_right[0] + 1, 0] = r_lane_lat_list[0:left_right[0] + 1]
df_out.iloc[0:left_right[0] + 1, 1] = r_lane_lon_list[0:left_right[0] + 1]
df_out.iloc[0:left_right[0] + 1, 2] = l_lane_lat_list[0:left_right[0] + 1]
df_out.iloc[0:left_right[0] + 1, 3] = l_lane_lon_list[0:left_right[0] + 1]
counter = 4
id_right = [0, 1]
id_left = [2, 3]
for i in range(len(left_right)):
# Get starting and ending index of next lane slice
current_index = left_right[i] + 1
if len(left_right) - 1 == i:
next_index = df.shape[0]
else:
next_index = left_right[i + 1] + 1
if left_right_label[i] == 'left':
id_right = id_left
id_left = [counter, counter + 1]
counter = counter + 2
if left_right_label[i] == 'right':
id_left = id_right
id_right = [counter, counter + 1]
counter = counter + 2
df_out.iloc[current_index:next_index, id_right[0]] = r_lane_lat_list[current_index:next_index]
df_out.iloc[current_index:next_index, id_right[1]] = r_lane_lon_list[current_index:next_index]
df_out.iloc[current_index:next_index, id_left[0]] = l_lane_lat_list[current_index:next_index]
df_out.iloc[current_index:next_index, id_left[1]] = l_lane_lon_list[current_index:next_index]
return df_out
def get_proj_from_open_drive(open_drive_path: str) -> str:
"""
Get Coordinate system infos from OpenDrive file
Args:
open_drive_path: Path to OpenDRIVE file
Returns:
object (str): Coordinate system
"""
if not isinstance(open_drive_path, str):
raise TypeError("input must be a str")
open_drive = open(open_drive_path, 'r')
proj_open_drive = 'unknown'
for line in open_drive:
if line.find("geoReference") >= 0:
proj_open_drive = pyproj.Proj(line[line.find("[CDATA[") + 7:line.find("]]")])
break
if proj_open_drive == 'unknown':
warnings.warn("no valid coordinate system found in OpenDRIVE -> coordinates won't be correct", UserWarning)
open_drive.close()
return proj_open_drive
<file_sep>import struct
import pandas as pd
import math
import warnings
from osc_generator.tools.user_config import UserConfig
import os
try:
from osc_generator.tools.OSI.OSITrace import OSITrace
except ImportError:
warnings.warn("Feature OSI Input Data is not available. Download from: https://github.com/OpenSimulationInterface/open-simulation-interface/blob/master/format/OSITrace.py", UserWarning)
def get_user_defined_attributes(osi_message, path):
"""
Obtain user defined attributes from the OSI message.
Writes to config file
:param :
osi_message: the initial message from the OSI file
path: for directory in which to write config file
"""
bb_dimension = []
bb_center = []
for obj in osi_message.global_ground_truth.moving_object:
if obj.base.HasField('dimension'):
# object bounding box dimensions
bb_dimension.append([obj.base.dimension.width, obj.base.dimension.length, obj.base.dimension.height])
else:
bb_dimension.append(None)
if obj.HasField('vehicle_attributes'):
if obj.vehicle_attributes.HasField('bbcenter_to_rear'):
# object bounding box center point, from rear axle
bb_center.append([obj.vehicle_attributes.bbcenter_to_rear.x,
obj.vehicle_attributes.bbcenter_to_rear.y,
obj.vehicle_attributes.bbcenter_to_rear.z])
else:
bb_center.append(None)
else:
bb_center.append(None)
dir_name = os.path.dirname(path)
user_config = UserConfig(dir_name)
user_config.read_config()
user_config.object_boundingbox = bb_dimension
user_config.bbcenter_to_rear = bb_center
user_config.write_config()
def osi2df(path: str) -> pd.DataFrame:
"""
Transfer osi messages into pandas dataframe.
:param path: path to osi file
:return: pandas dataframe
"""
if not isinstance(path, str):
raise TypeError("input must be a str")
trace = OSITrace()
trace.from_file(path=path)
messages = trace.get_messages()
m = trace.get_message_by_index(0)
number_of_vehicles = len(m.global_ground_truth.moving_object)
get_user_defined_attributes(m, path)
lists: list = [[] for _ in range(15)]
for i in messages:
timestamp = i.global_ground_truth.timestamp.seconds + i.global_ground_truth.timestamp.nanos / 1000000000
lists[0].append(timestamp)
for v in i.global_ground_truth.moving_object:
lists[1].append(v.base.position.x)
lists[2].append(v.base.position.y)
lists[3].append(v.base.velocity.x)
lists[4].append(v.base.velocity.y)
lists[5].append(v.base.orientation.yaw)
lists[6].append(v.vehicle_classification.type)
for lane in i.global_ground_truth.lane_boundary:
if lane.id.value == 0:
lists[7].append(lane.classification.type)
for boundary_line in lane.boundary_line:
lists[8].append(boundary_line.position.x)
lists[9].append(boundary_line.position.y)
lists[10].append(boundary_line.width)
elif lane.id.value == 1:
lists[11].append(lane.classification.type)
for boundary_line in lane.boundary_line:
lists[12].append(boundary_line.position.x)
lists[13].append(boundary_line.position.y)
lists[14].append(boundary_line.width)
else:
pass
df = pd.DataFrame(lists[0], columns=['timestamp'])
df.insert(1, 'lat', lists[1][0::number_of_vehicles])
df.insert(2, 'long', lists[2][0::number_of_vehicles])
df.insert(3, 'heading', lists[5][0::number_of_vehicles])
df.insert(4, 'speed', lists[3][0::number_of_vehicles])
df.insert(5, 'lin_right_beginn_x', lists[8])
df.insert(6, 'lin_right_y_abstand', lists[9])
df.insert(7, 'lin_right_breite', lists[10])
df.insert(8, 'lin_right_typ', lists[7])
df.insert(9, 'lin_left_beginn_x', lists[12])
df.insert(10, 'lin_left_y_abstand', lists[13])
df.insert(11, 'lin_left_breite', lists[14])
df.insert(12, 'lin_left_typ', lists[11])
for i in range(number_of_vehicles - 1):
i += 1
df.insert(i * 5 + 8, 'pos_x_' + str(i), lists[1][i::number_of_vehicles])
df.insert(i * 5 + 9, 'pos_y_' + str(i), lists[2][i::number_of_vehicles])
df.insert(i * 5 + 10, 'speed_x_' + str(i), lists[3][i::number_of_vehicles])
df.insert(i * 5 + 11, 'speed_y_' + str(i), lists[4][i::number_of_vehicles])
df.insert(i * 5 + 12, 'class_' + str(i), lists[6][i::number_of_vehicles])
trace.scenario_file.close()
return df<file_sep>-r requirements.txt
pytest~=6.2.4
xmldiff~=2.4<file_sep># ****************************************************************************
# @converter.py
#
# @copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
import numpy as np
import pandas as pd
import os
from typing import Union
from osc_generator.tools import utils
from osc_generator.tools import man_helpers
from osc_generator.tools.coord_calculations import transform_lanes_rel2abs
from osc_generator.tools.scenario_writer import convert_to_osc
from osc_generator.tools.osi_transformer import osi2df
class Converter:
"""
Main class for converter operations
"""
def __init__(self):
self.osc_version: str = '1.0'
self.trajectories_path: str = ''
self.opendrive_path: str = ''
self.outfile = None
self.use_folder: bool = True
self.dir_name: str = ''
self.section_name: str = ''
self.df = None
self.df_lanes = None
self.ego_maneuver_array = None
self.inf_maneuver_array = None
self.objlist = None
self.objects = None
self.ego = None
self.movobj_grps_coord = None
def set_paths(self, trajectories_path: str, opendrive_path: str, output_scenario_path: str = None):
"""
This method should be called before calling other class methods
Args:
trajectories_path: Path to the file containing the object trajectories used as input
opendrive_path: Path to the OpenDRIVE file which describes the road net which the objects are using
output_scenario_path: Output file path and name. If not specified, a directory and name will be chosen.
If the file already exists, it will be overwritten.
"""
if os.path.isfile(trajectories_path):
self.trajectories_path = trajectories_path
else:
raise FileNotFoundError("file not found: " + str(trajectories_path))
if os.path.isfile(opendrive_path):
self.opendrive_path = opendrive_path
else:
raise FileNotFoundError("file not found: " + str(opendrive_path))
if output_scenario_path is not None:
output_dir_path = os.path.dirname(os.path.abspath(output_scenario_path))
if os.path.isdir(output_dir_path):
self.outfile = output_scenario_path
else:
raise FileNotFoundError("folder not found: " + str(output_dir_path))
if self.use_folder:
path_name = self.trajectories_path.rsplit(os.path.sep)
self.section_name = path_name[-1]
self.dir_name = os.path.dirname(self.trajectories_path)
else:
raise NotImplementedError("use_folder flag is going to be removed")
def process_trajectories(self, relative: bool = True, df_lanes: pd.DataFrame = None):
"""
Process trajectories file and convert it to cleaned main dataframe
and a dataframe for absolute coordination of lanes
Args:
relative: True -> coordinates of lanes and vehicles are relative to ego.
df_lanes: If absolute coordinates are used, the lane coordinates needs to be passed here.
"""
data_type = ''
if self.trajectories_path.endswith(".csv"):
df = pd.read_csv(self.trajectories_path)
data_type = 'csv'
elif self.trajectories_path.endswith(".osi"):
df = osi2df(self.trajectories_path)
data_type = 'osi'
if relative:
# Delete not relevant objects (too far away, not visible long enough, not plausible)
movobj_grps = utils.find_vars('pos_x_|pos_y_|speed_x_|speed_y_|class_', df.columns, reshape=True)
df, del_obj = utils.delete_irrelevant_objects(df, movobj_grps, min_nofcases=20, max_posx_min=50.0,
max_posx_nofcases_ratio=10.0)
# Create absolute lane points from relative
self.df_lanes = transform_lanes_rel2abs(df, data_type)
# Compute coordinates of Objects
# Find posx-posy movobj_grps and define lat-lon movobj_grps
movobj_grps = utils.find_vars('pos_x_|pos_y_|speed_x_', df.columns, reshape=True)
movobj_grps_coord = []
for p in movobj_grps:
movobj_grps_coord.append([p[0].replace('pos_x', 'lat'), p[1].replace('pos_y', 'lon'),
p[2].replace('speed_x', 'speed'), p[2].replace('speed_x', 'class')])
# Compute Coordinates and absolute speed
for p, q in zip(movobj_grps, movobj_grps_coord):
coordx = []
coordy = []
for k in range(len(df[p])):
if not any(list(pd.isna(df.loc[k, p]))):
n = utils.calc_new_geopos_from_2d_vector_on_spheric_earth(curr_coords=df.loc[k, ["lat", "long"]],
heading=df.loc[k, "heading"],
dist_x=df.loc[k, p[0]], dist_y=df.loc[k, p[1]])
coordx.append(n[0])
coordy.append(n[1])
else:
coordx.append(np.nan)
coordy.append(np.nan)
df[q[0]] = coordx
df[q[1]] = coordy
df[q[2]] = abs(df[p[2]])
# Delete and reorder columns
delete_vars = utils.find_vars('speed_x_|speed_y_', df.columns)
df = df.drop(columns=delete_vars)
reorder_vars1 = ['timestamp', 'lat', 'long', 'heading', 'speed']
reorder_vars3 = utils.flatten(movobj_grps_coord)
self.df = df[reorder_vars1 + reorder_vars3]
else:
# Delete not relevant objects (too far away, too short seen, not plausible)
movobj_grps = utils.find_vars('lat_|lon_|speed_|class_', df.columns, reshape=True)
df, del_obj = utils.delete_irrelevant_objects(df, movobj_grps, min_nofcases=20, max_posx_min=50.0,
max_posx_nofcases_ratio=10.0)
if df_lanes is None:
raise ValueError('if absolute coordinates are used, the lane coordinates needs '
'to be passed in process_inter func. as a dataframe.')
else:
self.df_lanes = df_lanes
self.df = df
if self.use_folder:
self.df.to_csv(os.path.join(self.dir_name, 'df33.csv'))
else:
raise NotImplementedError("use_folder flag is going to be removed")
def label_maneuvers(self, acc_threshold: Union[float, np.ndarray] = 0.2, optimize_acc: bool = False,
generate_kml: bool = False):
"""
Main dataframe and lanes dataframe will be used here to label the maneuvers.
Args:
acc_threshold: Acceleration threshold for labeling
optimize_acc: Option to get optimal acceleration threshold
generate_kml: Option to create kml files
"""
if optimize_acc:
acc_thres_opt = man_helpers.calc_opt_acc_thresh(self.df, self.df_lanes, self.opendrive_path,
self.use_folder, self.dir_name)
acc_threshold = acc_thres_opt
ego_maneuver_array, inf_maneuver_array, objlist, objects, ego, movobj_grps_coord = man_helpers.label_maneuvers(
self.df, self.df_lanes, acc_threshold, generate_kml,
self.opendrive_path, self.use_folder, self.dir_name)
else:
ego_maneuver_array, inf_maneuver_array, objlist, objects, ego, movobj_grps_coord = man_helpers.label_maneuvers(
self.df, self.df_lanes, acc_threshold, generate_kml,
self.opendrive_path, self.use_folder, self.dir_name)
self.ego_maneuver_array = ego_maneuver_array
self.inf_maneuver_array = inf_maneuver_array
self.objlist = objlist
self.objects = objects
self.ego = ego
self.movobj_grps_coord = movobj_grps_coord
def write_scenario(self, plot: bool = False,
radius_pos_trigger: float = 2.0, timebased_lon: bool = True, timebased_lat: bool = False,
output: str = 'xosc'):
"""
Writes the trajectories or maneuvers in selected file formats.
Args:
plot: Ploting option
radius_pos_trigger: Defines the radius of position trigger
timebased_lon: True -> timebase trigger for longitudinal maneuver will be used. False -> position base
timebased_lat: True -> timebase trigger for latitudinal maneuver will be used. False -> position base
output: Pption for different file formats. To write OpenScenario -> 'xosc'.
"""
if output == 'xosc':
outfile = convert_to_osc(self.df, self.ego, self.objects, self.ego_maneuver_array, self.inf_maneuver_array,
self.movobj_grps_coord, self.objlist, plot,
self.opendrive_path, self.use_folder, timebased_lon, timebased_lat,
self.section_name, radius_pos_trigger, self.dir_name, self.osc_version, self.outfile)
self.outfile = outfile
else:
raise NotImplementedError('selected output option is not implemented')
<file_sep># ****************************************************************************
# @test_man_helpers.py
#
# @copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
import pandas as pd
import numpy as np
from osc_generator.tools import man_helpers
import pytest
import os
@pytest.fixture
def test_data_dir():
return os.path.join(os.path.dirname(__file__), '../test_data')
@pytest.fixture
def maneuver(test_data_dir):
return pd.read_csv(os.path.join(test_data_dir, 'temp_ego_maneuver_array.csv'))
@pytest.fixture
def model_speed(test_data_dir):
return np.load(os.path.join(test_data_dir, 'model_speed.npy'))
@pytest.fixture
def prepared_df(test_data_dir):
return pd.read_csv(os.path.join(test_data_dir, 'prepared_df.csv'))
@pytest.fixture
def df_lanes(test_data_dir):
return pd.read_csv(os.path.join(test_data_dir, 'df_lanes.csv'))
@pytest.fixture
def odr_path(test_data_dir):
opendrive_path = os.path.join(test_data_dir, '2017-04-04_Testfeld_A9_Nord_offset.xodr')
return opendrive_path
@pytest.fixture
def expected_ego_maneuver_array_0(test_data_dir):
return np.load(os.path.join(test_data_dir, 'ego_maneuver_array_0.npy'))
class TestManHelpers:
def test_speed_model(self, maneuver, model_speed):
actual = man_helpers.create_speed_model(maneuver, 99.57389)
expected = model_speed
np.testing.assert_array_almost_equal_nulp(actual, expected)
np.testing.assert_array_equal(actual, expected)
def test_opt_acc(self, prepared_df, df_lanes, odr_path, test_data_dir):
actual = man_helpers.calc_opt_acc_thresh(prepared_df,
df_lanes,
odr_path,
True,
test_data_dir)
expected = np.array([0.05, 0.1, 0.1])
np.testing.assert_array_almost_equal_nulp(actual, expected)
np.testing.assert_array_equal(actual, expected)
def test_man_labeling(self, prepared_df, df_lanes, odr_path, expected_ego_maneuver_array_0, test_data_dir):
acc_threshold = np.array([0.05, 0.1, 0.1])
ego_maneuver_array, inf_maneuver_array, objlist, objects, ego, movobj_grps_coord = man_helpers.label_maneuvers(
prepared_df,
df_lanes,
acc_threshold,
False,
odr_path,
True,
test_data_dir)
expected_ego = [3728.331392794964, -17465.94162228238, 27.65941358024691, 7.663740745507101]
np.testing.assert_array_equal(ego_maneuver_array[0], expected_ego_maneuver_array_0)
np.testing.assert_array_equal(ego, expected_ego)
<file_sep># ****************************************************************************
# @rulebased.py
#
# @copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from shapely.geometry import MultiPoint, LineString, Point
from scipy.signal import find_peaks
def create_longitudinal_maneuver_vectors(speed: pd.Series, acceleration_definition_threshold: float = 0.2,
acceleration_definition_min_length: float = 2.0,
speed_threshold_no_more_start: float = 20.0, plot: bool = False) -> tuple:
"""
Creates vectors for the longitudinal vehicle maneuvers.
Args:
speed: Vehicle speed information
acceleration_definition_threshold: Due to noise, if acc is bigger --> ego is accelerating
acceleration_definition_min_length: Minimum number in frames, if ego vehicle state is shorter --> ignore
speed_threshold_no_more_start: In kmh, if start is labeled and this velocity is surpassed --> finish labeling
plot: Plotting option
Returns:
object (tuple): Vectors with vehicle speed maneuvers:
accelerate_array,
start_array,
keep_velocity_array,
standstill_array,
decelerate_array,
stop_array,
reversing_array
"""
if not isinstance(speed, pd.Series):
raise TypeError("input must be a pd.Series")
if not isinstance(acceleration_definition_threshold, float):
raise TypeError("input must be a float")
if not isinstance(acceleration_definition_min_length, float):
raise TypeError("input must be a float")
if not isinstance(speed_threshold_no_more_start, float):
raise TypeError("input must be a float")
if not isinstance(plot, bool):
raise TypeError("input must be a bool")
new_speed = speed / 3.6 # Conversion km/h --> m/s
speed_gradient = new_speed.diff(periods=1) / 0.1 # Delta_ay/delta_t
speed_gradient = speed_gradient.rolling(window=5, min_periods=0).mean()
speed_gradient = speed_gradient.shift(periods=-2, fill_value=speed_gradient[speed_gradient.shape[0] - 1])
speed_gradient[speed.isnull()] = np.NaN
acceleration_x = speed_gradient
accelerate_array = np.zeros(speed.shape[0])
start_array = np.zeros(speed.shape[0])
keep_velocity_array = np.zeros(speed.shape[0])
standstill_array = np.zeros(speed.shape[0])
decelerate_array = np.zeros(speed.shape[0])
stop_array = np.zeros(speed.shape[0])
reversing_array = np.zeros(speed.shape[0])
# Initializations
counter_acceleration = 0
acceleration_start = False
counter_deceleration = 0
deceleration_start = False
counter_keep = 0
keep_start = False
counter_start = -1
counter_stop = 0
counter_buffer = 0
length_speed_rows = 0
for i in range(speed.shape[0]):
# Future proofing if breaks are introduced in the loop
length_speed_rows = i
# Get acceleration ego
if acceleration_x[i] > acceleration_definition_threshold:
acceleration_start = True
counter_acceleration += 1
else:
if acceleration_start & (counter_acceleration >= acceleration_definition_min_length):
if counter_buffer > 0:
counter_acceleration += counter_buffer
accelerate_array[i - counter_acceleration: i] = 1
counter_buffer = 0
else:
counter_buffer += counter_acceleration
counter_acceleration = 0
acceleration_start = False
# Get deceleration ego
if acceleration_x[i] < -acceleration_definition_threshold:
deceleration_start = True
counter_deceleration += 1
else:
if deceleration_start & (counter_deceleration >= acceleration_definition_min_length):
if counter_buffer > 0:
counter_deceleration += counter_buffer
decelerate_array[i - counter_deceleration: i] = 1
counter_buffer = 0
else:
counter_buffer += counter_deceleration
counter_deceleration = 0
deceleration_start = False
# Get keep velocity ego
if (acceleration_x[i] < acceleration_definition_threshold) & (
acceleration_x[i] > -acceleration_definition_threshold) & (speed[i] != 0):
keep_start = True
counter_keep += 1
else:
if keep_start & (counter_keep > acceleration_definition_min_length):
if counter_buffer > 0:
counter_keep += counter_buffer
keep_velocity_array[i - counter_keep: i] = 1
counter_buffer = 0
else:
counter_buffer += counter_keep
counter_keep = 0
keep_start = False
# Get reversing
if speed[i] < 0:
reversing_array[i] = 1
# Get standstill
if speed[i] == 0:
standstill_array[i] = 1
# Get start
# If counter > 0, counter increment (works only after start detection in next if statement)
if (speed[i] > 0) & (counter_start > 0):
counter_start += 1
start_array[(i - counter_start): i] = 1
# Break criteria:
if speed[i] > speed_threshold_no_more_start:
counter_start = -1
if deceleration_start:
counter_start = -1
# If start detected set counter to 1
if (speed[i] == 0) & (counter_start <= 1):
counter_start = 1
if (speed[i] > 0) & (counter_start <= 1):
counter_start = 0
# Get stop
if (counter_stop > 0) & (speed[i] == 0):
stop_array[i - counter_stop: i] = 1
counter_stop = 0
if (speed[i] < speed_threshold_no_more_start) & (speed[i] != 0):
counter_stop += 1
else:
counter_stop = 0
if acceleration_start:
counter_stop = 0
if keep_start:
counter_stop = 0
counter_acceleration += counter_buffer
counter_deceleration += counter_buffer
counter_keep += counter_buffer
# Make sure that last maneuver is labeled
if acceleration_start:
accelerate_array[length_speed_rows - counter_acceleration: length_speed_rows] = 1
if deceleration_start:
decelerate_array[length_speed_rows - counter_deceleration: length_speed_rows] = 1
if keep_start:
keep_velocity_array[length_speed_rows - counter_keep: length_speed_rows] = 1
if plot:
fill_array = accelerate_array.astype('bool') | decelerate_array.astype('bool') | \
keep_velocity_array.astype('bool') | reversing_array.astype('bool') | \
standstill_array.astype('bool') | start_array.astype('bool') | stop_array.astype('bool')
plt.subplot(10, 1, 1)
plt.plot(speed)
plt.subplot(10, 1, 2)
plt.plot(acceleration_x)
plt.subplot(10, 1, 3)
plt.plot(accelerate_array)
plt.subplot(10, 1, 4)
plt.plot(decelerate_array)
plt.subplot(10, 1, 5)
plt.plot(keep_velocity_array)
plt.subplot(10, 1, 6)
plt.plot(reversing_array)
plt.subplot(10, 1, 7)
plt.plot(standstill_array)
plt.subplot(10, 1, 8)
plt.plot(start_array)
plt.subplot(10, 1, 9)
plt.plot(stop_array)
plt.subplot(10, 1, 10)
plt.plot(fill_array)
plt.show()
return accelerate_array, start_array, keep_velocity_array, standstill_array, decelerate_array, stop_array, \
reversing_array
def create_lateral_maneuver_vectors(df_lanes: pd.DataFrame, lat: pd.core.series.Series,
lon: pd.core.series.Series, plot: bool = False) -> tuple:
"""
Get lane change maneuver from lanes with absolute coordinates
Args:
df_lanes: Lane coordinates
lat: Latitude of the vehicle
lon: Longitude of the vehicle
plot: Plotting option
Returns:
object (tuple): Vectors with vehicle lane change maneuvers:
"""
if not isinstance(df_lanes, pd.DataFrame):
raise TypeError("input must be a pd.DataFrame")
if not isinstance(lat, pd.core.series.Series):
raise TypeError("input must be a pd.core.series.Series")
if not isinstance(lon, pd.core.series.Series):
raise TypeError("input must be a pd.core.series.Series")
if not isinstance(plot, bool):
raise TypeError("input must be a bool")
def find_intersection(x_targ_series, y_targ_series, x_ref_series, y_ref_series):
"""
Helper function. detects lanechange
Args:
x_targ_series (pd.core.series.Series): series containing x-components
y_targ_series (pd.core.series.Series): series containing y-components
x_ref_series (pd.core.series.Series): series containing x-components
y_ref_series (pd.core.series.Series): series containing y-components
Returns:
object (np.ndarray, np.ndarray): arrays indicating lane change left and right:
left_lane_change, right_lane_change,
left_lane_change, right_lane_change
"""
x_targ_arr = np.asarray(x_targ_series)
y_targ_arr = np.asarray(y_targ_series)
x_ref_arr = np.asarray(x_ref_series)
y_ref_arr = np.asarray(y_ref_series)
l1 = LineString(list(zip(x_ref_arr[~np.isnan(x_ref_arr)], y_ref_arr[~np.isnan(y_ref_arr)])))
l2 = LineString(list(zip(x_targ_arr, y_targ_arr)))
# Find "ideal" intersection point
intersection = l1.intersection(l2)
if intersection.is_empty:
xs = []
ys = []
elif isinstance(intersection, MultiPoint):
xs = [point.x for point in intersection.geoms]
ys = [point.y for point in intersection.geoms]
else:
xs = [intersection.x]
ys = [intersection.y]
dist = []
dist2 = []
dist3 = []
left_lanechange_array = np.zeros(len(x_targ_arr))
right_lanechange_array = np.zeros(len(x_targ_arr))
if len(xs) > 0:
for x_targ_index in range(len(x_targ_arr)):
# Find the nearest trajectory point to "ideal" intersection point
dist.append((x_targ_arr[x_targ_index] - xs[0]) ** 2 + (y_targ_arr[x_targ_index] - ys[0]) ** 2)
# Compute the distance between trajectory and crossed lane
point = Point(x_targ_arr[x_targ_index], y_targ_arr[x_targ_index])
dist2.append(point.distance(l1))
for x_ref_index in range(len(x_ref_arr)):
dist3.append((x_ref_arr[x_ref_index] - xs[0]) ** 2 + (y_ref_arr[x_ref_index] - ys[0]) ** 2)
# Min of the nearest trajectory point is the intersection with its respective index
index = dist.index(min(dist))
# Min if nearest reference point is the intersection with its respective index
index2 = dist3.index(min(dist3))
# Find previous and next extrema for
peaks, _ = find_peaks(dist2, height=0)
pos = np.searchsorted(peaks, index)
if pos == 0:
start_index = 0
else:
start_index = peaks[pos - 1]
if pos == len(peaks):
end_index = len(x_targ_arr)
else:
end_index = peaks[pos]
if index + 1 == len(x_targ_arr):
point1 = [x_ref_arr[index2 - 1], y_ref_arr[index2 - 1]]
point2 = [x_ref_arr[index2], y_ref_arr[index2]]
point3 = [x_targ_arr[index - 1], y_targ_arr[index - 1]]
point4 = [x_targ_arr[index], y_targ_arr[index]]
elif index == 0:
point1 = [x_ref_arr[index2], y_ref_arr[index2]]
point2 = [x_ref_arr[index2 + 1], y_ref_arr[index2 + 1]]
point3 = [x_targ_arr[index], y_targ_arr[index]]
point4 = [x_targ_arr[index + 1], y_targ_arr[index + 1]]
else:
point1 = [x_ref_arr[index2 - 1], y_ref_arr[index2 - 1]]
point2 = [x_ref_arr[index2 + 1], y_ref_arr[index2 + 1]]
point3 = [x_targ_arr[index - 1], y_targ_arr[index - 1]]
point4 = [x_targ_arr[index + 1], y_targ_arr[index + 1]]
v0 = np.array(point2) - np.array(point1)
v1 = np.array(point4) - np.array(point3)
angle = np.math.atan2(np.linalg.det([v0, v1]), np.dot(v0, v1))
deg = np.degrees(angle)
# If left lane change
if deg < 0:
left_lanechange_array[start_index:end_index] = 1
else:
# If right lane change
right_lanechange_array[start_index:end_index] = 1
return left_lanechange_array, right_lanechange_array
if plot:
for i in range(int(df_lanes.shape[1] / 2)):
plt.scatter(df_lanes.iloc[:, i * 2], df_lanes.iloc[:, i * 2 + 1])
plt.scatter(lat, lon)
plt.show()
clean_lat = lat[~np.isnan(lat)]
clean_lon = lon[~np.isnan(lon)]
# Loop over all available lanes from df_lane
number_of_lanes = int(df_lanes.shape[1] / 2)
left_lane_change_array = np.zeros(len(clean_lat))
right_lane_change_array = np.zeros(len(clean_lat))
for i in range(number_of_lanes):
x_ref = df_lanes.iloc[:, (i * 2)] # Lat
y_ref = df_lanes.iloc[:, (i * 2) + 1] # Lon
left, right = find_intersection(clean_lat, clean_lon, x_ref, y_ref)
left_lane_change_array = np.logical_or(left_lane_change_array, left)
right_lane_change_array = np.logical_or(right_lane_change_array, right)
left_lane_change = np.zeros(len(lat))
left_lane_change[~np.isnan(lat)] = left_lane_change_array
right_lane_change = np.zeros(len(lon))
right_lane_change[~np.isnan(lon)] = right_lane_change_array
return left_lane_change, right_lane_change
<file_sep># ****************************************************************************
# @test_coord_calculations.py
#
# @copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
import pandas as pd
from osc_generator.tools import coord_calculations
import pytest
import os
@pytest.fixture
def test_data_dir():
return os.path.join(os.path.dirname(__file__), '../test_data')
@pytest.fixture
def df(test_data_dir):
return pd.read_csv(os.path.join(test_data_dir, 'trajectories_file.csv'))
@pytest.fixture
def df_lanes(test_data_dir):
return pd.read_csv(os.path.join(test_data_dir, 'df_lanes.csv'))
@pytest.fixture
def odr_path(test_data_dir):
opendrive_path = os.path.join(test_data_dir, r'2017-04-04_Testfeld_A9_Nord_offset.xodr')
return opendrive_path
class TestCoordCalculations:
def test_lanes_rel2abs_from_csv(self, df, df_lanes):
actual = coord_calculations.transform_lanes_rel2abs(df, 'csv')
expected = df_lanes
pd.testing.assert_frame_equal(actual, expected)
def test_get_proj_from_open_drive(self, odr_path):
actual = coord_calculations.get_proj_from_open_drive(open_drive_path=odr_path)
expected = '+proj=tmerc +lat_0=0 +lon_0=9 +k=0.9996 +x_0=-177308 +y_0=-5425923 +datum=WGS84 +units=m +no_defs'
assert actual.srs == expected
<file_sep>from setuptools import setup, find_packages
import os
exec(open(os.path.join(os.path.dirname(__file__), 'osc_generator', 'version.py')).read())
# with os.path.join(os.path.dirname(__file__), 'README.md') as file_path:
file_path = os.path.join(os.path.dirname(__file__), 'README.md')
if os.path.isfile(file_path):
with open(file_path, 'r+') as file:
lines = file.readlines()
for idx, line in enumerate(lines):
if line.startswith('version = {'):
lines[idx] = 'version = {' + str(__version__) + '}\n'
file.seek(0)
file.writelines(lines)
file.truncate()
# with os.path.join(os.path.dirname(__file__), 'CITATION.cff') as file_path:
file_path = os.path.join(os.path.dirname(__file__), 'CITATION.cff')
if os.path.isfile(file_path):
with open(file_path, 'r+') as file:
lines = file.readlines()
for idx, line in enumerate(lines):
if line.startswith('version: '):
lines[idx] = 'version: "' + str(__version__) + '"\n'
file.seek(0)
file.writelines(lines)
file.truncate()
with open("README.md", "r") as fh:
long_description = fh.read()
CLASSIFIERS = """\
Development Status :: 3 - Alpha
Intended Audience :: Science/Research
Intended Audience :: Developers
License :: OSI Approved :: Apache Software License
Natural Language :: English
Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Programming Language :: Python :: 3.9
Programming Language :: Python :: 3.10
Programming Language :: Python :: 3 :: Only
Programming Language :: Python :: Implementation :: CPython
Topic :: Scientific/Engineering
Topic :: Scientific/Engineering :: GIS
Topic :: Software Development
Typing :: Stubs Only
Operating System :: Microsoft :: Windows
"""
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as f:
install_requires = [l.strip() for l in f.readlines()]
setup(name='osc_generator',
version=str(__version__),
description='OSC-Generator can be used to generate ASAM OpenSCENARIO files from vehicle data and an ASAM OpenDRIVE file.',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://github.com/EFS-OpenSource/OSC-Generator',
project_urls={
"Bug Tracker": "https://github.com/EFS-OpenSource/OSC-Generator/issues",
"Source Code": "https://github.com/EFS-OpenSource/OSC-Generator"},
author='<NAME>.',
author_email='<EMAIL>',
packages=find_packages(exclude=('tests',)),
classifiers=[_f for _f in CLASSIFIERS.split('\n') if _f],
python_requires='>=3.7',
entry_points={'console_scripts': ['osc_generator=osc_generator.osc_generator:main']},
install_requires=install_requires,
)
<file_sep># ****************************************************************************
# @man_helpers.py
#
# @copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
"""
helper functions for maneuver abstraction.
"""
import pyproj
import simplekml
import math
import pandas as pd
import numpy as np
import os
from typing import Union
from osc_generator.tools.coord_calculations import get_proj_from_open_drive
from osc_generator.tools import rulebased, utils
def convert_maneuvers_to_kml(lat: pd.DataFrame, lon: pd.DataFrame, maneuvers: pd.DataFrame, ego: bool) -> simplekml.Kml:
"""
Convert manuevers from pandas Dataframe to kml
Args:
lat: Latitude
lon: Longitude
maneuvers: Maneuvers of the vehicle
ego: For the ego vehicle True
Returns:
object (simplekml.Kml): Kml file containing the maneuvers
"""
if not isinstance(lat, pd.DataFrame):
raise TypeError("input must be a pd.DataFrame")
if not isinstance(lon, pd.DataFrame):
raise TypeError("input must be a pd.DataFrame")
if not isinstance(maneuvers, pd.DataFrame):
raise TypeError("input must be a pd.DataFrame")
if not isinstance(ego, bool):
raise TypeError("input must be a bool")
kml = simplekml.Kml()
overview_doc = kml.newdocument(name='Overview')
old_lon = 0
old_lat = 0
accelerate = maneuvers['FM_EGO_accelerate']
accelerate_doc = kml.newdocument(name='accelerate')
velocity = maneuvers['FM_EGO_keep_velocity']
velocity_doc = kml.newdocument(name='velocity')
standstill = maneuvers['FM_EGO_standstill']
standstill_doc = kml.newdocument(name='standstill')
decelerate = maneuvers['FM_EGO_decelerate']
decelerate_doc = kml.newdocument(name='decelerate')
lane_change_left = None
lane_change_left_doc = None
lane_change_right = None
lane_change_right_doc = None
if ego is True:
lane_change_left = maneuvers['FM_INF_lane_change_left']
lane_change_left_doc = kml.newdocument(name='lane_change_left')
lane_change_right = maneuvers['FM_INF_lane_change_right']
lane_change_right_doc = kml.newdocument(name='lane_change_right')
for row in range(lat.shape[0]):
if not (pd.isna(lat.loc[row])) or not (pd.isna(lon.loc[row])):
if old_lat != 0 and old_lon != 0:
pathway = overview_doc.newlinestring()
pathway.coords = [(old_lon, old_lat), (lon.loc[row], lat.loc[row])]
pathway.style.linestyle.width = 8
pathway.style.linestyle.color = simplekml.Color.rgb(0, 0, 0)
if accelerate[row] == 1:
pathway = accelerate_doc.newlinestring()
pathway.coords = [(old_lon, old_lat), (lon.loc[row], lat.loc[row])]
pathway.style.linestyle.width = 4
pathway.style.linestyle.color = simplekml.Color.rgb(0, 255, 251)
if velocity[row] == 1:
pathway = velocity_doc.newlinestring()
pathway.coords = [(old_lon, old_lat), (lon.loc[row], lat.loc[row])]
pathway.style.linestyle.width = 4
pathway.style.linestyle.color = simplekml.Color.rgb(0, 143, 255)
if standstill[row] == 1:
pathway = standstill_doc.newlinestring()
pathway.coords = [(old_lon, old_lat), (lon.loc[row], lat.loc[row])]
pathway.style.linestyle.width = 4
pathway.style.linestyle.color = simplekml.Color.rgb(0, 0, 0)
if decelerate[row] == 1:
pathway = decelerate_doc.newlinestring()
pathway.coords = [(old_lon, old_lat), (lon.loc[row], lat.loc[row])]
pathway.style.linestyle.width = 4
pathway.style.linestyle.color = simplekml.Color.rgb(0, 23, 255)
if ego is True:
if lane_change_left[row] == 1:
pathway = lane_change_left_doc.newlinestring()
pathway.coords = [(old_lon, old_lat), (lon.loc[row], lat.loc[row])]
pathway.style.linestyle.width = 4
pathway.style.linestyle.color = simplekml.Color.rgb(255, 169, 59)
if lane_change_right[row] == 1:
pathway = lane_change_right_doc.newlinestring()
pathway.coords = [(old_lon, old_lat), (lon.loc[row], lat.loc[row])]
pathway.style.linestyle.width = 4
pathway.style.linestyle.color = simplekml.Color.rgb(209, 126, 20)
old_lon = lon.loc[row]
old_lat = lat.loc[row]
return kml
def create_speed_model(df_maneuvers: pd.DataFrame, init_speed: float) -> Union[list, np.ndarray]:
"""
Helper function. Extracts speed information from maneuvers.
Args:
df_maneuvers: Maneuvers array
init_speed: Initial speed
Returns:
object (Union[list, np.ndarray]): Modelled speed
"""
if not isinstance(df_maneuvers, pd.DataFrame):
raise TypeError("input must be a pd.DataFrame")
if not isinstance(init_speed, float):
raise TypeError("input must be a float")
speed = []
man_type = [] # 1 for acceleration, -1 for deceleration, 0 for standstill
num_rows, num_cols = df_maneuvers.shape
for i in range(num_rows):
if df_maneuvers.iloc[i].iloc[2] == 'FM_EGO_decelerate':
man_type.append(-1)
elif df_maneuvers.iloc[i].iloc[2] == 'FM_EGO_keep_velocity':
if i == 0:
start_speed = float(init_speed / 3.6)
else:
start_speed = float(df_maneuvers.iloc[i - 1].iloc[5])
if float(df_maneuvers.iloc[i].iloc[5]) >= start_speed:
man_type.append(1)
else:
man_type.append(-1)
elif df_maneuvers.iloc[i].iloc[2] == 'FM_EGO_accelerate':
man_type.append(1)
elif df_maneuvers.iloc[i].iloc[2] == 'FM_EGO_standstill':
man_type.append(0)
accel_res = []
maneuver_len = []
for i in range(num_rows):
accel_res.append(float(df_maneuvers.iloc[i].iloc[6]) * man_type[i])
if i > 0:
maneuver_start = int(df_maneuvers.iloc[i].iloc[0])
maneuver_end = int(df_maneuvers.iloc[i - 1].iloc[1])
if maneuver_end >= maneuver_start:
maneuver_len.append(int(df_maneuvers.iloc[i].iloc[1]) - maneuver_end)
else:
maneuver_len.append(int(df_maneuvers.iloc[i].iloc[1]) + 1 - int(df_maneuvers.iloc[i].iloc[0]))
else:
maneuver_len.append(int(df_maneuvers.iloc[i].iloc[1]) + 1 - int(df_maneuvers.iloc[i].iloc[0]))
start_time = int(df_maneuvers.iloc[0].iloc[0])
delta_t = 0.1
acc_full = []
for i in range(len(maneuver_len)):
for k in range(int(maneuver_len[i])):
acc_full.append(accel_res[i])
for i in range(start_time, start_time + len(acc_full)):
if i == start_time:
speed.append(init_speed)
else:
if start_time == 0:
sub = 1
else:
sub = start_time + 1
speed.append(speed[i - sub] + acc_full[i - sub] * delta_t * 3.6)
speed_np = np.array(speed)
return speed_np
def calc_opt_acc_thresh(df: pd.DataFrame, df_lanes: pd.DataFrame, opendrive_path: str, use_folder: bool,
dir_name: str) -> np.ndarray:
"""
Used to get optimal acceleration threshold to label maneuvers.
Args:
df: Main processed dataframe
df_lanes: Dataframe which contains absolute positions of lanes
opendrive_path: Path to opendrive file
use_folder: Option to create folder structure
dir_name: Name of the folder
Returns:
object (np.ndarray): Optimal acceleration threshold
"""
if not isinstance(df, pd.DataFrame):
raise TypeError("input must be a pd.DataFrame")
if not isinstance(df_lanes, pd.DataFrame):
raise TypeError("input must be a pd.DataFrame")
if not isinstance(opendrive_path, str):
raise TypeError("input must be a str")
if not isinstance(use_folder, bool):
raise TypeError("input must be a bool")
if not isinstance(dir_name, str):
raise TypeError("input must be a str")
movobj_grps_coord = utils.find_vars('lat_|lon_|speed_|class', df.columns, reshape=True)
# Labeling
lane_change_left_array, lane_change_right_array = rulebased.create_lateral_maneuver_vectors(df_lanes, df['lat'], df['long'])
# Array can be extended with more values for acceleration thresholds
acc_thres = np.array([0.05, 0.1, 0.15, 0.2, 0.25, 0.3])
quality_array = np.zeros((len(movobj_grps_coord) + 1, len(acc_thres)))
for x in range(len(acc_thres)):
curr_thres = acc_thres[x]
print('current acceleration threshold: ' + str(curr_thres))
speed = df['speed']
accelerate_array, \
start_array, \
keep_velocity_array, \
standstill_array, \
decelerate_array, \
stop_array, \
reversing_array = rulebased.create_longitudinal_maneuver_vectors(
speed, acceleration_definition_threshold=curr_thres)
# Create df with maneuver info
df_maneuvers = pd.DataFrame(data=None)
df_maneuvers['FM_INF_lane_change_left'] = lane_change_left_array
df_maneuvers['FM_INF_lane_change_right'] = lane_change_right_array
df_maneuvers['FM_EGO_accelerate'] = accelerate_array
df_maneuvers['FM_EGO_start'] = start_array
df_maneuvers['FM_EGO_keep_velocity'] = keep_velocity_array
df_maneuvers['FM_EGO_standstill'] = standstill_array
df_maneuvers['FM_EGO_decelerate'] = decelerate_array
df_maneuvers['FM_EGO_stop'] = stop_array
df_maneuvers['FM_EGO_reversing'] = reversing_array
df_maneuvers_objects = {}
for i in range(len(movobj_grps_coord)):
speed = df[movobj_grps_coord[i][2]]
accelerate_array, \
start_array, \
keep_velocity_array, \
standstill_array, \
decelerate_array, \
stop_array, \
reversing_array = rulebased.create_longitudinal_maneuver_vectors(
speed, acceleration_definition_threshold=acc_thres[x])
df_maneuvers_objects[i] = pd.DataFrame(data=None)
df_maneuvers_objects[i]['FM_EGO_accelerate'] = accelerate_array
df_maneuvers_objects[i]['FM_EGO_start'] = start_array
df_maneuvers_objects[i]['FM_EGO_keep_velocity'] = keep_velocity_array
df_maneuvers_objects[i]['FM_EGO_standstill'] = standstill_array
df_maneuvers_objects[i]['FM_EGO_decelerate'] = decelerate_array
df_maneuvers_objects[i]['FM_EGO_stop'] = stop_array
df_maneuvers_objects[i]['FM_EGO_reversing'] = reversing_array
left_lane_change_array, right_lane_change_array = rulebased.create_lateral_maneuver_vectors(df_lanes, df[
movobj_grps_coord[i][0]], df[movobj_grps_coord[i][1]]) # lat lon
df_maneuvers_objects[i]['FM_INF_lane_change_left'] = left_lane_change_array
df_maneuvers_objects[i]['FM_INF_lane_change_right'] = right_lane_change_array
# Init
# Get projection coordinates of respective open drive from open drive file
proj_in = pyproj.Proj('EPSG:4326')
proj_out = get_proj_from_open_drive(open_drive_path=opendrive_path)
columns = ['lat', 'long', 'speed', 'heading']
# Get start position, speed and heading of ego
ego = []
lon, lat = (pyproj.Transformer.from_crs(proj_in.crs, proj_out.crs, always_xy=True)).transform(
df[columns[1]][0],
df[columns[0]][0])
ego.append(lon)
ego.append(lat)
ego.append(df[columns[2]][0] / 3.6) # Speed
ego.append(utils.convert_heading(df[columns[3]][0])) # Heading
# Get start position, speed and heading of other objects
objects = {}
for i in range(len(movobj_grps_coord)):
lon, lat = (pyproj.Transformer.from_crs(proj_in.crs, proj_out.crs, always_xy=True)).transform(
df[movobj_grps_coord[i][1]][0],
df[movobj_grps_coord[i][0]][0])
obj = list()
obj.append(lon) # Lon
obj.append(lat) # Lat
obj.append(df[movobj_grps_coord[i][2]][0] / 3.6) # Speed
temp_heading = utils.calc_heading_from_two_geo_positions(df[movobj_grps_coord[i][0]][0], df[movobj_grps_coord[i][1]][0],
df[movobj_grps_coord[i][0]][1], df[movobj_grps_coord[i][1]][1])
obj.append(utils.convert_heading(temp_heading))
objects[i] = obj
# Get maneuvers
ego_maneuver_array = {}
for j in range(len(df_maneuvers_objects) + 1): # + 1 because of ego maneuvers
# Ego basis maneuvers for speed & acceleration control
acceleration_switch = -1
keep_switch = -1
deceleration_switch = -1
standstill_switch = -1
temp_ego_maneuver_array = np.empty(shape=[0, 7])
if j == 0: # Use ego
maneuvers = df_maneuvers
cols = columns
else: # Use objects
maneuvers = df_maneuvers_objects[j - 1]
cols = movobj_grps_coord[j - 1]
# Get start and end time of each maneuver
for i in range(len(maneuvers)):
# Start
if maneuvers['FM_EGO_accelerate'][i] == 1 and acceleration_switch == -1:
temp_lon, temp_lat = (pyproj.Transformer.from_crs(proj_in.crs, proj_out.crs, always_xy=True)).\
transform(
df[cols[1]][i],
df[cols[0]][i])
temp_ego_maneuver_array = np.append(temp_ego_maneuver_array,
[[i, i, 'FM_EGO_accelerate', temp_lon, temp_lat, 0, 0]], axis=0)
acceleration_switch = temp_ego_maneuver_array.shape[0] - 1
# End
elif maneuvers['FM_EGO_accelerate'][i] == 0 and acceleration_switch > -1:
temp_ego_maneuver_array[acceleration_switch][1] = i - 1
# Target speed
temp_ego_maneuver_array[acceleration_switch][5] = df[cols[2]][i - 1] / 3.6
# Calculate the acceleration = (target speed - start speed) / duration
temp_ego_maneuver_array[acceleration_switch][6] = abs(df[cols[2]][i - 1] / 3.6 - (
df[cols[2]][int(temp_ego_maneuver_array[acceleration_switch][0])] / 3.6)) / ((i - int(
temp_ego_maneuver_array[acceleration_switch][0])) / 10)
acceleration_switch = -1
if maneuvers['FM_EGO_keep_velocity'][i] == 1 and keep_switch == -1:
temp_lon, temp_lat = (pyproj.Transformer.from_crs(proj_in.crs, proj_out.crs, always_xy=True)).\
transform(
df[cols[1]][i],
df[cols[0]][i])
temp_ego_maneuver_array = np.append(temp_ego_maneuver_array,
[[i, i, 'FM_EGO_keep_velocity', temp_lon, temp_lat, 0, 0]],
axis=0)
keep_switch = temp_ego_maneuver_array.shape[0] - 1
elif maneuvers['FM_EGO_keep_velocity'][i] == 0 and keep_switch > -1:
temp_ego_maneuver_array[keep_switch][1] = i - 1
temp_ego_maneuver_array[keep_switch][5] = df[cols[2]][i - 1] / 3.6
temp_ego_maneuver_array[keep_switch][6] = abs(df[cols[2]][i - 1] / 3.6 - (
df[cols[2]][int(temp_ego_maneuver_array[keep_switch][0])] / 3.6)) / ((i - int(
temp_ego_maneuver_array[keep_switch][0])) / 10)
keep_switch = -1
if maneuvers['FM_EGO_decelerate'][i] == 1 and deceleration_switch == -1:
temp_lon, temp_lat = (pyproj.Transformer.from_crs(proj_in.crs, proj_out.crs, always_xy=True)).\
transform(
df[cols[1]][i],
df[cols[0]][i])
temp_ego_maneuver_array = np.append(temp_ego_maneuver_array,
[[i, i, 'FM_EGO_decelerate', temp_lon, temp_lat, 0, 0]],
axis=0)
deceleration_switch = temp_ego_maneuver_array.shape[0] - 1
elif maneuvers['FM_EGO_decelerate'][i] == 0 and deceleration_switch > -1:
temp_ego_maneuver_array[deceleration_switch][1] = i - 1
temp_ego_maneuver_array[deceleration_switch][5] = df[cols[2]][i - 1] / 3.6
temp_ego_maneuver_array[deceleration_switch][6] = abs(df[cols[2]][i - 1] / 3.6 - (
df[cols[2]][int(temp_ego_maneuver_array[deceleration_switch][0])] / 3.6)) / ((i - int(
temp_ego_maneuver_array[deceleration_switch][0])) / 10)
deceleration_switch = -1
if maneuvers['FM_EGO_standstill'][i] == 1 and standstill_switch == -1:
if len(temp_ego_maneuver_array) > 0: # Assure that last maneuver (if it exists) ends with 0 km/h
temp_ego_maneuver_array[len(temp_ego_maneuver_array) - 1][5] = 0.0
temp_lon, temp_lat = pyproj.transform(proj_in, proj_out, df[cols[1]][i], df[cols[0]][i])
temp_ego_maneuver_array = np.append(temp_ego_maneuver_array,
[[i, i, 'FM_EGO_standstill', temp_lon, temp_lat, 0, 0]],
axis=0)
standstill_switch = temp_ego_maneuver_array.shape[0] - 1
elif maneuvers['FM_EGO_standstill'][i] == 0 and standstill_switch > -1:
temp_ego_maneuver_array[standstill_switch][1] = i - 1
temp_ego_maneuver_array[standstill_switch][5] = df[cols[2]][i - 1] / 3.6
temp_ego_maneuver_array[standstill_switch][6] = abs(df[cols[2]][i - 1] / 3.6 - (
df[cols[2]][int(temp_ego_maneuver_array[standstill_switch][0])] / 3.6)) / ((i - int(
temp_ego_maneuver_array[standstill_switch][0])) / 10)
standstill_switch = -1
if j == 0:
speed = df['speed']
else:
speed_tmp = df[movobj_grps_coord[j - 1][2]]
speed = []
for y in range(len(speed_tmp)):
if not math.isnan(speed_tmp[y]):
speed.append(speed_tmp[y])
speed = np.array(speed)
# Calculate the model speed in osc format (linear accelerations)
if temp_ego_maneuver_array.size != 0:
df_ego_maneuver_array = pd.DataFrame(
data=temp_ego_maneuver_array[0:, 0:],
index=temp_ego_maneuver_array[0:, 0],
columns=temp_ego_maneuver_array[0, 0:])
model_speed = create_speed_model(df_ego_maneuver_array, speed[0])
# Use RMSE Value for calculating the difference
if len(model_speed) - len(speed) == 1:
rmse_speed = np.sqrt(np.square(np.subtract(model_speed[0:-1], speed)).mean())
elif len(speed) - len(model_speed) == 1:
rmse_speed = np.sqrt(np.square(np.subtract(model_speed, speed[0:-1])).mean())
elif len(model_speed) == len(speed):
rmse_speed = np.sqrt(np.square(np.subtract(model_speed, speed)).mean())
else:
rmse_speed = 999
else:
rmse_speed = 999
ego_maneuver_array[j] = temp_ego_maneuver_array
quality_array[j][x] = rmse_speed
# Get the minumum RMSE values for each object (EGO + Player)
num_rows, num_cols = quality_array.shape
df_opt_acc = pd.DataFrame()
acc_thres_opt = []
obj_qual = np.empty(0)
for z in range(num_rows):
obj_qual = quality_array[z][:]
acc_thres_opt.append(acc_thres[np.argmin(obj_qual)])
if z == 0:
playername = 'EGO'
else:
playername = 'Player' + str(z)
df_opt_acc[playername] = [acc_thres[np.argmin(obj_qual)]]
if use_folder:
if not os.path.isdir(os.path.abspath(dir_name)):
raise FileNotFoundError("input must be a valid path.")
if not os.path.exists(os.path.abspath(dir_name)):
raise NotADirectoryError("input must be a directory.")
maneuver_dir = os.path.abspath(dir_name + '/maneuver_lists')
if not os.path.exists(maneuver_dir):
os.mkdir(maneuver_dir)
df_opt_acc.to_csv(maneuver_dir + '/acc_thres_values.csv')
acc_thres_opt.append(acc_thres[np.argmin(obj_qual)])
return np.array(acc_thres_opt)
def label_maneuvers(df: pd.DataFrame, df_lanes: pd.DataFrame, acc_threshold: Union[float, np.ndarray], generate_kml: bool,
opendrive_path: str, use_folder: bool, dir_name: str) -> tuple:
"""
Used for labeling the maneuvers
Args:
df: Main processed Dataframe
df_lanes: Dataframe which contains absolute positions of lanes
acc_threshold: Acceleration threshold for labeling
generate_kml: Option to generate kml files
opendrive_path: Path to opendrive file
use_folder: Option to create folder structure
dir_name: Name of the folder
Returns:
object (tuple): ego_maneuver_array, inf_maneuver_array, objlist, objects, ego, movobj_grps_coord
"""
if not isinstance(df, pd.DataFrame):
raise TypeError("input must be a pd.DataFrame")
if not isinstance(df_lanes, pd.DataFrame):
raise TypeError("input must be a pd.DataFrame")
if not (isinstance(acc_threshold, float) or isinstance(acc_threshold, np.ndarray)):
raise TypeError("input must be a float or np.ndarray")
if not isinstance(generate_kml, bool):
raise TypeError("input must be a bool")
if not isinstance(opendrive_path, str):
raise TypeError("input must be a str")
if not isinstance(use_folder, bool):
raise TypeError("input must be a bool")
if not isinstance(dir_name, str):
raise TypeError("input must be a str")
# Get signals from trajectories file
speed = df['speed']
# Labeling
lane_change_left_array, lane_change_right_array = rulebased.create_lateral_maneuver_vectors(df_lanes,
df['lat'],
df['long'])
if isinstance(acc_threshold, int) or isinstance(acc_threshold, float):
accelerate_array, \
start_array, \
keep_velocity_array, \
standstill_array, \
decelerate_array, \
stop_array, \
reversing_array = rulebased.create_longitudinal_maneuver_vectors(
speed, acceleration_definition_threshold=acc_threshold)
else:
accelerate_array, \
start_array, \
keep_velocity_array, \
standstill_array, \
decelerate_array, \
stop_array, \
reversing_array = rulebased.create_longitudinal_maneuver_vectors(
speed, acceleration_definition_threshold=acc_threshold[0])
# Create df with maneuver info
df_maneuvers = pd.DataFrame(data=None)
df_maneuvers['FM_INF_lane_change_left'] = lane_change_left_array
df_maneuvers['FM_INF_lane_change_right'] = lane_change_right_array
df_maneuvers['FM_EGO_accelerate'] = accelerate_array
df_maneuvers['FM_EGO_start'] = start_array
df_maneuvers['FM_EGO_keep_velocity'] = keep_velocity_array
df_maneuvers['FM_EGO_standstill'] = standstill_array
df_maneuvers['FM_EGO_decelerate'] = decelerate_array
df_maneuvers['FM_EGO_stop'] = stop_array
df_maneuvers['FM_EGO_reversing'] = reversing_array
if use_folder:
if not os.path.exists(dir_name + '/maneuver_lists'):
os.mkdir(dir_name + '/maneuver_lists')
df_maneuvers.to_excel(dir_name + '/maneuver_lists/maneuver_ego.xlsx')
class_dict = {0: ["UnknownClass1"],
3: ["PedestrianClass1"],
5: ["BicycleClass1"],
6: ["MotorbikeClass1"],
7: ["CarClass1"],
8: ["VanClass1"],
9: ["TruckClass1"],
11: ["AnimalClass1"]}
movobj_grps_coord = utils.find_vars('lat_|lon_|speed_|class', df.columns, reshape=True)
rel_class = [int(df[movobj_grps_coord[i][3]].mode()) for i in range(len(movobj_grps_coord))]
objlist = []
np.random.seed(0)
for cl in rel_class:
objlist.append(class_dict[cl][np.random.randint(0, len(class_dict[cl]))])
df_maneuvers_objects = {}
for i in range(len(movobj_grps_coord)):
speed = df[movobj_grps_coord[i][2]]
if isinstance(acc_threshold, int) or isinstance(acc_threshold, float):
accelerate_array, \
start_array, \
keep_velocity_array, \
standstill_array, \
decelerate_array, \
stop_array, \
reversing_array = rulebased.create_longitudinal_maneuver_vectors(
speed, acceleration_definition_threshold=acc_threshold)
else:
accelerate_array, \
start_array, \
keep_velocity_array, \
standstill_array, \
decelerate_array, \
stop_array, \
reversing_array = rulebased.create_longitudinal_maneuver_vectors(
speed,
acceleration_definition_threshold=acc_threshold[i + 1])
df_maneuvers_objects[i] = pd.DataFrame(data=None)
df_maneuvers_objects[i]['FM_EGO_accelerate'] = accelerate_array
df_maneuvers_objects[i]['FM_EGO_start'] = start_array
df_maneuvers_objects[i]['FM_EGO_keep_velocity'] = keep_velocity_array
df_maneuvers_objects[i]['FM_EGO_standstill'] = standstill_array
df_maneuvers_objects[i]['FM_EGO_decelerate'] = decelerate_array
df_maneuvers_objects[i]['FM_EGO_stop'] = stop_array
df_maneuvers_objects[i]['FM_EGO_reversing'] = reversing_array
left_lane_change_array, right_lane_change_array = rulebased.create_lateral_maneuver_vectors(df_lanes,
df[movobj_grps_coord[i][0]],
df[movobj_grps_coord[i][1]])
df_maneuvers_objects[i]['FM_INF_lane_change_left'] = left_lane_change_array
df_maneuvers_objects[i]['FM_INF_lane_change_right'] = right_lane_change_array
if use_folder:
df_maneuvers_objects[i].to_excel(dir_name + '/maneuver_lists/maneuver_object' + str(i) + '.xlsx')
if generate_kml:
kml = convert_maneuvers_to_kml(df['lat'], df['long'], df_maneuvers, True)
if use_folder:
if not os.path.exists(dir_name + '/kml_files'):
os.mkdir(dir_name + '/kml_files')
kml.save(dir_name + '/kml_files/ego.kml')
else:
kml.save(r'../files/ego.kml')
for i in range(len(movobj_grps_coord)):
lat = df[movobj_grps_coord[i][0]]
lon = df[movobj_grps_coord[i][1]]
kml = convert_maneuvers_to_kml(lat, lon, df_maneuvers_objects[i], False)
if use_folder:
kml.save(dir_name + '/kml_files/vehicle' + str(i) + '.kml')
else:
kml.save(r'../files/vehicle' + str(i) + '.kml')
# Prepare simulation parameters
# Get projection coordinates of respective open drive from open drive file
proj_in = pyproj.Proj('EPSG:4326')
proj_out = get_proj_from_open_drive(open_drive_path=opendrive_path)
columns = ['lat', 'long', 'speed', 'heading']
# Get start position, speed and heading of ego
ego = []
lon, lat = (pyproj.Transformer.from_crs(proj_in.crs, proj_out.crs, always_xy=True)).transform(df[columns[1]][0],
df[columns[0]][0])
ego.append(lon)
ego.append(lat)
ego.append(df[columns[2]][0] / 3.6) # speed
ego.append(utils.convert_heading(df[columns[3]][0])) # heading
# Get start position, speed and heading of other objects
objects = {}
for i in range(len(movobj_grps_coord)):
lon, lat = (pyproj.Transformer.from_crs(proj_in.crs, proj_out.crs, always_xy=True)).transform(
df[movobj_grps_coord[i][1]][0],
df[movobj_grps_coord[i][0]][0])
obj = list()
obj.append(lon) # Lon
obj.append(lat) # Lat
obj.append(df[movobj_grps_coord[i][2]][0] / 3.6) # speed
temp_heading = utils.calc_heading_from_two_geo_positions(df[movobj_grps_coord[i][0]][0], df[movobj_grps_coord[i][1]][0],
df[movobj_grps_coord[i][0]][2], df[movobj_grps_coord[i][1]][2])
obj.append(utils.convert_heading(temp_heading))
objects[i] = obj
# Get maneuvers
ego_maneuver_array = {}
for j in range(len(df_maneuvers_objects) + 1): # + 1 because of ego maneuvers
# Ego basis maneuvers for speed & acceleration control
acceleration_switch = -1
keep_switch = -1
deceleration_switch = -1
standstill_switch = -1
temp_ego_maneuver_array = np.empty(shape=[0, 7])
if j == 0: # Use ego
maneuvers = df_maneuvers
cols = columns
else: # Use objects
maneuvers = df_maneuvers_objects[j - 1]
cols = movobj_grps_coord[j - 1]
# Get start and end time of each maneuver
for i in range(len(maneuvers)):
# Start
if maneuvers['FM_EGO_accelerate'][i] == 1 and acceleration_switch == -1:
temp_lon, temp_lat = (pyproj.Transformer.from_crs(proj_in.crs, proj_out.crs, always_xy=True)).transform(
df[cols[1]][i],
df[cols[0]][i])
temp_ego_maneuver_array = np.append(temp_ego_maneuver_array,
[[i, i, 'FM_EGO_accelerate', temp_lon, temp_lat, 0, 0]], axis=0)
acceleration_switch = temp_ego_maneuver_array.shape[0] - 1
# End
elif maneuvers['FM_EGO_accelerate'][i] == 0 and acceleration_switch > -1:
temp_ego_maneuver_array[acceleration_switch][1] = i - 1
# Target speed
temp_ego_maneuver_array[acceleration_switch][5] = df[cols[2]][i - 1] / 3.6
# Calculate the acceleration = (target speed - start speed) / duration
temp_ego_maneuver_array[acceleration_switch][6] = abs(df[cols[2]][i - 1] / 3.6 - (
df[cols[2]][int(temp_ego_maneuver_array[acceleration_switch][0])] / 3.6)) / ((i - int(
temp_ego_maneuver_array[acceleration_switch][0])) / 10)
acceleration_switch = -1
if maneuvers['FM_EGO_keep_velocity'][i] == 1 and keep_switch == -1:
temp_lon, temp_lat = (pyproj.Transformer.from_crs(proj_in.crs, proj_out.crs, always_xy=True)).transform(
df[cols[1]][i],
df[cols[0]][i])
temp_ego_maneuver_array = np.append(temp_ego_maneuver_array,
[[i, i, 'FM_EGO_keep_velocity', temp_lon, temp_lat, 0, 0]], axis=0)
keep_switch = temp_ego_maneuver_array.shape[0] - 1
elif maneuvers['FM_EGO_keep_velocity'][i] == 0 and keep_switch > -1:
temp_ego_maneuver_array[keep_switch][1] = i - 1
temp_ego_maneuver_array[keep_switch][5] = df[cols[2]][i - 1] / 3.6
temp_ego_maneuver_array[keep_switch][6] = abs(
df[cols[2]][i - 1] / 3.6 - (df[cols[2]][int(temp_ego_maneuver_array[keep_switch][0])] / 3.6)) / \
((i - int(temp_ego_maneuver_array[keep_switch][0])) / 10)
keep_switch = -1
if maneuvers['FM_EGO_decelerate'][i] == 1 and deceleration_switch == -1:
temp_lon, temp_lat = (pyproj.Transformer.from_crs(proj_in.crs, proj_out.crs, always_xy=True)).transform(
df[cols[1]][i],
df[cols[0]][i])
temp_ego_maneuver_array = np.append(temp_ego_maneuver_array,
[[i, i, 'FM_EGO_decelerate', temp_lon, temp_lat, 0, 0]], axis=0)
deceleration_switch = temp_ego_maneuver_array.shape[0] - 1
elif maneuvers['FM_EGO_decelerate'][i] == 0 and deceleration_switch > -1:
temp_ego_maneuver_array[deceleration_switch][1] = i - 1
temp_ego_maneuver_array[deceleration_switch][5] = df[cols[2]][i - 1] / 3.6
temp_ego_maneuver_array[deceleration_switch][6] = abs(df[cols[2]][i - 1] / 3.6 - (
df[cols[2]][int(temp_ego_maneuver_array[deceleration_switch][0])] / 3.6)) / ((i - int(
temp_ego_maneuver_array[deceleration_switch][0])) / 10)
deceleration_switch = -1
if maneuvers['FM_EGO_standstill'][i] == 1 and standstill_switch == -1:
if len(temp_ego_maneuver_array) > 0: # Assure that last maneuver (if it exists) ends with 0 km/h
temp_ego_maneuver_array[len(temp_ego_maneuver_array) - 1][5] = 0.0
temp_lon, temp_lat = pyproj.transform(proj_in, proj_out, df[cols[1]][i], df[cols[0]][i])
temp_ego_maneuver_array = np.append(temp_ego_maneuver_array,
[[i, i, 'FM_EGO_standstill', temp_lon, temp_lat, 0, 0]], axis=0)
standstill_switch = temp_ego_maneuver_array.shape[0] - 1
elif maneuvers['FM_EGO_standstill'][i] == 0 and standstill_switch > -1:
temp_ego_maneuver_array[standstill_switch][1] = i - 1
temp_ego_maneuver_array[standstill_switch][5] = df[cols[2]][i - 1] / 3.6
temp_ego_maneuver_array[standstill_switch][6] = abs(df[cols[2]][i - 1] / 3.6 - (
df[cols[2]][int(temp_ego_maneuver_array[standstill_switch][0])] / 3.6)) / ((i - int(
temp_ego_maneuver_array[standstill_switch][0])) / 10)
standstill_switch = -1
ego_maneuver_array[j] = temp_ego_maneuver_array
if use_folder:
pd.DataFrame(temp_ego_maneuver_array).to_csv(
dir_name + '/maneuver_lists/maneuver_array_lon_' + str(j) + '.csv')
# Infrastructure maneuvers for lane change control
inf_maneuver_array = {}
for j in range(len(df_maneuvers_objects) + 1): # + 1 because of ego maneuvers
lane_change_left_switch = -1
lane_change_right_switch = -1
temp_inf_maneuver_array = np.empty(shape=[0, 6])
if j == 0: # Use ego
maneuvers = df_maneuvers
cols = columns
else: # Use objects
maneuvers = df_maneuvers_objects[j - 1]
cols = movobj_grps_coord[j - 1]
# Get start and end time of each maneuver
for i in range(len(maneuvers)):
# Get start and end time of maneuver
if maneuvers['FM_INF_lane_change_left'][i] == 1 and lane_change_left_switch == -1:
temp_lon, temp_lat = pyproj.transform(proj_in, proj_out, df[cols[1]][i], df[cols[0]][i])
temp_inf_maneuver_array = np.append(temp_inf_maneuver_array,
[[i, i, 'FM_INF_lane_change_left', temp_lon, temp_lat, 0]], axis=0)
lane_change_left_switch = temp_inf_maneuver_array.shape[0] - 1
elif maneuvers['FM_INF_lane_change_left'][i] == 0 and lane_change_left_switch > -1:
temp_inf_maneuver_array[lane_change_left_switch][1] = i
temp_inf_maneuver_array[lane_change_left_switch][5] = (i - int(
temp_inf_maneuver_array[lane_change_left_switch][0])) / 10
lane_change_left_switch = -1
elif i == len(maneuvers) - 1 and lane_change_left_switch > -1:
temp_inf_maneuver_array[lane_change_left_switch][1] = i
temp_inf_maneuver_array[lane_change_left_switch][5] = (i - int(
temp_inf_maneuver_array[lane_change_left_switch][0])) / 10
lane_change_left_switch = -1
if maneuvers['FM_INF_lane_change_right'][i] == 1 and lane_change_right_switch == -1:
temp_lon, temp_lat = pyproj.transform(proj_in, proj_out, df[cols[1]][i], df[cols[0]][i])
temp_inf_maneuver_array = np.append(temp_inf_maneuver_array,
[[i, i, 'FM_INF_lane_change_right', temp_lon, temp_lat, 0]], axis=0)
lane_change_right_switch = temp_inf_maneuver_array.shape[0] - 1
elif maneuvers['FM_INF_lane_change_right'][i] == 0 and lane_change_right_switch > -1:
temp_inf_maneuver_array[lane_change_right_switch][1] = i
temp_inf_maneuver_array[lane_change_right_switch][5] = (i - int(
temp_inf_maneuver_array[lane_change_right_switch][0])) / 10
lane_change_right_switch = -1
elif i == len(maneuvers) - 1 and lane_change_right_switch > -1:
temp_inf_maneuver_array[lane_change_right_switch][1] = i
temp_inf_maneuver_array[lane_change_right_switch][5] = (i - int(
temp_inf_maneuver_array[lane_change_right_switch][0])) / 10
lane_change_right_switch = -1
inf_maneuver_array[j] = temp_inf_maneuver_array
if use_folder and temp_inf_maneuver_array.size:
pd.DataFrame(temp_inf_maneuver_array).to_csv(
dir_name + '/maneuver_lists/maneuver_array_lat_' + str(j) + '.csv')
return ego_maneuver_array, inf_maneuver_array, objlist, objects, ego, movobj_grps_coord
<file_sep># ****************************************************************************
# @osc_generator.py
#
# @copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
import os
from .tools.converter import Converter
from .tools.user_config import UserConfig
import sys
from argparse import ArgumentParser
from .version import __version__
class OSCGenerator:
"""
This class provides an easy-to-use API for generating scenarios.
The API is designed with forward-compatibility in mind,
which is the reason why many experimental features of the underlying code are not accessible here.
"""
def __init__(self):
self.converter: Converter = Converter()
def generate_osc(self, trajectories_path: str, opendrive_path: str, output_scenario_path: str = None,
**kwargs: str):
"""
This method generates a OpenSCENARIO file based on trajectories and an OpenDRIVE file.
Args:
trajectories_path: Path to the file containing the object trajectories used as input
opendrive_path: Path to the OpenDRIVE file which describes the road net which the objects are using
output_scenario_path: Output file path and name. If not specified, a directory and name will be chosen.
If the file already exists, it will be overwritten.
keyword arguments:
catalog_path: Path to the catalog file containing vehicle catalog information for the output scenario
osc_version: Desired version of the output OpenScenario file. Default is OSC V1.0
"""
if "catalog_path" in kwargs:
if kwargs["catalog_path"] is not None:
dir_name = os.path.dirname(trajectories_path)
user_config = UserConfig(dir_name)
user_config.catalogs = kwargs["catalog_path"]
user_config.write_config()
if "osc_version" in kwargs:
if kwargs["osc_version"] is not None:
self.converter.osc_version = kwargs["osc_version"]
if output_scenario_path:
self.converter.set_paths(trajectories_path, opendrive_path, output_scenario_path)
else:
self.converter.set_paths(trajectories_path, opendrive_path)
self.converter.process_trajectories(relative=True)
self.converter.label_maneuvers(acc_threshold=0.2, optimize_acc=False, generate_kml=False)
self.converter.write_scenario(plot=False,
radius_pos_trigger=2.0,
timebased_lon=True,
timebased_lat=False,
output='xosc')
print('Path to OpenSCENARIO file: ' + os.path.abspath(self.converter.outfile))
def main():
parser = ArgumentParser()
parser.add_argument('-v', '--version', action='version', version=('%(prog)s ' + str(__version__)),
help="Show program's version number and exit.")
parser.add_argument("-t", "--trajectories", dest="trajectories_path",
help="path to the file containing the object trajectories used as input")
parser.add_argument("-d", "--opendrive", dest="opendrive_path",
help="path to the opendrive file which describes the road net which the objects are using")
parser.add_argument("-s", "--openscenario", dest="output_scenario_path", default=None,
help="output file path and name. If not specified, a directory and name will be chosen. "
"If the file already exists , it will be overwritten.")
parser.add_argument("-cat", "--catalog", dest="catalog_path", default=None,
help="catalog file path and name. If not specified, a default catalog path is used. ")
parser.add_argument("-oscv", "--oscversion", dest="osc_version", default=None,
help="Desired version of the output OpenScenario file. If not specified, default is OSC V1.0 ")
try:
args = parser.parse_args()
except SystemExit as err:
if err.code == 2:
parser.print_help()
sys.exit(0)
if (args.trajectories_path is None) or (args.opendrive_path is None):
parser.print_help()
return
oscg = OSCGenerator()
oscg.generate_osc(args.trajectories_path, args.opendrive_path, args.output_scenario_path,
catalog_path=args.catalog_path,
osc_version=args.osc_version)
if __name__ == '__main__':
main()
<file_sep># ****************************************************************************
# @test_rulebased.py
#
# @copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
from osc_generator.tools import rulebased
import pytest
import pandas as pd
import numpy as np
import os
@pytest.fixture
def test_data_dir():
return os.path.join(os.path.dirname(__file__), '../test_data')
@pytest.fixture
def prepared_df(test_data_dir):
return pd.read_csv(os.path.join(test_data_dir, 'prepared_df.csv'))
@pytest.fixture
def e_accelerate_array(test_data_dir):
return np.load(os.path.join(test_data_dir, 'accelerate_array.npy'))
@pytest.fixture
def e_decelerate_array(test_data_dir):
return np.load(os.path.join(test_data_dir, 'decelerate_array.npy'))
@pytest.fixture
def e_keep_velocity_array(test_data_dir):
return np.load(os.path.join(test_data_dir, 'keep_velocity_array.npy'))
@pytest.fixture
def e_lane_change_right_array(test_data_dir):
return np.load(os.path.join(test_data_dir, 'lane_change_right_array.npy'))
@pytest.fixture
def e_lane_change_left_array(test_data_dir):
return np.load(os.path.join(test_data_dir, 'lane_change_left_array.npy'))
@pytest.fixture
def prepared_df(test_data_dir):
return pd.read_csv(os.path.join(test_data_dir, 'prepared_df.csv'))
@pytest.fixture
def df_lanes(test_data_dir):
return pd.read_csv(os.path.join(test_data_dir, 'df_lanes.csv'))
class TestRulebased:
def test_get_vehicle_state_maneuver(self, prepared_df, e_accelerate_array, e_decelerate_array,
e_keep_velocity_array):
speed = prepared_df['speed']
accelerate_array, start_array, keep_velocity_array, standstill_array, decelerate_array, stop_array, \
reversing_array = rulebased.create_longitudinal_maneuver_vectors(speed, acceleration_definition_threshold=0.2)
np.testing.assert_array_equal(accelerate_array, e_accelerate_array)
np.testing.assert_array_equal(decelerate_array, e_decelerate_array)
np.testing.assert_array_equal(keep_velocity_array, e_keep_velocity_array)
def test_get_lanechange_absolute(self, prepared_df, df_lanes, e_lane_change_right_array, e_lane_change_left_array):
lane_change_left_array, lane_change_right_array = rulebased.create_lateral_maneuver_vectors(df_lanes,
prepared_df['lat'],
prepared_df['long'])
np.testing.assert_array_equal(lane_change_right_array, e_lane_change_right_array)
np.testing.assert_array_equal(lane_change_left_array, e_lane_change_left_array)
<file_sep># ****************************************************************************
# @test_converter.py
#
# @copyright 2023 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
from osc_generator.tools.converter import Converter
from xmldiff import main
import pytest
import pandas as pd
import os
import warnings
@pytest.fixture
def test_data_dir():
return os.path.join(os.path.dirname(__file__), '../test_data')
@pytest.fixture
def df_lanes(test_data_dir):
return pd.read_csv(os.path.join(test_data_dir, 'df_lanes_llc.csv'))
class TestConverter:
def test_converter_csv_relative_ego_llc(self, test_data_dir): # left lane change scenario, from csv file
trajectories_path = os.path.join(test_data_dir, r'testfile_llc.csv')
opendrive_path = os.path.join(test_data_dir, r'TestTrack.xodr')
output_scenario_path = os.path.join(test_data_dir, r'output_scenario.xosc')
expected_scenario_path = os.path.join(test_data_dir, r'expected_llc.xosc')
system_under_test = Converter()
system_under_test.osc_version = '1.2'
system_under_test.set_paths(trajectories_path, opendrive_path, output_scenario_path)
system_under_test.process_trajectories(relative=True)
system_under_test.label_maneuvers(acc_threshold=0.2, optimize_acc=False, generate_kml=False)
system_under_test.write_scenario(plot=False,
radius_pos_trigger=2.0,
timebased_lon=True,
timebased_lat=True,
output='xosc')
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
def test_converter_osi_relative_ego_llc(self, test_data_dir): # left lane change scenario, from osi file
trajectories_path = os.path.join(test_data_dir, r'testfile_llc.osi')
opendrive_path = os.path.join(test_data_dir, r'TestTrack.xodr')
output_scenario_path = os.path.join(test_data_dir, r'output_scenario.xosc')
expected_scenario_path = os.path.join(test_data_dir, r'expected_llc.xosc')
try:
system_under_test = Converter()
system_under_test.osc_version = '1.2'
system_under_test.set_paths(trajectories_path, opendrive_path, output_scenario_path)
system_under_test.process_trajectories(relative=True)
system_under_test.label_maneuvers(acc_threshold=0.2, optimize_acc=False, generate_kml=False)
system_under_test.write_scenario(plot=False,
radius_pos_trigger=2.0,
timebased_lon=True,
timebased_lat=True,
output='xosc')
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
except NameError:
warnings.warn(
"Feature OSI Input Data is not available. Download from: "
"https://github.com/OpenSimulationInterface/open-simulation-interface/blob/master/format/OSITrace.py",
UserWarning)
def test_converter_csv_absolute_ego_llc(self, test_data_dir, df_lanes): # left lane change, absolute co-ords
trajectories_path = os.path.join(test_data_dir, r'testfile_llc.csv')
opendrive_path = os.path.join(test_data_dir, r'TestTrack.xodr')
output_scenario_path = os.path.join(test_data_dir, r'output_scenario.xosc')
expected_scenario_path = os.path.join(test_data_dir, r'expected_llc.xosc')
system_under_test = Converter()
system_under_test.osc_version = '1.2'
system_under_test.set_paths(trajectories_path, opendrive_path, output_scenario_path)
system_under_test.process_trajectories(relative=False, df_lanes=df_lanes)
system_under_test.label_maneuvers(acc_threshold=0.2, optimize_acc=False, generate_kml=False)
system_under_test.write_scenario(plot=False,
radius_pos_trigger=2.0,
timebased_lon=True,
timebased_lat=True,
output='xosc')
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
def test_converter_csv_relative_ego_rlc(self, test_data_dir): # right lane change scenario, from csv file
trajectories_path = os.path.join(test_data_dir, r'testfile_rlc.csv')
opendrive_path = os.path.join(test_data_dir, r'TestTrack.xodr')
output_scenario_path = os.path.join(test_data_dir, r'output_scenario.xosc')
expected_scenario_path = os.path.join(test_data_dir, r'expected_rlc.xosc')
system_under_test = Converter()
system_under_test.osc_version = '1.2'
system_under_test.set_paths(trajectories_path, opendrive_path, output_scenario_path)
system_under_test.process_trajectories(relative=True)
system_under_test.label_maneuvers(acc_threshold=0.2, optimize_acc=False, generate_kml=False)
system_under_test.write_scenario(plot=False,
radius_pos_trigger=2.0,
timebased_lon=True,
timebased_lat=True,
output='xosc')
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
def test_converter_osi_relative_ego_rlc(self, test_data_dir): # right lane change scenario, from osi file
trajectories_path = os.path.join(test_data_dir, r'testfile_rlc.osi')
opendrive_path = os.path.join(test_data_dir, r'TestTrack.xodr')
output_scenario_path = os.path.join(test_data_dir, r'output_scenario.xosc')
expected_scenario_path = os.path.join(test_data_dir, r'expected_rlc.xosc')
try:
system_under_test = Converter()
system_under_test.osc_version = '1.2'
system_under_test.set_paths(trajectories_path, opendrive_path, output_scenario_path)
system_under_test.process_trajectories(relative=True)
system_under_test.label_maneuvers(acc_threshold=0.2, optimize_acc=False, generate_kml=False)
system_under_test.write_scenario(plot=False,
radius_pos_trigger=2.0,
timebased_lon=True,
timebased_lat=True,
output='xosc')
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
except NameError:
warnings.warn(
"Feature OSI Input Data is not available. Download from: "
"https://github.com/OpenSimulationInterface/open-simulation-interface/blob/master/format/OSITrace.py",
UserWarning)
<file_sep># ****************************************************************************
# @test_utils.py
#
# @copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
import pandas as pd
import numpy as np
from osc_generator.tools import utils
import pytest
import os
@pytest.fixture
def test_data_dir():
return os.path.join(os.path.dirname(__file__), '../test_data')
@pytest.fixture
def df(test_data_dir):
return pd.read_csv(os.path.join(test_data_dir, 'trajectories_file.csv'))
@pytest.fixture
def cleaned_df(test_data_dir):
return pd.read_csv(os.path.join(test_data_dir, 'cleaned_df.csv'))
@pytest.fixture
def cols():
cols = [['pos_x_1', 'pos_y_1', 'speed_x_1', 'speed_y_1', 'class_1'],
['pos_x_2', 'pos_y_2', 'speed_x_2', 'speed_y_2', 'class_2'],
['pos_x_3', 'pos_y_3', 'speed_x_3', 'speed_y_3', 'class_3'],
['pos_x_4', 'pos_y_4', 'speed_x_4', 'speed_y_4', 'class_4'],
['pos_x_5', 'pos_y_5', 'speed_x_5', 'speed_y_5', 'class_5'],
['pos_x_6', 'pos_y_6', 'speed_x_6', 'speed_y_6', 'class_6'],
['pos_x_7', 'pos_y_7', 'speed_x_7', 'speed_y_7', 'class_7']]
return cols
class TestUtils:
def test_delete_not_relevant_objects(self, df, cleaned_df, cols):
actual, _ = utils.delete_irrelevant_objects(df, cols)
expected = cleaned_df
pd.testing.assert_frame_equal(actual, expected)
def test_new_coordinate_heading(self, df, cleaned_df):
p = ['pos_x_6', 'pos_y_6', 'speed_x_6']
k = 64
actual = utils.calc_new_geopos_from_2d_vector_on_spheric_earth(curr_coords=df.loc[k, ["lat", "long"]],
heading=df.loc[k, "heading"],
dist_x=df.loc[k, p[0]], dist_y=df.loc[k, p[1]])
expected = [1, 2]
assert actual is not None
assert len(actual) == len(expected)
def test_flatten(self):
cols_1 = [['pos_x_1', 'pos_y_1', 'speed_x_1', 'speed_y_1', 'class_1'],
['pos_x_2', 'pos_y_2', 'speed_x_2', 'speed_y_2', 'class_2']]
expected_1 = ['pos_x_1', 'pos_y_1', 'speed_x_1', 'speed_y_1', 'class_1',
'pos_x_2', 'pos_y_2', 'speed_x_2', 'speed_y_2', 'class_2']
cols_2 = ['pos_x_1', 'pos_y_1', 'speed_x_1', 'speed_y_1', 'class_1',
'pos_x_2', 'pos_y_2', 'speed_x_2', 'speed_y_2', 'class_2']
expected_2 = ['pos_x_1', 'pos_y_1', 'speed_x_1', 'speed_y_1', 'class_1',
'pos_x_2', 'pos_y_2', 'speed_x_2', 'speed_y_2', 'class_2']
cols_3 = [[], []]
expected_3 = []
assert utils.flatten(cols_1) == expected_1
assert utils.flatten(cols_2) == expected_2
assert utils.flatten(cols_3) == expected_3
def test_find_vars(self, df, cols):
actual = utils.find_vars('pos_x_|pos_y_|speed_x_|speed_y_|class_', df.columns, reshape=True)
expected = np.asarray(cols)
assert actual is not None
assert isinstance(actual, np.ndarray)
assert actual[2, 3] == expected[2, 3]
def test_convert_heading(self):
assert round(utils.convert_heading(0.0), 2) != 0
assert round(utils.convert_heading(0), 2) != 0
assert round(utils.convert_heading(360), 2) == 1.57
assert round(utils.convert_heading(-270), 2) == 12.57
assert round(utils.convert_heading(-735), 2) == 20.68
def test_get_heading(self, df, cols):
actual = utils.calc_heading_from_two_geo_positions(48.80437693633773, 48.80440442405007, 11.465818732551098, 11.465823006918304)
assert round(actual, 2) == -127.32
assert utils.calc_heading_from_two_geo_positions(0, 0, 0, 0) == 180
<file_sep>import os
import warnings
import json
class UserConfig:
"""
class for user defined configurations
"""
def __init__(self, path):
self.path_to_config: str = path
self.catalogs = None
self.object_boundingbox = None
self.bbcenter_to_rear = None
def read_config(self):
"""
read config file and store relevant information
"""
try:
with open(os.path.join(self.path_to_config, 'user_config.json'), 'r') as config_file:
data = json.load(config_file)
if "moving_objects" in data:
objects = data["moving_objects"]
object_bb = []
object_bbcenter = []
for bb in objects:
if "boundingbox" in bb:
object_bb.append(bb["boundingbox"])
else:
object_bb.append(None)
if "bbcenter_to_rear" in bb:
object_bbcenter.append(bb["bbcenter_to_rear"])
else:
object_bbcenter.append(None)
self.object_boundingbox = object_bb
self.bbcenter_to_rear = object_bbcenter
if "catalogs" in data:
self.catalogs = data["catalogs"]
except FileNotFoundError:
warnings.warn("User configuration file unavailable. ", UserWarning)
def write_config(self):
"""
write config file from relevant information
"""
config_data = {}
if self.object_boundingbox is not None and self.bbcenter_to_rear is not None:
config_data["moving_objects"] = [{'boundingbox': self.object_boundingbox[i],
'bbcenter_to_rear': self.bbcenter_to_rear[i]}
for i in range(len(self.object_boundingbox))]
if self.catalogs is not None:
config_data["catalogs"] = self.catalogs
if config_data:
try:
with open(os.path.join(self.path_to_config, 'user_config.json'), 'w') as config_file:
json.dump(config_data, config_file, indent=4)
except:
warnings.warn("Unable to write config file", UserWarning)
<file_sep># ****************************************************************************
# @test_osc_generator.py
#
# @copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
from osc_generator.osc_generator import OSCGenerator
from xmldiff import main
import pandas as pd
import pytest
import os
import warnings
@pytest.fixture
def test_data_dir():
return os.path.join(os.path.dirname(__file__), '../test_data')
class TestOSCGenerator:
def test_generate_osc(self, test_data_dir):
trajectories_path = os.path.join(test_data_dir, r'trajectories_file.csv')
opendrive_path = os.path.join(test_data_dir, r'2017-04-04_Testfeld_A9_Nord_offset.xodr')
output_scenario_path = os.path.join(test_data_dir, r'output_scenario.xosc')
expected_scenario_path = os.path.join(test_data_dir, r'expected_scenario.xosc')
system_under_test = OSCGenerator()
system_under_test.generate_osc(trajectories_path, opendrive_path, output_scenario_path, osc_version="1.2")
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
def test_generate_osc_class_reuse(self, test_data_dir):
trajectories_path = os.path.join(test_data_dir, r'trajectories_file.csv')
opendrive_path = os.path.join(test_data_dir, r'2017-04-04_Testfeld_A9_Nord_offset.xodr')
output_scenario_path = os.path.join(test_data_dir, r'output_scenario.xosc')
expected_scenario_path = os.path.join(test_data_dir, r'expected_scenario.xosc')
system_under_test = OSCGenerator()
system_under_test.generate_osc(trajectories_path, opendrive_path, output_scenario_path, osc_version="1.2")
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
system_under_test.generate_osc(trajectories_path, opendrive_path, output_scenario_path, osc_version="1.2")
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
def test_generate_osc_class_osi(self, test_data_dir):
try:
trajectories_path = os.path.join(test_data_dir, r'trajectories_file.osi')
opendrive_path = os.path.join(test_data_dir, r'2017-04-04_Testfeld_A9_Nord_offset.xodr')
output_scenario_path = os.path.join(test_data_dir, r'output_scenario.xosc')
expected_scenario_path = os.path.join(test_data_dir, r'expected_scenario_osi.xosc')
system_under_test = OSCGenerator()
system_under_test.generate_osc(trajectories_path, opendrive_path, output_scenario_path, osc_version="1.2")
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
system_under_test.generate_osc(trajectories_path, opendrive_path, output_scenario_path, osc_version="1.2")
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
except NameError:
warnings.warn(
"Feature OSI Input Data is not available. Download from: https://github.com/OpenSimulationInterface/open-simulation-interface/blob/master/format/OSITrace.py",
UserWarning)
def test_generate_osc_class_osi_reuse(self, test_data_dir):
try:
trajectories_path = os.path.join(test_data_dir, r'trajectories_file.osi')
opendrive_path = os.path.join(test_data_dir, r'2017-04-04_Testfeld_A9_Nord_offset.xodr')
output_scenario_path = os.path.join(test_data_dir, r'output_scenario.xosc')
expected_scenario_path = os.path.join(test_data_dir, r'expected_scenario_osi.xosc')
system_under_test = OSCGenerator()
system_under_test.generate_osc(trajectories_path, opendrive_path, output_scenario_path, osc_version="1.2")
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
system_under_test.generate_osc(trajectories_path, opendrive_path, output_scenario_path, osc_version="1.2")
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
except NameError:
warnings.warn("Feature OSI Input Data is not available. Download from: https://github.com/OpenSimulationInterface/open-simulation-interface/blob/master/format/OSITrace.py", UserWarning)
def test_generate_osc_class_csv_reuse(self, test_data_dir):
trajectories_path = os.path.join(test_data_dir, r'trajectories_file.csv')
opendrive_path = os.path.join(test_data_dir, r'2017-04-04_Testfeld_A9_Nord_offset.xodr')
output_scenario_path = os.path.join(test_data_dir, r'output_scenario.xosc')
expected_scenario_path = os.path.join(test_data_dir, r'expected_scenario.xosc')
system_under_test = OSCGenerator()
system_under_test.generate_osc(trajectories_path, opendrive_path, output_scenario_path, osc_version="1.2")
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
system_under_test.generate_osc(trajectories_path, opendrive_path, output_scenario_path, osc_version="1.2")
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
def test_generate_osc_straight_csv(self, test_data_dir):
trajectories_path = os.path.join(test_data_dir, r'testfile_straight.csv')
opendrive_path = os.path.join(test_data_dir, r'TestTrack.xodr')
output_scenario_path = os.path.join(test_data_dir, r'output_scenario.xosc')
expected_scenario_path = os.path.join(test_data_dir, r'expected_straight.xosc')
system_under_test = OSCGenerator()
system_under_test.generate_osc(trajectories_path, opendrive_path, output_scenario_path, osc_version="1.2")
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
def test_generate_osc_straight_osi(self, test_data_dir):
trajectories_path = os.path.join(test_data_dir, r'testfile_straight.osi')
opendrive_path = os.path.join(test_data_dir, r'TestTrack.xodr')
output_scenario_path = os.path.join(test_data_dir, r'output_scenario.xosc')
expected_scenario_path = os.path.join(test_data_dir, r'expected_straight.xosc')
try:
system_under_test = OSCGenerator()
system_under_test.generate_osc(trajectories_path, opendrive_path, output_scenario_path, osc_version="1.2")
diff = main.diff_files(output_scenario_path, expected_scenario_path)
assert [] == diff
except NameError:
warnings.warn("Feature OSI Input Data is not available. Download from: https://github.com/OpenSimulationInterface/open-simulation-interface/blob/master/format/OSITrace.py", UserWarning)
<file_sep># ****************************************************************************
# @scenario_writer.py
#
# @copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
import pandas as pd
import os
import numpy as np
from xml.etree.ElementTree import Element, SubElement
from xml.etree import ElementTree
from xml.dom import minidom
from scenariogeneration import xosc
from osc_generator.tools.user_config import UserConfig
import datetime
def write_pretty(elem: Element, output: str, use_folder: bool, timebased_lon: bool, timebased_lat: bool,
dir_name: str, section_name: str, radius_pos_trigger: float, output_path: str = None):
"""
Write a pretty-printed XML string for the Element.
Args:
elem: Root of the Element tree
output: Output file type xosc
use_folder: Option to use folder structure
timebased_lon: Option to use time based trigger for longitudinal maneuvers
timebased_lat: Option to use time based trigger for lateral maneuvers
dir_name: Name of the directory
section_name: Name of the scenario section
radius_pos_trigger: Radius of the position based trigger
output_path: Path to scenario file
Returns:
object (str): Path to scenario file
"""
if not isinstance(elem, Element):
raise TypeError("input must be a Element")
if not isinstance(output, str):
raise TypeError("input must be a str")
if not isinstance(use_folder, bool):
raise TypeError("input must be a bool")
if not isinstance(timebased_lon, bool):
raise TypeError("input must be a bool")
if not isinstance(timebased_lat, bool):
raise TypeError("input must be a bool")
if not isinstance(dir_name, str):
raise TypeError("input must be a str")
if not isinstance(section_name, str):
raise TypeError("input must be a str")
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
xmlstr = reparsed.toprettyxml(indent="\t")
if output == 'xosc':
if output_path is not None:
path = output_path
else:
if use_folder:
if timebased_lon and timebased_lat:
path = os.path.join(dir_name, 'man_export_' + os.path.basename(section_name) + '_time_lon_lat.xosc')
elif timebased_lon and not timebased_lat:
path = os.path.join(dir_name, 'man_export_' + os.path.basename(section_name) + '_time_lon_pos_lat_' + str(
radius_pos_trigger) + '_m.xosc')
elif not timebased_lon and timebased_lat:
path = os.path.join(dir_name, 'man_export_' + os.path.basename(section_name) + '_pos_lon_time_lat.xosc')
else:
path = os.path.join(dir_name, 'man_export_' + os.path.basename(section_name) + '_pos_lon_lat_' +
str(radius_pos_trigger) + '_m.xosc')
else:
raise NotImplementedError("use_folder flag is going to be removed")
else:
raise NotImplementedError("Only xosc output is currently implemented.")
with open(path, 'w') as f:
f.write(xmlstr)
return path
def convert_to_osc(df: pd.DataFrame, ego: list, objects: dict, ego_maneuver_array: dict, inf_maneuver_array: dict,
movobj_grps_coord: np.ndarray, objlist: list,
plot: bool, opendrive_path: str, use_folder: bool, timebased_lon: bool, timebased_lat: bool,
section_name: str, radius_pos_trigger: float,
dir_name: str, osc_version: str, output_path: str = None) -> str:
"""
Converter for OpenScenario
Args:
df: Dataframe containing trajectories
ego: Ego position
objects: Object positions
ego_maneuver_array: Dict containing array of ego maneuvers
inf_maneuver_array: Ict containing array of infrastructure specific maneuvers
movobj_grps_coord: Coordinates of groups of detected objects
objlist: Object list
plot: Flag for graphical plotting
opendrive_path: Path to the OpenDRIVE file
use_folder: Iption to use folder structure
timebased_lon: Option to use time based trigger for long maneuvers
timebased_lat: Option to use time based trigger for lat maneuvers
section_name: Name of the scenario section
radius_pos_trigger: Radius of the position based trigger
dir_name: Name of the directory
osc_version: OpenSCENARIO version
output_path: Path to OpenSCENARIO file
Returns:
object (str): Path to scenario file
"""
if not isinstance(df, pd.DataFrame):
raise TypeError("input must be a pd.DataFrame")
if not isinstance(ego, list):
raise TypeError("input must be a list")
if not isinstance(objects, dict):
raise TypeError("input must be a dict")
if not isinstance(ego_maneuver_array, dict):
raise TypeError("input must be a dict")
if not isinstance(inf_maneuver_array, dict):
raise TypeError("input must be a dict")
if not isinstance(movobj_grps_coord, np.ndarray):
raise TypeError("input must be a np.ndarray")
if not isinstance(objlist, list):
raise TypeError("input must be a list")
if not isinstance(plot, bool):
raise TypeError("input must be a bool")
if not isinstance(opendrive_path, str):
raise TypeError("input must be a str")
if not isinstance(use_folder, bool):
raise TypeError("input must be a bool")
if not isinstance(timebased_lon, bool):
raise TypeError("input must be a bool")
if not isinstance(timebased_lat, bool):
raise TypeError("input must be a bool")
if not isinstance(section_name, str):
raise TypeError("input must be a str")
if not isinstance(radius_pos_trigger, float):
raise TypeError("input must be a float")
if not isinstance(dir_name, str):
raise TypeError("input must be a str")
if not isinstance(osc_version, str):
raise TypeError("input must be a str")
opendrive_name = opendrive_path.split(os.path.sep)[-1]
osgb_name = opendrive_name[:-4] + 'opt.osgb'
#Get User-defined parameters
user_param = UserConfig(dir_name)
user_param.read_config()
object_bb, object_bb_center = user_param.object_boundingbox, user_param.bbcenter_to_rear
# Write Parameters
param = xosc.ParameterDeclarations()
# Write catalogs
if user_param.catalogs is not None:
catalog_path = user_param.catalogs
else:
catalog_path = "../Catalogs/Vehicles"
catalog = xosc.Catalog()
catalog.add_catalog("VehicleCatalog", catalog_path)
# Write road network
road = xosc.RoadNetwork(
roadfile=opendrive_name, scenegraph=osgb_name
)
# Write entities
entities = xosc.Entities()
# Entity - ego
egoname = "Ego"
# vehicle
bb_input = []
if object_bb:
if object_bb[0] is not None and object_bb_center[0] is not None:
bb_input.extend([object_bb[0][0], object_bb[0][1], object_bb[0][2],
object_bb_center[0][0], object_bb_center[0][1], object_bb_center[0][2]])
elif object_bb[0] is None and object_bb_center[0] is not None:
bb_input.extend([1.872, 4.924, 1.444,
object_bb_center[0][0], object_bb_center[0][1], object_bb_center[0][2]])
elif object_bb[0] is not None and object_bb_center[0] is None:
bb_input.extend([object_bb[0][0], object_bb[0][1], object_bb[0][2],
1.376, 0, 0.722])
else:
# default values
bb_input.extend([1.872, 4.924, 1.444, 1.376, 0, 0.722])
else:
bb_input.extend([1.872, 4.924, 1.444, 1.376, 0, 0.722])
bb = xosc.BoundingBox(*bb_input) # dim(w, l, h), centre(x, y, z)
fa = xosc.Axle(0.48, 0.684, 1.672, 2.91, 0.342)
ra = xosc.Axle(0, 0.684, 1.672, 0, 0.342)
if float(osc_version) < 1.1:
ego_veh = xosc.Vehicle("car_white", xosc.VehicleCategory.car, bb, fa, ra, 67, 10, 9.5)
else:
ego_veh = xosc.Vehicle("car_white", xosc.VehicleCategory.car, bb, fa, ra, 67, 10, 9.5, 1700)
ego_veh.add_property(name="control", value="external")
ego_veh.add_property_file("")
# entity controller
prop = xosc.Properties()
prop.add_property(name="weight", value="60")
prop.add_property(name="height", value="1.8")
prop.add_property(name="eyeDistance", value="0.065")
prop.add_property(name="age", value="28")
prop.add_property(name="sex", value="male")
cont = xosc.Controller("DefaultDriver", prop)
if user_param.catalogs:
entities.add_scenario_object(
egoname, xosc.CatalogReference("VehicleCatalog", "car_blue")
)
else:
entities.add_scenario_object(egoname, ego_veh, cont)
# Entities - objects
bb_obj = []
for idx, obj in objects.items():
object_count = idx + 1
objname = f"Player{object_count}"
# vehicle
if len(object_bb) <= 1 or object_bb[object_count] is None and object_bb_center[object_count] is None:
# set default values
bb_obj.extend([1.872, 4.924, 1.444, 1.376, 0, 0.722])
elif object_bb[object_count] is None and object_bb_center[object_count] is not None:
bb_obj.extend([1.872, 4.924, 1.444,
object_bb_center[object_count][0],
object_bb_center[object_count][1],
object_bb_center[object_count][2]])
elif object_bb[object_count] is not None and object_bb_center[object_count] is None:
bb_obj.extend([object_bb[object_count][0], object_bb[object_count][1], object_bb[object_count][2],
1.376, 0, 0.722])
else:
bb_obj.extend([object_bb[object_count][0], object_bb[object_count][1], object_bb[object_count][2],
object_bb_center[object_count][0], object_bb_center[object_count][1], object_bb_center[object_count][2]])
bb = xosc.BoundingBox(*bb_obj) # dim(w, l, h), centre(x, y, z)
bb_obj.clear()
fa = xosc.Axle(0.48, 0.684, 1.672, 2.91, 0.342)
ra = xosc.Axle(0, 0.684, 1.672, 0, 0.342)
if float(osc_version) < 1.1:
obj_veh = xosc.Vehicle(objlist[idx], xosc.VehicleCategory.car, bb, fa, ra, 67, 10, 9.5)
else:
obj_veh = xosc.Vehicle(objlist[idx], xosc.VehicleCategory.car, bb, fa, ra, 67, 10, 9.5, 1700)
obj_veh.add_property(name="control", value="internal")
obj_veh.add_property_file("")
if user_param.catalogs:
entities.add_scenario_object(
objname, xosc.CatalogReference("VehicleCatalog", "car_white")
)
else:
entities.add_scenario_object(objname, obj_veh, cont)
# Determine Priority attribute according to osc version
if float(osc_version) <= 1.1:
xosc_priority = xosc.Priority.overwrite
else:
xosc_priority = xosc.Priority.override
# Write Init
init = xosc.Init()
step_time = xosc.TransitionDynamics(
xosc.DynamicsShapes.step, xosc.DynamicsDimension.rate, 0
)
# Start (init) conditions - Ego
egospeed = xosc.AbsoluteSpeedAction(float(f'{ego[2]}'), step_time)
egostart = xosc.TeleportAction(xosc.WorldPosition(x=f'{ego[0]}', y=f'{ego[1]}', z='0', h=f'{ego[3]}', p='0', r='0'))
init.add_init_action(egoname, egostart)
init.add_init_action(egoname, egospeed)
# init storyboard object
sb = xosc.StoryBoard(init)
# Start (init) conditions objects
for idx, obj in objects.items():
object_count = idx + 1
objname = f"Player{object_count}"
objspeed = xosc.AbsoluteSpeedAction(float(f'{obj[2]}'), step_time)
objstart = xosc.TeleportAction(xosc.WorldPosition(x=f'{obj[0]}', y=f'{obj[1]}',
z='0', h=f'{obj[3]}', p='0', r='0'))
init.add_init_action(objname, objstart)
init.add_init_action(objname, objspeed)
# Write Story
story = xosc.Story("New Story")
# For each vehicle write a separate Act
# (Act --> for each vehicle; Events inside of Act --> for each of vehicles maneuvers)
for key, maneuver_list in ego_maneuver_array.items():
if key == 0:
name = 'Ego'
else:
name = 'Player' + str(key)
eventcounter = 0
standstill = False
# Create necessary Story Element Objects
man = xosc.Maneuver(f'New Maneuver {key + 1}', parameters=param)
man_lat = xosc.Maneuver(f'New Maneuver {key + 1}', parameters=param)
mangroup = xosc.ManeuverGroup(f'New Sequence {key + 1}')
mangroup.add_actor(name)
# Start trigger for Act
act_trig_cond = xosc.SimulationTimeCondition(value=0, rule=xosc.Rule.greaterThan)
act_starttrigger = xosc.ValueTrigger(name=f'Start Condition of Act {key + 1}', delay=0,
conditionedge=xosc.ConditionEdge.rising, valuecondition=act_trig_cond)
act = xosc.Act(f'New Act {key + 1}', starttrigger=act_starttrigger)
long_event = False
# Loop ego specific maneuvers (accelerate, decelerate, standstill, ...)
for idx, ego_maneuver in enumerate(maneuver_list):
if str(ego_maneuver[2]) != 'FM_EGO_standstill':
eventcounter += 1
if standstill & (str(ego_maneuver[2]) == 'FM_EGO_standstill'):
standstill = True
if not standstill:
## Long maneuvers without move_in, move_out
event = xosc.Event(f'New Event {eventcounter}', priority=xosc_priority)
# Starting Condition of long maneuvers
if timebased_lon:
long_event = True
# Time based trigger
trig_cond = xosc.SimulationTimeCondition(value=float(ego_maneuver[0]) / 10, rule=xosc.Rule.greaterThan)
trigger = xosc.ValueTrigger(name=f'Start Condition of Event {eventcounter}', delay=0,
conditionedge=xosc.ConditionEdge.rising, valuecondition=trig_cond)
elif not timebased_lon:
long_event = True
# Position based absolute position trigger
worldpos = xosc.WorldPosition(x=ego_maneuver[3], y=ego_maneuver[4],
z='0', h='0', p='0', r='0')
trig_cond = xosc.DistanceCondition(value=f'{radius_pos_trigger}', rule=xosc.Rule.lessThan,
position=worldpos, alongroute="0", freespace="0")
trigger = xosc.EntityTrigger(name=f'Start Condition of Event {eventcounter}', delay=0,
conditionedge=xosc.ConditionEdge.rising, entitycondition=trig_cond,
triggerentity=f'{name}')
event.add_trigger(trigger)
dyn = xosc.TransitionDynamics(shape=xosc.DynamicsShapes.linear,
dimension=xosc.DynamicsDimension.rate, value=ego_maneuver[6])
action = xosc.AbsoluteSpeedAction(speed=ego_maneuver[5], transition_dynamics=dyn)
event.add_action(actionname=f"{ego_maneuver[2]}", action=action)
man.add_event(event)
if standstill & (str(ego_maneuver[2]) != 'FM_EGO_standstill'):
standstill = False
# Maneuver: change speed by absolute elapsed simulation time trigger
event = xosc.Event(f'New Event {eventcounter}', priority=xosc_priority)
trig_cond = xosc.SimulationTimeCondition(value=float(ego_maneuver[0]) / 10, rule=xosc.Rule.greaterThan)
trigger = xosc.ValueTrigger(name=f'Start Condition of Event {eventcounter}', delay=0,
conditionedge=xosc.ConditionEdge.rising, valuecondition=trig_cond)
event.add_trigger(trigger)
dyn = xosc.TransitionDynamics(shape=xosc.DynamicsShapes.linear,
dimension=xosc.DynamicsDimension.rate, value=ego_maneuver[6])
action = xosc.AbsoluteSpeedAction(speed=ego_maneuver[5], transition_dynamics=dyn)
event.add_action(actionname=f"{ego_maneuver[2]}", action=action)
man.add_event(event)
lateral_event = False
# Loop infrastructure specific maneuvers
current_inf_maneuver_array = inf_maneuver_array[key]
for idx, inf_maneuver in enumerate(current_inf_maneuver_array):
eventcounter += 1
if inf_maneuver[2] == 'FM_INF_lane_change_left':
lane_change = 1
elif inf_maneuver[2] == 'FM_INF_lane_change_right':
lane_change = -1
else:
raise ValueError('Lane change maneuver name is wrong')
# Lane Change
event = xosc.Event(f'New Event {eventcounter}', priority=xosc_priority)
# Starting Condition of lane change
if timebased_lat:
# Time based_lat trigger
trig_cond = xosc.SimulationTimeCondition(value=float(inf_maneuver[0]) / 10,
rule=xosc.Rule.greaterThan)
trigger = xosc.ValueTrigger(name=f'Start Condition of Event {eventcounter}', delay=0,
conditionedge=xosc.ConditionEdge.rising, valuecondition=trig_cond)
lateral_event = True
elif not timebased_lat:
# Position based absolute position trigger
worldpos = xosc.WorldPosition(x=inf_maneuver[3], y=inf_maneuver[4],
z='0', h='0', p='0', r='0')
trig_cond = xosc.DistanceCondition(value=f'{radius_pos_trigger}', rule=xosc.Rule.lessThan,
position=worldpos, alongroute="0", freespace="0")
trigger = xosc.EntityTrigger(name=f'Start Condition of Event {eventcounter}', delay=0,
conditionedge=xosc.ConditionEdge.rising, entitycondition=trig_cond,
triggerentity=f'{name}')
lateral_event = True
event.add_trigger(trigger)
dyn = xosc.TransitionDynamics(shape=xosc.DynamicsShapes.sinusoidal,
dimension=xosc.DynamicsDimension.time, value=inf_maneuver[5])
action = xosc.RelativeLaneChangeAction(lane=lane_change, entity=f'{name}', transition_dynamics=dyn,
target_lane_offset=4.26961e-316)
event.add_action(actionname=f"{inf_maneuver[2]}", action=action)
man_lat.add_event(event)
# Add maneuver events to act and story
if long_event:
mangroup.add_maneuver(man)
if lateral_event:
mangroup.add_maneuver(man_lat)
act.add_maneuver_group(mangroup)
story.add_act(act)
# Create Scenario
sb.add_story(story)
osc_minor_version = int(osc_version.split('.')[-1])
scenario = xosc.Scenario(
"",
"OSC Generator",
param,
entities,
sb,
road,
catalog,
creation_date=datetime.datetime(2023, 1, 1, 0, 0, 0, 0),
osc_minor_version=osc_minor_version
)
# Create Output Path
if output_path is not None:
path = output_path
else:
if use_folder:
if timebased_lon and timebased_lat:
path = os.path.join(dir_name, 'man_export_' + os.path.basename(section_name) + '_time_lon_lat.xosc')
elif timebased_lon and not timebased_lat:
path = os.path.join(dir_name,
'man_export_' + os.path.basename(section_name) + '_time_lon_pos_lat_' + str(
radius_pos_trigger) + '_m.xosc')
elif not timebased_lon and timebased_lat:
path = os.path.join(dir_name, 'man_export_' + os.path.basename(section_name) + '_pos_lon_time_lat.xosc')
else:
path = os.path.join(dir_name, 'man_export_' + os.path.basename(section_name) + '_pos_lon_lat_' +
str(radius_pos_trigger) + '_m.xosc')
else:
raise NotImplementedError("use_folder flag is going to be removed")
# Write Scenario to xml
scenario.write_xml(path)
return path
<file_sep># ****************************************************************************
# @utils.py
#
# @copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
#
# @license Apache v2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ****************************************************************************
import math
import decimal
import re
import pandas as pd
import numpy as np
from geographiclib.geodesic import Geodesic
from typing import Union
def delete_irrelevant_objects(df: pd.DataFrame, movobj_grps: Union[list, np.ndarray],
min_nofcases: int = 8, max_posx_min: float = 120.0,
max_posx_nofcases_ratio: float = 4.0) -> tuple:
"""
Deletes not relevant objects from input data
Args:
df: Input dataframe
movobj_grps: Detected objects
min_nofcases: Minimum number of cases (higher value means more dropping)
max_posx_min: Maximum of minimum distance to object (lower value means more dropping)
max_posx_nofcases_ratio: Maximum of ratio between minimum distance and number of cases
(lower value means more dropping)
Returns:
df: Dataframe containing only objects
count: Number of removed objects
"""
if not isinstance(df, pd.DataFrame):
raise TypeError("input must be a Dataframe")
if not (isinstance(movobj_grps, np.ndarray) or isinstance(movobj_grps, list)):
raise TypeError("input must be a list or np.ndarray")
if not isinstance(min_nofcases, int):
raise TypeError("input must be a integer")
if not isinstance(max_posx_min, float):
print(max_posx_min)
raise TypeError("input must be a float")
if not isinstance(max_posx_nofcases_ratio, float):
print(max_posx_nofcases_ratio)
raise TypeError("input must be a float")
end = len(df) - 1
count = 0
for p in movobj_grps:
posx_min = df[p[0]].min()
nofcases = sum(~pd.isna(df[p[0]]))
if nofcases < min_nofcases or posx_min > max_posx_min or posx_min / nofcases > max_posx_nofcases_ratio:
df = df.drop(columns=p)
# count += 1
else:
start = True
first_one = end
last_one = end
for i in range(len(df)):
if start and not pd.isna(df.loc[i, p[0]]):
first_one = i
start = False
elif not start and pd.isna(df.loc[i, p[0]]):
last_one = i - 1
break
variance = sum((df.loc[first_one:last_one, "speed"] - df.loc[first_one:last_one, p[2]]) ** 2)
if variance < 50 and nofcases < 50:
df = df.drop(columns=p)
count += 1
else:
for i in range(first_one, last_one):
acceleration = (abs(df.loc[i + 1, p[2]] - df.loc[i, p[2]]) / 3.6) * 10
if acceleration > 250:
df = df.drop(columns=p)
count += 1
break
return df, count
def calc_new_geopos_from_2d_vector_on_spheric_earth(curr_coords: pd.Series, heading: float, dist_x: float, dist_y: float) -> list:
"""
Computes the new coordinates of the traced car -- interpolation for only 200ms time intervals
Args:
curr_coords: Current coordinates of the ego car to get the heading of the car
heading: Tracked heading of the ego car
dist_x: Distances in x directions of the ego car
dist_y: Distances in y directions of the ego car
Returns:
object (list): List containing latitude and longitude of new position
"""
if not isinstance(curr_coords, pd.Series):
raise TypeError("input must be a pd.Series")
if not isinstance(heading, float):
raise TypeError("input must be a float")
if not isinstance(dist_x, float):
raise TypeError("input must be a float")
if not isinstance(dist_y, float):
raise TypeError("input must be a float")
earth_rad = 6378137 # Earth radius in meters
# Take angle from trace
beta = (heading * math.pi) / 180
# Step one: in x direction (ego view) new coordinates
x_versch = dist_x * math.cos(beta)
y_versch = dist_x * math.sin(beta)
d_lat = x_versch / earth_rad
d_lon = y_versch / (earth_rad * math.cos(math.pi * curr_coords[0] / 180))
lat_new = curr_coords[0] + d_lat * 180 / math.pi
lon_new = curr_coords[1] + d_lon * 180 / math.pi
first_coords = [lat_new, lon_new]
# Step two: in y direction (ego view) new coordinates
newbeta = beta - (math.pi / 2) # New heading shift pi/2 for y direction
x_versch_y = dist_y * math.cos(newbeta)
y_versch_y = dist_y * math.sin(newbeta)
d_lat_y = x_versch_y / earth_rad
d_lon_y = y_versch_y / (
earth_rad * math.cos(math.pi * first_coords[0] / 180))
lat_new_final = first_coords[0] + d_lat_y * 180 / math.pi
lon_new_final = first_coords[1] + d_lon_y * 180 / math.pi
new_coords = [lat_new_final, lon_new_final] # Final coordinates shifted in x as well as y direction
return new_coords
def flatten(x: Union[list, tuple]) -> list:
"""
Flattening function for nested lists and tuples
Args:
x: List or tuple
Returns:
object (list): Flat list
"""
if not isinstance(x, list) and isinstance(x, tuple):
raise TypeError("input must be a list or tuple")
out: list = []
for item in x:
if isinstance(item, (list, tuple)):
out.extend(flatten(item))
else:
out.append(item)
return out
def find_vars(pattern: str, var_list: pd.Series.index, reshape: bool = False) -> Union[np.ndarray, list]:
"""
Find variables for a given pattern in a list
Args:
pattern: Search pattern
var_list: List to be searched
reshape: If True pattern will be split by '|' and used to reshape output
Returns:
object (Union[np.ndarray, list]): Found variables
"""
if not isinstance(pattern, str):
raise TypeError("input must be a str")
if not isinstance(reshape, bool):
raise TypeError("input must be a bool")
tmp_list: list = []
for i in var_list:
if len(re.findall(pattern, i)):
tmp_list.append(i)
if not reshape:
return tmp_list
else:
order = len(pattern.split('|'))
shape = int(len(tmp_list) / order)
tlist_np = np.array(tmp_list).reshape(shape, order)
return tlist_np
def convert_heading(degree: Union[int, float]) -> Union[int, float]:
"""
Convert heading to other convention and unit
Args:
degree: Starting north increasing clockwise
Returns:
object (Union[int, float]): Heading angle in rad starting east increasing anti-clockwise and conversion
"""
if not (isinstance(degree, float) or isinstance(degree, int)):
raise TypeError("input must be a float or int")
float_degree = float(degree)
if float_degree == 0:
temp_degree: float = 0
else:
temp_degree = 360 - float_degree
temp_degree = temp_degree + 90
return math.radians(temp_degree)
def calc_heading_from_two_geo_positions(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""
Get the heading of the vehicle
Args:
lat1: Start latitude
lon1: Start longitude
lat2: End latitude
lon2: End longitude
Returns:
object (float): Heading in rad
"""
if not (isinstance(lat1, float) or isinstance(lat1, int)):
raise TypeError("input must be a float or int")
if not (isinstance(lon1, float) or isinstance(lon1, int)):
raise TypeError("input must be a float or int")
if not (isinstance(lat2, float) or isinstance(lat2, int)):
raise TypeError("input must be a float or int")
if not (isinstance(lon2, float) or isinstance(lon2, int)):
raise TypeError("input must be a float or int")
brng = Geodesic.WGS84.Inverse(lat1, lon1, lat2, lon2)['azi1']
return brng
<file_sep># Description
OSC-Generator is a collection of Python tools to generate [ASAM OpenSCENARIO](https://www.asam.net/standards/detail/openscenario/) files from vehicle data and an [ASAM OpenDRIVE](https://www.asam.net/standards/detail/opendrive/) file.

The generated openSCENARIO file (.xosc) can then be used for purposes such as scenario re-simulations, or in further applications, for example, visualised in a tool like [esmini](https://github.com/esmini/esmini).

## Scope of Application
Currently, OpenSCENARIO V1.2 and OpenDRIVE V1.4 are supported.
Intersections may currently cause trouble but will be supported in a future release.
All features are tested in Python 3.7 on Windows 10.
## Installation
### PyPI
- OSC-Generator can be installed using pip
```
pip install osc-generator
```
### Testing
- Additional dependencies for testing are required.
- Required Python packages can be installed via pip:
```
pip install -r requirements_dev.txt
```
- For testing, an ASAM OpenDRIVE file is needed. The file '_2017-04-04_Testfeld_A9_Nord_offset.xodr_' from [here](https://service.mdm-portal.de/mdm-portal-application/publDetail.do?publicationId=2594000) can be used by downloading a copy to the _tests/test_data_ folder. This file uses ASAM OpenDRIVE V1.4 format.
- Run pytest in the _tests_ folder or a parent folder thereof.
- When everything is set up correctly, all tests should run successfully without raising any warnings.
## Usage
- Class: OSC-Generator provides a Python class which can be used to generate a scenario in the OpenSCENARIO format from trajectories and an OpenDRIVE file. The file example.py contains runnable example code for usage of this class.
- CLI:
- OSC-Generator can use arguments provided via Python's commandline interface. For information on how to use this feature, see the output of the help function:
- When installed via pip, OSC-Generator can directly be called in the console:
```
osc_generator -h
```
- To use the OSC-Generator through the command line (without installation via pip), navigate to the main project directory and from there the help function can be called:
```
python -m osc_generator.osc_generator -h
```
- CLI arguments
- the following table outlines the available input arguments
| Argument | Type | Default Value | Description |
|-----|----------|--------------|--------------------------------------------------------------------|
| "-t", "--trajectories" | required | N/A | Path to the file containing the object trajectories used as input |
| "-d", "--opendrive" | required | N/A | Path to the opendrive file which describes the road net which the objects are using |
| "-s", "--openscenario" | optional | "None" | Output file path and name. If not specified, a directory and name will be chosen. If the file already exists , it will be overwritten |
| "-v", "--version" | optional | N/A | Show program's version number and exit |
| "-cat", "--catalog" | optional | "None" | Catalog file path and name. If not specified, a default catalog path is used |
| "-oscv", "--oscversion" | optional | "None" | Desired version of the output OpenScenario file. If not specified, default is OSC V1.0 |
## Expected Input Data and Formats
### Trajectories file
- the input trajectories file can currently be provided in two formats
- .csv
- .osi (Open Simulation Interface - see below)
- the following data is required in a .csv for an OpenSCENARIO file to be generated (especially when using lane data relative to the ego vehicle):
- **timestamp** [seconds] - time of each data point, from the beginning of the "scenario"
- **lat** [decimal degree (WGS84)] - latitude of the ego vehicle in the scenario
- **lon** [decimal degree (WGS84)] - longitude of the ego vehicle in the scenario
- **heading** [degrees (starting North, increasing clockwise)] - heading of the ego vehicle in the scenario
- **speed** [kilometers/hour] - speed of the ego vehicle in the scenario
- **lin_left_typ** [-] - lane type of left lane
- **lin_left_beginn_x** [meters] - beginning left lane detection point, relative to the ego vehicle, in the x direction
- **lin_left_y_abstand** [meters] - distance between the ego vehicle and the left lane, in the y direction
- **lin_left_kruemm** [-] - the curvature of the left lane
- **lin_left_ende_x** [meters] - end left lane detection point, relative to the ego vehicle, in the x direction
- **lin_left_breite** [meters] - width of the lane marking
- **lin_right_typ** [-] - lane type of left lane
- **lin_right_beginn_x** [meters] - beginning right lane detection point, relative to the ego vehicle, in the x direction
- **lin_right_y_abstand** [meters] - distance between the ego vehicle and the right lane, in the y direction
- **lin_right_kruemm** [-] - the curvature of the right lane
- **lin_right_ende_x** [meters] - end right lane detection point, relative to the ego vehicle, in the x direction
- **lin_right_breite** [meters] - lane type of right lane
- the following data is optional, depending on how many object vehicles are in the scenario - "#" represents the object number, starting at 1
- **pos_x_#** [meters] - distance between object vehicle and ego vehicle in x direction
- **pos_y_#** [meters] - distance between object vehicle and ego vehicle in y direction
- **speed_x_#** [kilometers/hour] - speed of object vehicle in x direction
- **speed_y_#** [kilometers/hour] - speed of object vehicle in y direction
- **class_#** [-] - class/type of object, e.g. 7 = car class
- for an example of an input trajectory .csv file, see "tests/test_data/trajectories_file.csv"
### OpenDRIVE file
- the OpenDRIVE file should be compliant with ASAM's standard
- ideally matching the trajectory data too
## Open Simulation Interface (OSI) Format Input
- In order to use OSI format (.osi) input trajectory files with the OSC-Generator, the following steps are required:
- install the Open Simulation Interface (OSI):
- follow the installation instructions: https://github.com/OpenSimulationInterface/open-simulation-interface
- copy the file 'OSITrace.py':
- from "$PATH_TO_OSI_DIRECTORY\open-simulation-interface\format"
- to "$PATH_TO_OSC-GENERATOR_DIRECTORY\OSC-Generator\osc_generator\tools\OSI"
- run tests
- Usage of this feature functions as described above.
- if OSI is not installed, the OSC-Generator can still be used with .csv input trajectory files.
## Citation
An associated [paper](https://ieeexplore.ieee.org/document/9575441) describes the original use case for which the OSC-Generator was created.
See also [this dissertation](https://opus4.kobv.de/opus4-fau/frontdoor/index/index/searchtype/authorsearch/author/Francesco+Montanari/docId/22788/start/0/rows/20).
When using this software, please cite the following:
```
@software{OSC-Generator,
author = {{<NAME>}, {<NAME>}, {<NAME>}, {<NAME>}, {<NAME>}, {<NAME>}, {<NAME>}},
license = {Apache-2.0},
title = {{OSC-Generator}},
url = {https://github.com/EFS-OpenSource/OSC-Generator},
version = {0.2.0}
}
```
## Acknowledgment
This work is supported by the German Federal Ministry for Digital and Transport (BMDV) within the *Automated and Connected Driving* funding program under grant No. 01MM20012F ([SAVeNoW](https://savenow.de)).
@copyright 2022 e:fs TechHub GmbH and Audi AG. All rights reserved.
https://www.efs-techhub.com/
https://www.audi.com/de/company.html
@license Apache v2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| af6f11b64c2ead30d87394c54c6d2e212ad9323d | [
"Markdown",
"Python",
"Text"
]
| 18 | Python | EFS-OpenSource/OSC-Generator | 48177576849e3a600d5d3914447286bf3d1d95e4 | c6b402e15eabc4d3614a0ffd716f700823bf2112 |
refs/heads/master | <repo_name>alnouirah/Template1<file_sep>/js/plugin.js
$( document ).ready(function() {
setTimeout(function(){
$('.overlayLoading').fadeOut(800,function(){
$(this).remove();
})
}, 1000);
$('.slider__item').on('mouseover', function(){
$('.slider__item').removeClass('active');
$(this).addClass('active');
});
$('.slider__item').on('mouseout', function(){
$('.slider__item').removeClass('active');
$(this).addClass('');
});
});
| e3a7a2b52f779c06885866b9ddb67144127ebdc9 | [
"JavaScript"
]
| 1 | JavaScript | alnouirah/Template1 | 71dfcac56fa666bd9485c70afe10e8beea864124 | 4c518f1c6386b8f7ae986a3c9d0f29c9a8f84b01 |
refs/heads/master | <repo_name>DI-Isvor/DI<file_sep>/animateCC/localStorage.js
function setLocalStorage(key, valor) {
localStorage.setItem(key, valor);
}
function getLocalStorage(key) {
localStorage.getItem(key);
}<file_sep>/animateCC/auxiliar.js
var array = [];
/*array[] = ScormProcessGetValue("cmi.suspend_data");*/
var index = null;
var auxiliar = null;
function clickTest(index, auxiliar){
if (auxiliar == true){
array[index] = true;
}
if (auxiliar == false){
array[index] = false;
}
/* ScormProcessSetValue("cmi.suspend_data", array[]); */
}
function retorno(index){
alert(array[index]);
}
| 59e83fd0d560fd3cee4d4eb9a85ec6a3c3d241cc | [
"JavaScript"
]
| 2 | JavaScript | DI-Isvor/DI | e31c13e063d2241b925d9c9563bc63c16b86632c | 4e5ea63e1d906c99f51e83fcf1d8d53c75213833 |
refs/heads/master | <file_sep>console.log('hello from main.js!');
document.querySelector('#root').innerHTML = `<h1>Hello from main.js!</h1>`;
require('./main.css');
require('./main.scss');
require('./index.html'); | f6d4aa4fd5d95dc7b80f39a4bbcb2a3e7d221ecf | [
"JavaScript"
]
| 1 | JavaScript | gerardramosm89/webpack-demonstration | c0a759878f45a9cd5bc9a887b50622b6af0ebcdd | cf406745c11054963689ce1ca181f5e6121d91b3 |
refs/heads/master | <repo_name>ryaugusta/holistic-health-app-android<file_sep>/README.md
# holistic-health-app-android
Final project for my Android class. Create our own application from our own idea - this was mine.
<file_sep>/java/com/example/ryanaugusta/hoistichealthapp/MyCursorAdapter.java
// Project: Holistic Health App
// Author: <NAME>
// Date: 2018
// Desc: This Handles the cursor adapter
package com.example.ryanaugusta.hoistichealthapp;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.ContactsContract;
import android.text.style.TtsSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
/**
* Created by ryanaugusta on 2/4/18.
*/
public class MyCursorAdapter extends CursorAdapter implements Filterable {
SQLiteDatabase db;
// CursorAdapter will handle all the moveToFirst(), getCount() logic
public MyCursorAdapter(Context context, Cursor c)
{
super(context, c, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
@Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup)
{
// using my own list item layout
return LayoutInflater.from(context).inflate(R.layout.list_items, viewGroup, false);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
@Override
public void bindView(View view, Context context, Cursor cursor)
{
// get the data from the cursor
String id = cursor.getString(0);
String name = cursor.getString(1);
String info = cursor.getString(2);
// get the textViews inside the item in the listView
TextView tvItemName = (TextView)view.findViewById(R.id.tvItemName);
TextView tvItemInfo = (TextView)view.findViewById(R.id.tvItemInfo);
// assign the data from the cursor to the textViews in the item in listView
tvItemName.setText(name);
tvItemInfo.setText(info);
}
}
<file_sep>/java/com/example/ryanaugusta/hoistichealthapp/AddDialog.java
// Project: Holistic Health App
// Author: Augusta
// Date: 2018
// Desc: This is an add dialog that can be utilized to populate the supplement ListView
// I may change this to populate the 'MyStack' ListView instead.
package com.example.ryanaugusta.hoistichealthapp;
import android.app.Dialog;
//import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.support.v4.app.DialogFragment;
/**
* Created by ryanaugusta on 2/4/18.
*/
// THIS CLASS MAY NOT BE NEEDED.
public class AddDialog extends DialogFragment {
// create a reference for the inflator
private LayoutInflater inflater;
private EditText etName;
// private EditText etInfo;
// private EditText etName;
// private EditText etInfo;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// create the dialog builder
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//builder.setMessage("Add" + name + "to My Stack?");
// set the title
builder.setTitle("Add to 'My Stack'");
// Get the layout inflater object
inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View dialogLayout = inflater.inflate(R.layout.add_dialog, null);
builder.setView(dialogLayout);
// create the Java objects and tie to the dialog GUI
etName = (EditText)dialogLayout.findViewById(R.id.etName);
// etInfo = (EditText)dialogLayout.findViewById(R.id.etInfo);
// add a positive button
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
System.out.println("Add dialog onClick called");
try
{
MyStackInfo myStackInfo = new MyStackInfo(etName.getText().toString());
// debug
System.out.println(myStackInfo.toString());
addListener.addDialogPositiveClick(myStackInfo);
}
catch(Exception e)
{
System.out.println("Catch: " + e.getMessage());
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
}
});
return builder.create();
}
// public interface used to define callback methods
// that will be called in the MainActivity
public interface AddDialogListener
{
// these method will be implemented in the MainActivity
public void addDialogPositiveClick(MyStackInfo myStackInfo);
public void addDialogNegativeClick();
}
// Use this reference of the interface to deliver action events
private AddDialogListener addListener;
// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
@Override
public void onAttach(Context context)
{
super.onAttach(context);
// Verify that the host activity implements the callback interface
try
{
// Instantiate the addListener so we can send events to the host
// addListener = (AddDialogListener) context;
// set the fragment as the listener for the dialog
addListener = (AddDialogListener)getTargetFragment();
}
catch (ClassCastException e)
{
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(context.toString()
+ " must implement AddDialogListener");
}
}
}
<file_sep>/java/com/example/ryanaugusta/hoistichealthapp/MyStackFragment.java
// Project: Holistic Health App
// Author: <NAME>
// Class: MyStackFragment
// Description: This class handles the My Stack fragment.
package com.example.ryanaugusta.hoistichealthapp;
//import android.app.Fragment;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.IntDef;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
/**
* Created by ryanaugusta on 2/1/18.
*/
public class MyStackFragment extends Fragment implements DeleteConfirmDialog.DeleteConfirmDialogListener,
SaveDialog.SaveConfirmDialogListener
{
// declare Java references
private TextView msgTextView;
private ListView lvMyStack;
private DatabaseHandler dbh;
private MyCursorAdapter addAdapter;
private Button btnClear;
// textView tied to the calendar
private TextView tvStartDate;
// floating action button for calendar
private FloatingActionButton fab_calendar;
private ArrayAdapter<String> adapter;
private MyStackFragment frag;
public static MyStackFragment newInstance()
{
MyStackFragment fragment = new MyStackFragment();
return fragment;
}
// default constructor
public MyStackFragment() {
}
// Called to create the view hierarchy associated with the fragment.
// container from Activity holding the fragment.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// inflate the xml layout file into the fragment, save the rootview
View rootView = inflater.inflate(R.layout.mystack_frag, container, false);
// Get the main activity in case needed
MainActivity ma = (MainActivity)getActivity();
// use the rootView and findViewById to create Java object tied to the resource
msgTextView = rootView.findViewById(R.id.msgTextView);
msgTextView.setText("My Stack");
fab_calendar = rootView.findViewById(R.id.fab_calendar);
tvStartDate = rootView.findViewById(R.id.tvStartDate);
btnClear = rootView.findViewById(R.id.btnClear);
lvMyStack = rootView.findViewById(R.id.lvMystack);
dbh = new DatabaseHandler(this.getContext());
addAdapter = myCursorAdapter();
lvMyStack.setAdapter(addAdapter);
frag = this;
// get bundle from the Supplement Fragment and display in the MyStack ListView
Bundle bundle = this.getArguments();
if (bundle != null)
{
adapter = stackAdapter(bundle.getString("name"));
lvMyStack.setAdapter(adapter);
}
lvMyStack.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
// get the textViews inside the item in the listView
TextView tvItemName = (TextView)view.findViewById(R.id.tvItemName);
// create a bundle object
Bundle args = new Bundle();
// add the name selected to the bundle with key name
args.putString("name", tvItemName.getText().toString());
// create the DeleteDialog
DialogFragment newFragment = new DeleteConfirmDialog();
// set BusinessFragment as the target for the dialog
newFragment.setTargetFragment(frag, 0);
// add the args bundle to the dialog fragment
newFragment.setArguments(args);
// show it
newFragment.show(getFragmentManager(), "delete");
return true;
}
});
// floating action button for calendar
fab_calendar.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
try
{
// show the datePicker dialog
DialogFragment newFragment = new DatePickerFragment();
newFragment.setTargetFragment(frag, 0);
newFragment.show(getFragmentManager(), "datePicker");
}
catch (Exception e)
{
System.out.println("Caught Exception For Calendar");
}
}
});
btnClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try
{
clearAllEntries();
}
catch (Exception e) {
System.out.println("it didn't work");
}
}
});
Log.i("Fragment", "MyStack onCreateView");
return rootView;
}
private ArrayAdapter<String> stackAdapter(String stack)
{
ArrayList<String> stackList = new ArrayList<>(Arrays.asList(stack));
ArrayAdapter<String> stackAdapter = new ArrayAdapter<String>(this.getContext(), android.R.layout.simple_list_item_1, stackList);
return stackAdapter;
}
protected MyCursorAdapter myCursorAdapter()
{
// get new cursor from the database
Cursor cursor = dbh.getAllMyStackObjects();
// create the cursorAdapter and return it
return new MyCursorAdapter(this.getContext(), cursor);
}
// lifecycle methods
// Called when the fragment has been associated with the activity (the Activity is passed in here).
@Override
public void onAttach(Context context)
{
Log.i("Fragment", "Home onAttach");
super.onAttach(context);
}
// Called when the activity's onCreate() method has returned.
@Override
public void onActivityCreated (Bundle savedInstanceState)
{
Log.i("Fragment", "Home onActivityCreated");
super.onActivityCreated(savedInstanceState);
}
// Called when the view previously created by onCreateView(LayoutInflater,
// ViewGroup, Bundle) has been detached from the fragment.
@Override
public void onDestroyView ()
{
Log.i("FragmentEx", "Frag1 onDestroyView");
super.onDestroyView();
}
// Called when the fragment is no longer attached to its activity. This is called after onDestroy()
@Override
public void onDetach()
{
Log.i("FragmentEx", "Frag1 onDetach");
super.onDetach();
}
// Called when the Fragment is no longer resumed.
// This is generally tied to Activity.onPause of the containing Activity's lifecycle.
@Override
public void onPause ()
{
Log.i("Fragment", "Home onPause");
super.onPause();
}
// Called when the fragment is visible to the user and actively running.
// This is generally tied to Activity.onResume of the containing Activity's lifecycle.
@Override
public void onResume ()
{
Log.i("Fragment", "Home onResume");
super.onResume();
}
// Called when the Fragment is visible to the user.
// This is generally tied to Activity.onStart of the containing Activity's lifecycle.
@Override
public void onStart ()
{
Log.i("Fragment", "Home onStart");
super.onStart();
}
// Called when the Fragment is no longer started.
// This is generally tied to Activity.onStop of the containing Activity's lifecycle.
@Override
public void onStop ()
{
Log.i("Fragment", "Home onStop");
super.onStop();
}
@Override
public void onDialogDeleteNegativeClick()
{
// do nothing
}
// delete dialogs
@Override
public void onDialogDelete(String name)
{
// get the data from database and get new cursor
dbh.deleteMyStackByName(name);
addAdapter.notifyDataSetChanged();
// swap new cursor into cursorAdapter
addAdapter.swapCursor(dbh.getAllMyStackObjects());
System.out.println("delete selected");
}
@Override
public void onDialogSaveNegativeClick()
{
}
@Override
public void onDialogSave(String name)
{
dbh.testMyStackAdd(name);
addAdapter.swapCursor(dbh.getAllMyStackObjects());
addAdapter.notifyDataSetChanged();
Log.i("SaveDialog", "instance saved from fragment");
}
// method to clear all entries in the List
public void clearAllEntries()
{
MainActivity ma = (MainActivity)getActivity();
dbh.deleteMyStackObjects();
addAdapter.swapCursor(dbh.getAllMyStackObjects());
addAdapter.notifyDataSetChanged();
Toast.makeText(ma, "List has been cleared", Toast.LENGTH_SHORT).show();
}
// Calendar Methods
// set date using a calendar object to the textView
// called from DatePickerFragment
public void setDate(Calendar aDate)
{
//Examples for April 6, 1970 at 3:23am:
//"MM/dd/yy h:mmaa" -> "04/06/70 3:23am"
//"MMM dd, yyyy h:mmaa" -> "Apr 6, 1970 3:23am"
//"MMMM dd, yyyy h:mmaa" -> "April 6, 1970 3:23am"
//"E, MMMM dd, yyyy h:mmaa" -> "Mon, April 6, 1970 3:23am&
//"EEEE, MMMM dd, yyyy h:mmaa" -> "Monday, April 6, 1970 3:23am"
// display the date chosen and days from current
tvStartDate.setText("Your cycle will begin on " + DateFormat.format("EEEE, MMMM dd, yyyy. ", aDate)); //+
//daysBetween(Calendar.getInstance(), aDate)); //+ " days from today");
}
}
| 3cab41113b19ebb24933f33cf1b4ece78d11149b | [
"Markdown",
"Java"
]
| 4 | Markdown | ryaugusta/holistic-health-app-android | 6dbc1e6afb767bae7bc28854353183fcbdba2f74 | 5035fbd91fe4fbdf3a183420da0100e5ac6dfa33 |
refs/heads/master | <repo_name>2892931976/HelpHim<file_sep>/README.md
# SpringBoot项目脚手架
## 集成框架
1. SpringBoot1.3.5.RELEASE
2. spring-boot-starter-thymeleaf1.4.0.RELEASE
3. MyBatis3.4.1
4. MySQL
5. Shiro1.2.5
6. 前端基于Bootstrap3的框架:Inspinia2.5, 这个出2.6了,修复了2.5在移动端的BUG等等,之后有时间再升级。
## shiro
### 问题 subject.isPermitted(String permission) 权限验证的逻辑
该方法判断登陆用户是否有某个权限,逻辑位于WildcardPermission.implies
1. 假设用户具有system权限,我们需要验证用户是否具有system:role:page权限
2. shiro会将权限分开成3部分变成:用户已有权限:[system], 待验证权限:[system]:[role]:[page]
3. 在第一部分[system]shiro会判断权限验证通过,而已有权限部分长度小于待验证的,shiro就认为用户有该部分开头的所有权限,代码如下
// If this permission has less parts than the other permission, everything after the number of parts contained
// in this permission is automatically implied, so return true
if (getParts().size() - 1 < i) {
return true;
} else {
Set<String> part = getParts().get(i);
if (!part.contains(WILDCARD_TOKEN) && !part.containsAll(otherPart)) {
return false;
}
i++;
}
### 结论
>所以我们在使用的时候,全选就把父菜单的权限分配进数据库,否则只能分配子菜单的权限进数据库。
## thymeleaf
### 问题 在页面中使用\<script type="text/html">\</script>
1. thymeleaf会检查html语法,对于<%%>这种符号不允许出现!!看之后能找到地方修改thymelefa语法检查么
## 目的
1. 抽象Controller、Service、Mapper中的公共方法,
2. 包括JS中也可以使用模板模式节约大量工作量(static/js/common.js,权限做完后这个文件要优化)
3. 实现自己的自定义标签库,之后重新开个github项目
## 使用
0. 约定
1. 数据库表别名,第一个单词的首字母和下划线后首字母的拼接,例如:sys_role_permission 别名为 srp
2. 如果该表需要使用JqGrid条件查询,请在POJO中为表和VO字段加上@TableAlias注解 @see com.vanxd.data.entity.user.SysPermission
3. Mapper.xml中在需要用到JqGrid条件查询的地方,一定要写表别名。
1. 分页(page)接口数据筛选条件:
1. 可传实体属性作为参数查询。
2. 可传filters参数,参数值符合jqGrid多条件查询的json字符串格式,具体可看Filter类
3. 以上两个参数都存在时,只会使用filters参数。当然,这个取决于mapper.xml中的判断
2. 列表页(例,接口:/system/permission/page)
1. 将会返回/views/system/permission/pageSysPermission.html该页面,可在子控制器重写pageView()来指定页面。
2. 列表页中使用jqGrid以ajax请求list.json接口获得列表数据。
3. checkbox和radio统一使用iCheck
1.common.js中的bindIChecks(selector),之后优化放到其他文件
2.iCheck获得事件源event.target
4. 权限管理:菜单是由模块->菜单->功能 3级组成
1. 权限增加时如果是菜单级需要填写相应的URI<file_sep>/data/src/main/resources/TableStructure.sql
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50616
Source Host : localhost:3306
Source Database : helphim
Target Server Type : MYSQL
Target Server Version : 50616
File Encoding : 65001
Date: 2016-11-15 17:10:04
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for sys_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_permission`;
CREATE TABLE `sys_permission` (
`id` varchar(32) NOT NULL,
`create_time` datetime NOT NULL,
`status` int(11) NOT NULL,
`description` varchar(100) NOT NULL,
`permission` varchar(50) NOT NULL,
`name` varchar(20) NOT NULL,
`weight` int(11) NOT NULL,
`type` int(11) NOT NULL,
`creator_user_id` varchar(32) NOT NULL,
`is_show` bit(1) NOT NULL,
`icon` varchar(20) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
`parent_id` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `u_permission` (`permission`),
KEY `index_parent_id` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_permission
-- ----------------------------
INSERT INTO `sys_permission` VALUES ('06237d1d31b645ad948b9a0345315e07', '2016-11-02 15:47:46', '1', '用户详情', 'system:user:detail', '用户详情', '1', '3', '1', '\0', '', '', '690dd7a92cf44126bb3e0d5673d52f82');
INSERT INTO `sys_permission` VALUES ('06237d1d31b645ad948b9a0345315e08', '2016-11-02 15:47:46', '1', '角色详情', 'system:role:detail', '角色详情', '1', '3', '1', '\0', '', '', 'ef31d2d192ed4659b50d084fb649e2e2');
INSERT INTO `sys_permission` VALUES ('06237d1d31b645ad948b9a0345315e09', '2016-11-02 15:47:46', '1', '权限详情', 'system:permission:detail', '权限详情', '1', '3', '1', '\0', '', '', 'cc933ded4957417e9636a3d98b3a7a86');
INSERT INTO `sys_permission` VALUES ('08a8a730de184efeb3ee0bd82e5289a0', '2016-11-02 15:46:58', '1', '编辑系统用户', 'system:user:edit', '用户编辑', '1', '3', '1', '\0', '', '', '690dd7a92cf44126bb3e0d5673d52f82');
INSERT INTO `sys_permission` VALUES ('08a8a730de184efeb3ee0bd82e5289a1', '2016-11-02 15:46:58', '1', '编辑角色', 'system:role:edit', '角色编辑', '1', '3', '1', '\0', '', '', 'ef31d2d192ed4659b50d084fb649e2e2');
INSERT INTO `sys_permission` VALUES ('08a8a730de184efeb3ee0bd82e5289a2', '2016-11-02 15:46:58', '1', '编辑权限', 'system:permission:edit', '权限编辑', '1', '3', '1', '\0', '', '', 'cc933ded4957417e9636a3d98b3a7a86');
INSERT INTO `sys_permission` VALUES ('690dd7a92cf44126bb3e0d5673d52f82', '2016-11-02 16:20:53', '1', '用户管理', 'system:user', '用户管理', '1', '2', '1', '', '', '/system/user/page', '6e36ea2494e049a0bfbda74f86f18c0a');
INSERT INTO `sys_permission` VALUES ('6e36ea2494e049a0bfbda74f86f18c0a', '2016-10-11 14:51:43', '1', '系统相关配置管理', 'system', '系统管理', '1', '1', '1', '', 'fa-gear', '', '0');
INSERT INTO `sys_permission` VALUES ('cc933ded4957417e9636a3d98b3a7a86', '2016-11-02 16:21:37', '1', '权限管理', 'system:permission', '权限管理', '3', '2', '1', '', '', '/system/permission/page', '6e36ea2494e049a0bfbda74f86f18c0a');
INSERT INTO `sys_permission` VALUES ('df10f89acd494418954b893cf5c2a0c9', '2016-10-11 16:17:11', '1', '角色管理', 'system:role:page', '角色列表', '2', '2', '1', '', '', '', 'ef31d2d192ed4659b50d084fb649e2e2');
INSERT INTO `sys_permission` VALUES ('eca3dc246a184785997340af52977a06', '2016-10-12 14:02:34', '1', '系统用户管理', 'system:user:page', '用户列表', '3', '2', '1', '', '', '', '690dd7a92cf44126bb3e0d5673d52f82');
INSERT INTO `sys_permission` VALUES ('ef31d2d192ed4659b50d084fb649e2e2', '2016-11-02 16:21:14', '1', '角色管理', 'system:role', '角色管理', '2', '2', '1', '', '', '/system/role/page', '6e36ea2494e049a0bfbda74f86f18c0a');
INSERT INTO `sys_permission` VALUES ('f2d33140b0304f7f8cd056b3c0b8ba18', '2016-10-11 16:12:23', '1', '管理每一个功能的权限', 'system:permission:page', '菜单权限列表', '1', '2', '1', '', '', '', 'cc933ded4957417e9636a3d98b3a7a86');
INSERT INTO `sys_permission` VALUES ('fd4b2b8f0860412ca64037e69cebf1dc', '2016-11-02 15:48:15', '1', '删除用户', 'system:user:delete', '用户删除', '1', '3', '1', '\0', '', '', '690dd7a92cf44126bb3e0d5673d52f82');
INSERT INTO `sys_permission` VALUES ('fd4b2b8f0860412ca64037e69cebf1dd', '2016-11-02 15:48:15', '1', '删除角色', 'system:role:delete', '角色删除', '1', '3', '1', '\0', '', '', 'ef31d2d192ed4659b50d084fb649e2e2');
INSERT INTO `sys_permission` VALUES ('fd4b2b8f0860412ca64037e69cebf1de', '2016-11-02 15:48:15', '1', '删除权限', 'system:permission:delete', '权限删除', '1', '3', '1', '\0', '', '', 'cc933ded4957417e9636a3d98b3a7a86');
-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` varchar(32) NOT NULL,
`create_time` datetime NOT NULL,
`status` int(11) NOT NULL,
`description` varchar(300) NOT NULL,
`name` varchar(100) NOT NULL,
`role` varchar(100) NOT NULL,
`creator_user_id` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `u_role` (`role`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES ('1', '2016-09-09 16:35:41', '1', '系统超级管理员', '系统超级管理员', 'admin', '1');
INSERT INTO `sys_role` VALUES ('5853886fe60f462fb5fb74dbb17ead5b', '2016-10-12 11:56:21', '1', '只能管理系统角色', '角色管理员', 'role_manager', '1');
INSERT INTO `sys_role` VALUES ('a779072db9d04bf086df08ad26a94f0a', '2016-10-29 15:46:14', '1', '只有用户管理菜单', '用户管理', 'user_manager', '1');
-- ----------------------------
-- Table structure for sys_role_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_permission`;
CREATE TABLE `sys_role_permission` (
`id` varchar(32) NOT NULL,
`create_time` datetime NOT NULL,
`status` int(11) NOT NULL,
`role_id` varchar(32) NOT NULL,
`permission_id` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
KEY `index_role_permission` (`role_id`,`permission_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_role_permission
-- ----------------------------
INSERT INTO `sys_role_permission` VALUES ('04815ce2142f46b1a1ac9289361233ea', '2016-11-14 17:40:52', '1', '1', 'f2d33140b0304f7f8cd056b3c0b8ba18');
INSERT INTO `sys_role_permission` VALUES ('04e9ae79a03c440a96083f10568a4dcb', '2016-11-14 17:40:56', '1', '1', '08a8a730de184efeb3ee0bd82e5289a0');
INSERT INTO `sys_role_permission` VALUES ('09a7ee6197294f63bd5917b55d7877ce', '2016-11-14 17:40:55', '1', '1', 'ef31d2d192ed4659b50d084fb649e2e2');
INSERT INTO `sys_role_permission` VALUES ('1b0f18c89ec5419887fc0b30b8600e51', '2016-11-14 17:40:52', '1', '1', 'cc933ded4957417e9636a3d98b3a7a86');
INSERT INTO `sys_role_permission` VALUES ('44687c954eb44885a3f848ce7edea750', '2016-11-14 17:40:55', '1', '1', '690dd7a92cf44126bb3e0d5673d52f82');
INSERT INTO `sys_role_permission` VALUES ('464959abac98464bb1ae4ab5dc12dd89', '2016-11-14 17:40:55', '1', '1', 'fd4b2b8f0860412ca64037e69cebf1dd');
INSERT INTO `sys_role_permission` VALUES ('48c859f7ada64cbeab4ec7bb700e673c', '2016-11-14 17:40:56', '1', '1', '06237d1d31b645ad948b9a0345315e07');
INSERT INTO `sys_role_permission` VALUES ('736d94e06e934bfb855eb3c6bc390a8c', '2016-11-14 17:40:56', '1', '1', 'fd4b2b8f0860412ca64037e69cebf1dc');
INSERT INTO `sys_role_permission` VALUES ('790035af69e143d4bbe6f57c629dece2', '2016-11-14 17:40:55', '1', '1', '06237d1d31b645ad948b9a0345315e08');
INSERT INTO `sys_role_permission` VALUES ('8082be6a50a94672bef45cffa23b89a0', '2016-11-14 17:40:55', '1', '1', '08a8a730de184efeb3ee0bd82e5289a1');
INSERT INTO `sys_role_permission` VALUES ('8f4b63fa1263497aa2cd9abc6a4daf06', '2016-11-14 17:40:57', '1', '1', '6e36ea2494e049a0bfbda74f86f18c0a');
INSERT INTO `sys_role_permission` VALUES ('bee2d59bdbbd427bb1dcfe238c51314d', '2016-11-14 17:40:52', '1', '1', 'fd4b2b8f0860412ca64037e69cebf1de');
INSERT INTO `sys_role_permission` VALUES ('c10a8cd6a08047fbb2dd168a7162756d', '2016-11-14 17:40:56', '1', '1', 'eca3dc246a184785997340af52977a06');
INSERT INTO `sys_role_permission` VALUES ('dc4fffe47227413eac48d7a82b40408c', '2016-11-14 17:40:52', '1', '1', '<PASSWORD>');
INSERT INTO `sys_role_permission` VALUES ('e775506b0ba2422aa372fd89cff5fe63', '2016-11-14 17:40:52', '1', '1', '0<PASSWORD>4531<PASSWORD>');
INSERT INTO `sys_role_permission` VALUES ('eeb8da7c97fe4966a92025209cab2d79', '2016-11-14 17:40:55', '1', '1', 'df10f89acd494418954b893cf5c2a0c9');
-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` varchar(32) NOT NULL,
`create_time` datetime NOT NULL,
`status` int(11) NOT NULL,
`email` varchar(100) NOT NULL,
`nickname` varchar(100) NOT NULL,
`mobile_phone` varchar(11) NOT NULL,
`password` varchar(100) NOT NULL,
`salt` varchar(5) NOT NULL,
`username` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `u_username` (`username`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES ('1', '2016-09-08 15:57:12', '1', '123', 'AdminNickname', '123', '849f92e1dbe18285fd48adadfb20e6ce', 'AhLDi', 'admin');
INSERT INTO `sys_user` VALUES ('134991168d8d42e2b573858a1097cf65', '2016-10-12 15:55:40', '1', '12312', 'wyd', '11111111111', '31deb0285f1912a808cb006832a798d3', 'iXC3f', 'wyd');
INSERT INTO `sys_user` VALUES ('97426f411dc7403c9ef78a2a8bc65c0e', '2016-10-29 15:45:45', '1', '3734<EMAIL>', 'test', '17785145470', '56dfcf54fdd5c2d5d2b6e4c3e47ceb6a', 'iwcMW', 'test');
-- ----------------------------
-- Table structure for sys_user_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`id` varchar(32) NOT NULL,
`create_time` datetime NOT NULL,
`status` int(11) NOT NULL,
`user_id` varchar(32) NOT NULL,
`role_id` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
KEY `index_user_role` (`user_id`,`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_user_role
-- ----------------------------
INSERT INTO `sys_user_role` VALUES ('0fd727ca33874cdeae77d9e881dc45b5', '2016-10-20 15:33:35', '1', '1', '1');
INSERT INTO `sys_user_role` VALUES ('5093317921a440228d3c9afe84179d59', '2016-10-28 15:20:23', '1', '1', '5853886fe60f462fb5fb74dbb17ead5b');
INSERT INTO `sys_user_role` VALUES ('7839963b77ed40e9a45496bd768935d0', '2016-10-29 16:14:18', '1', '97426f411dc7403c9ef78a2a8bc65c0e', 'a779072db9d04bf086df08ad26a94f0a');
SET FOREIGN_KEY_CHECKS=1;
<file_sep>/admin/src/main/resources/static/js/system/user/pageSysUser.js
$(function () {
buildJqGridGenerator();
initValidate();
});
function initValidate() {
$("#edit-form").validate({
errorPlacement: (error, element) => {
element.after(error);
},
rules: {
nickname : {
required : true,
maxlength : 100
},
username : {
required : true,
maxlength : 100
},
password : {
accordingTo : true,
maxlength : 30,
minlength : 6
},
email : {
required : true,
maxlength : 100
},
mobilePhone : {
required : true,
number : true,
maxlength : 11,
minlength : 11
}
},
messages : {
nickname : {
required : "必填",
maxlength : "最长100个字符"
},
username : {
required : "必填",
maxlength : "最长100个字符"
},
password : {
maxlength : "最长30个字符",
minlength : "最短6个字符",
accordingTo : "必填"
},
email : {
required : "必填",
maxlength : "最长100个字符"
},
mobilePhone : {
required : "必填",
number : "只能填数字",
maxlength : "最长11个字符",
minlength : "最短11个字符"
}
},
submitHandler : form => {
$(form).ajaxSubmit({
success : result => {
if(200 == result.code) {
$(iJqGrid).trigger("reloadGrid");
$("#edit-modal-form").modal("hide");
} else {
alert(result.message);
}
}
});
}
});
}
function buildJqGridGenerator() {
var tableSelector = "#data-table-1",
pager = "pager-table-1";
return jqGridFactory.generate({
tableSelector : tableSelector,
pager : pager,
url : "/system/user/list.json",
caption:"系统用户列表",
colNames : ["昵称", "用户名", "邮箱", "手机", "创建时间" ],
colModel : [
{
name : "nickname",
index : "nickname"
},
{
name : "username",
index : "username"
},
{
name : "email",
index : "email",
},
{
name : "mobilePhone",
index : "mobilePhone"
},
{
name : "createTime",
index : "createTime",
formatter : (cellValue, options, row) => {
return new Date(cellValue).format("yyyy-MM-dd hh:mm:ss");
},
searchoptions : {
dataInit : ele => {
DateTimePickerFactory.generate(ele);
}
}
}
]
}).navButtonAdd('#pager-table-1',{
caption : "",
title : "关联角色",
buttonicon : "ui-icon-shuffle",
onClickButton : listRoles
});
}
/**
* 显示所有角色,并标注该用户已关联的角色
*/
function listRoles() {
var dataId = iJqGrid.jqGrid('getGridParam','selrow');
if(!dataId) {
alert("请选择需要关联角色的用户!");
return ;
}
$.ajax({
type : "GET",
url : "/system/userRole/listChecked.json",
data : {
userId : dataId
},
success : result => {
if(isRequestSuccess(result)) {
result.userId = dataId;
var roleTmpl = `
<% for(var i = 0, j = result.length; i < j ; i++) { %>
<tr>
<td><%=i+1%></td>
<td><%=result[i].name%></td>
<td><%=result[i].description%></td>
<td>
<label class="i-checks" id="is-show-checks">
<div class="icheckbox_square-green <%= result[i].checked ? "checked" : ''%>" style="position: relative;">
<input <%= result[i].checked ? 'checked=true' : ''%>" onchange="relation(this, '<%=result[i].id%>', '<%=userId%>')" class="role-icheck" type="checkbox" style="position: absolute; opacity: 0;">
<ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins>
</div>
</label>
</td>
</tr>
<% } %>
`;
$("#roles").html(template.compile(roleTmpl)(result));
} else {
handleRequestFail(result);
}
}
});
$("#relation-role-form").modal();
}
/**
* 关联角色和用户
* @param ele 触发事件的checkbox
* @param roleId 角色ID
* @param userId 用户ID
*/
function relation(ele, roleId, userId) {
$(ele).parent().toggleClass("checked");
if(ele.checked) {
ajaxRequest({
type : "post",
url : "/system/userRole/edit.json",
data : {
roleId : roleId,
userId : userId
}
});
} else {
ajaxRequest({
type : "post",
url : "/system/userRole/cancelRelation.json",
data : {
roleId : roleId,
userId : userId
}
});
}
}
/**
* 获得权限类型的含义
* @param value
* @returns {*}
*/
function meaningOfPermissionType(value) {
switch (parseInt(value)) {
case 1 :
return "模块";
case 2 :
return "菜单";
case 3 :
return "功能";
}
}
/**
* 添加模板,模态框
*/
function addFuncDiaglog(id) {
$("#id").val();
$("#edit-form #username").prop("disabled", false);
}
/**
* 编辑模板,模态框
*
* @param id 数据ID
*/
function editFuncDiaglog(entity) {
$("#edit-form #password").val("");
$("#edit-form #username").prop("disabled", true);
}
/**
* 删除模板,模态框
*
* @param id 数据ID
*/
function delFuncDiaglog(id) {
}
<file_sep>/admin/src/main/resources/static/js/system/role/pageSysRole.js
$(function () {
buildJqGridGenerator();
initValidate();
$('#nestable2').nestable();
});
function initValidate() {
$("#edit-form").validate({
errorPlacement: (error, element) => {
element.after(error);
},
rules: {
name : {
required : true,
maxlength : 100
},
role : {
required : true,
maxlength : 100
},
description : {
required : true,
maxlength : 300
}
},
messages : {
name : {
required : "必填",
maxlength : "最长100个字符"
},
role : {
required : "必填",
maxlength : "最长100个字符"
},
description : {
required : "必填",
maxlength : "最长300个字符"
}
},
submitHandler : form => {
$(form).ajaxSubmit({
success : result => {
if(200 == result.code) {
$(iJqGrid).trigger("reloadGrid");
$("#edit-modal-form").modal("hide");
} else {
alert(result.message);
}
}
});
}
});
}
function buildJqGridGenerator() {
return jqGridFactory.generate({
tableSelector : "#data-table-1",
pager : "pager-table-1",
url : "/system/role/list.json",
caption:"角色列表",
colNames : ["名称", "标识", "描述", "创建人","创建时间" ],
colModel : [
{
name : "name",
index : "name"
},
{
name : "role",
index : "role"
},
{
name : "description",
index : "description"
},
{
name : "creatorUserNickname",
index : "creatorUserNickname"
},
{
name : "createTime",
index : "createTime",
formatter : (cellValue, options, row) => {
return new Date(cellValue).format("yyyy-MM-dd hh:mm:ss");
},
searchoptions : {
dataInit : ele => {
DateTimePickerFactory.generate(ele);
}
}
}
]
}).navButtonAdd('#pager-table-1',{
caption : "",
title : "关联权限",
buttonicon : "ui-icon-shuffle",
onClickButton : listPermissions
});
}
/**
* 添加模板,模态框
*/
function addFuncDiaglog(id) {
$("#id").val();
}
/**
* 编辑模板,模态框
*
* @param id 数据ID
*/
function editFuncDiaglog(entity) {
}
/**
* 删除模板,模态框
*
* @param id 数据ID
*/
function delFuncDiaglog(id) {
}
/**
* 所有权限列表
*/
function listPermissions() {
var roleId = iJqGrid.jqGrid('getGridParam','selrow');
if(!roleId) {
alert("请选择需要关联权限的角色!");
return ;
}
$.ajax({
type : "GET",
url : "/system/rolePermission/listChecked.json",
data : {
roleId : roleId
},
success : result => {
if(isRequestSuccess(result)) {
result.roleId = roleId;
var permissionTmpl = `
<% for(var i = 0, j = result.length; i < j ; i++) { %>
<li class="dd-item dd-collapsed">
<button data-action="collapse" type="button" style="display: none;">Collapse</button>
<button data-action="expand" type="button">Expand</button>
<div class="dd-row">
<span class="pull-right">
<input <%=result[i].checked ? 'checked=true' : ''%> id="<%=result[i].id%>" class="permission-icheck" type="checkbox">
</span>
<span class="label label-info"><i class="fa <%=result[i].icon%>"></i></span> <%=result[i].name%>
</div>
<ol class="dd-list" style="display: none;" id="sub-of-<%=result[i].id%>">
<% for(var k = 0, l = result[i].subPermissions.length; k < l ; k++) { %>
<li class="dd-item dd-collapsed" id="1">
<button data-action="collapse" type="button" style="display: none;">Collapse</button>
<button data-action="expand" type="button">Expand</button>
<div class="dd-row">
<span class="pull-right">
<input <%=result[i].subPermissions[k].checked ? 'checked=true' : ''%> id="<%=result[i].subPermissions[k].id%>" data-parent-id="<%=result[i].id%>" class="permission-icheck" type="checkbox">
</span>
<span class="label label-info"><i class="fa <%=result[i].subPermissions[k].icon%>"></i></span> <%=result[i].subPermissions[k].name%>
</div>
<ol class="dd-list" style="display: none;" id="sub-of-<%=result[i].subPermissions[k].id%>">
<% for(var m = 0, n = result[i].subPermissions[k].subPermissions.length; m < n ; m++) { %>
<li class="dd-item" data-id="2">
<div class="dd-row">
<span class="pull-right">
<input id="<%=result[i].subPermissions[k].subPermissions[m].id%>" <%=result[i].subPermissions[k].subPermissions[m].checked ? 'checked=true' : ''%>" onchange="relation(this, '<%=roleId%>', '<%=result[i].subPermissions[k].subPermissions[m].id%>')" data-parent-id="<%=result[i].subPermissions[k].id%>" class="permission-icheck" type="checkbox">
</span>
<span class="label label-info"></span> <%=result[i].subPermissions[k].subPermissions[m].name%>
</div>
</li>
<% } %>
</ol>
</li>
<% } %>
</ol>
</li>
<% } %>
`;
// 检查子菜单是否被全选
$("#permissions").html(template.compile(permissionTmpl)(result));
bindIChecks(".permission-icheck").on("ifChecked ifUnchecked", event => {
relation(event.type, event.target, roleId);
});
} else {
handleRequestFail(result);
}
}
});
$("#relation-permission-form").modal();
}
/**
* 关联角色和权限
* 当所有子菜单被选中时,选择父菜单,
* 当有一个子菜单被取消选中时,取消选择父菜单
* @param eventType 事件类型
* @param ele 触发事件的checkbox
* @param roleId 角色ID
*/
function relation(eventType, ele, roleId) {
if(eventType == "ifChecked") {
ajaxRequest({
type : "post",
url : "/system/rolePermission/edit.json",
data : {
roleId : roleId,
permissionId : ele.id
},
success : result => {
// 找到当前元素的所有子权限全部全选
var subCheckbox = $("#sub-of-" + ele.id).find("input[data-parent-id=" + ele.id +"]");
if(subCheckbox.length > 0) {
subCheckbox.iCheck("check");
}
// 找到当前元素的父权限的所有子权限,如果该父权限下的所有子权限被选中,则勾选父权限
var parentId = $(ele).data("parent-id");
if(parentId) {
var parentCheckbox = $("#" + parentId);
if(!parentCheckbox.prop("checked")) {
var subCheckbox = $("#sub-of-" + parentId + " input[type=checkbox]"),
subCheckedCount = subCheckbox.length - subCheckbox.not(":checked").length;
if(subCheckedCount == subCheckbox.length) {
parentCheckbox.iCheck("check");
}
}
}
}
});
} else if (eventType == "ifUnchecked") {
ajaxRequest({
type : "post",
url : "/system/rolePermission/cancelRelation.json",
data : {
roleId : roleId,
permissionId : ele.id
},
success : result => {
// 找到当前元素的所有子权限,如果所有子权限被选中,则反选所有子权限
var subCheckbox = $("#sub-of-" + ele.id + " input[type=checkbox]"),
subCheckedCount = subCheckbox.length - subCheckbox.not(":checked").length;
if(subCheckedCount == subCheckbox.length) {
subCheckbox.iCheck("uncheck");
}
// 如果当前元素的父权限被选中,反选父权限
var parentId = $(ele).data("parent-id");
if(parentId) {
var parentCheckbox = $("#" + parentId);
if(parentCheckbox.prop("checked")) {
parentCheckbox.iCheck("uncheck");
}
}
}
});
}
}<file_sep>/admin/src/main/java/com/vanxd/admin/service/user/impl/SysUserServiceImpl.java
package com.vanxd.admin.service.user.impl;
import com.vanxd.admin.exception.BusinessException;
import com.vanxd.admin.service.BaseServiceImpl;
import com.vanxd.admin.service.user.SysUserService;
import com.vanxd.admin.shiro.authc.PasswordService;
import com.vanxd.data.entity.user.SysPermission;
import com.vanxd.data.entity.user.SysRolePermission;
import com.vanxd.data.entity.user.SysUser;
import com.vanxd.data.entity.user.SysUserRole;
import com.vanxd.data.mapper.user.SysPermissionMapper;
import com.vanxd.data.mapper.user.SysRolePermissionMapper;
import com.vanxd.data.mapper.user.SysUserMapper;
import com.vanxd.data.mapper.user.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by wyd on 2016/6/30.
*/
@Transactional
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUser, SysUserMapper> implements SysUserService {
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysUserRoleMapper sysUserRoleMapper;
@Autowired
private SysRolePermissionMapper sysRolePermissionMapper;
@Autowired
private PasswordService passwordService;
@Override
public SysUserMapper getMapper() {
return sysUserMapper;
}
public SysUser getByUsername(String username) {
return sysUserMapper.selectByUsername(username);
}
@Override
public int save(SysUser entity) {
entity.randomSalt();
encryptPassword(entity);
return super.save(entity);
}
@Override
public int updateByPrimaryKeySelective(SysUser entity) {
SysUser dbSysUser = sysUserMapper.selectByPrimaryKey(entity.getId());
if(null == dbSysUser) {
throw new BusinessException("用户不存在!");
}
entity.setSalt(dbSysUser.getSalt());
entity.setUsername(dbSysUser.getUsername());
encryptPassword(entity);
return super.updateByPrimaryKeySelective(entity);
}
@Override
public Set<String> getRoleIdentitiesByUserId(String userId) {
Set<String> rolesIdentities = new HashSet<String>();
SysUserRole userRoleConditions = new SysUserRole();
userRoleConditions.setUserId(userId);
List<SysUserRole> sysUserRoles = sysUserRoleMapper.page(userRoleConditions, null, null);
for(SysUserRole userRole : sysUserRoles) {
rolesIdentities.add(userRole.getRole());
}
return rolesIdentities;
}
@Override
public Set<String> getPermissionIdentitiesByUserId(String userId) {
Set<String> permissionIdentities = sysUserRoleMapper.selectPermissionsByUserId(userId);
return permissionIdentities;
}
/**
* 密码加密
* @param entity 用户对象
*/
private void encryptPassword(SysUser entity) {
try {
if(!StringUtils.isEmpty(entity.getPassword())) {
entity.setPassword(passwordService.encryptPassword(entity.getUsername(),entity.getPassword(), entity.getSalt()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/admin/src/main/java/com/vanxd/admin/start/MyBatisConfig.java
package com.vanxd.admin.start;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import javax.sql.DataSource;
/**
* MyBatis Java Configuration
* @author wyd on 2016/9/7.
*/
@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
/**
* 设置数据源
* todo 设置druid的其他属性
* @return
*/
@Bean( name = "dataSource", destroyMethod = "close")
public DataSource getDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername("root");
dataSource.setPassword("");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/helphim?useUnicode=true&characterEncoding=UTF-8");
return dataSource;
}
/**
* 配置sessionFactory,在其中扫描MyBatis 实体的包 和mapper XML文件
* @return
*/
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(getDataSource());
bean.setTypeAliasesPackage("com.vanxd.data.entity");
//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
//设置xml扫描路径
bean.setMapperLocations(resolver.getResources("classpath:/mybatis/mapper/*.xml"));
return bean.getObject();
} catch (Exception e) {
throw new RuntimeException("sqlSessionFactory init fail",e);
}
}
/**
* 事务管理,具体使用在service层加入@Transactional注解
*/
@Bean(name = "transactionManager")
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(getDataSource());
}
/**
* 扫描mapper 接口文件
* @return
*/
@Bean
public MapperScannerConfigurer getMapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.vanxd.data.mapper");
return mapperScannerConfigurer;
}
}
<file_sep>/admin/src/main/java/com/vanxd/admin/service/user/SysUserService.java
package com.vanxd.admin.service.user;
import com.vanxd.admin.service.BaseService;
import com.vanxd.data.entity.user.SysUser;
import com.vanxd.data.mapper.user.SysUserMapper;
import java.util.Set;
/**
* Created by wyd on 2016/8/25.
*/
public interface SysUserService extends BaseService<SysUser, SysUserMapper>{
/**
* 根据用户名获得用户数据
* @param username 用户名
* @return 用户对象
*/
SysUser getByUsername(String username);
/**
* 获得用户的所有权限识别码
* @param userId 用户ID
* @return set 权限识别码列表
*/
Set<String> getPermissionIdentitiesByUserId(String userId);
/**
* todo 改为一条sql
*
* 获得用户的所有角色识别码
*
* @param userId 用户ID
* @return set 角色识别码列表
*/
Set<String> getRoleIdentitiesByUserId(String userId);
}
| fb0152fd138305f2319e7882a2eccef85d512abb | [
"Markdown",
"SQL",
"Java",
"JavaScript"
]
| 7 | Markdown | 2892931976/HelpHim | 1a73b5f62b4f6a46eb323cb7df11df69288b2f5c | e0e8641b0f768d16bad0a6b08a4728745948834b |
refs/heads/master | <repo_name>kasselTrankos/functional-react-flux<file_sep>/app/vue/immutable/index.js
import { Map, List } from 'immutable';
//const state = Map({});
const state = List();
export default state;
<file_sep>/app/vue/index.js
import Vue from 'vue';
import actState from './components/myComponent.jsx';
import Home from './templates/home.vue';
import store from './store'
new Vue({
store,
el: '#app',
render: function (createElement) {
return createElement(Home)
}
});<file_sep>/app/js/base/validQuery.js
var validQueryObject = function (pattern, callback){
var _object = {}, _lexers = [];
var _startARR = '[', _endARR = ']', _startObj = '.';
function Lexer(){
for(var i=0;i<=pattern.length; i++){
Object(i); Array(i)
}
}
function valid(i){
Lexer();
var _o = _object;
for(var i=0;i<_lexers.length; i++){
_o = _o[pattern.slice(_lexers[i].start, _lexers[i].end)];
if(!_o) break;
}
return _o;
}
function Object(i){
if(pattern.charAt(i)===_startObj){
_lexers.push({
start: i+1,
end: -1
});
}
if(
_lexers.length>0 &&
pattern.charAt(_lexers.slice(-1)[0].start-1)===_startObj &&
(pattern.charAt(i)===_startARR || i === pattern.length)){
_lexers.slice(-1)[0].end = i;
return true;
}
return false;
}
function Array(i){
if(pattern.charAt(i)===_startARR){
_lexers.push({
start: i+1,
end: -1
});
}
if(pattern.charAt(i)===_endARR){
_lexers.slice(-1)[0].end = i;
return true;
}
return false;
}
function validate(obj){
var isValid = valid();
if(callback){
callback(isValid, obj)
}
return isValid
};
return function (obj){
_object = obj;
return validate(obj);
}
};
<file_sep>/transform.js
var browserify = require('browserify'),
babelify = require("babelify"),
fs = require('fs'),
watchify = require('watchify'),
path = require('path'),
source = require('vinyl-source-stream');
var _file = "app/js/immutable/bundle.js";
var b = browserify({
debug: true,
plugin: [watchify],
cache: {},
packageCache: {},
entries: ['app/immutable/index.js']
})
.transform(babelify.configure({
presets:['es2015']
}));
b.on('update', function(){
console.log('update it');
b.bundle().pipe(fs.createWriteStream(_file));
})
.bundle()
.pipe(fs.createWriteStream(_file));
<file_sep>/app/js/main.js
var element = document.getElementById('test');
var list = new List();
var _demosObject= [{
title: 'sion',
id: 12112,
children:[
{
title: 'amaris',
id: 99999,
ids:[1,3,4,5,6]
},
{
title: 'good',
id: 4
},
{
title:'glass',
id:2,
children:[
{
title: 'candy',
id:3
},
{
title:'miller',
id:4,
children:[
{
title: '<NAME>',
id: 5
},
{
title:'florence',
id: 6
},
{
title: 'philip',
id: 7,
children:[
{
title: 'lisp',
id: 8
}
]
}
]
}
]
}
]
}];
var isValid = validQueryObject('_demosObject[0].children[0].ids' )(_demosObject);
console.log('Without CALLBACK', isValid);
//console.log(isValid, '_demosObject[0].children[0].ids');
validQueryObject('_demosObject[0].children[0].status' ,function(founded, obj){
if(founded!==void(0)){
console.log(founded, 'callback done and FOUNDED');
}else{
console.log(founded, 'callback done and NOT FOUNDED');
}
})(_demosObject);
/////////////////from book,
/////dynamic scope
var stackBinder = list.stack(function(stack, v){
stack.push(v);
return stack;
});
stackBinder('a', 'content');
stackBinder('b', 'lo ves?');
var unStackBinder = list.stack(function(stack, v){
stack.pop();
return stack;
});
({f: function(){
//console.log(this);
return this;
}}).f.call('!');
function factorial (n) {
//console.log(n);
return !(n > 1) ? 1 : factorial(n - 1) * n;
}
////////////////////////////////////////////////////////////////////////////////
function iteration(map, compare){
///aqui necesito la function de i++ compare
var i=0, l=map.length;
return function(stack){
for (i; i<l;i++)
stack = compare(stack[map[i]]);
return stack;
}
}
/* var s = iteration(
pattern('0.1.1.2'), function(stack){
if(typeof(stack)=='undefined') return false;
return stack.children || stack;
}
)(_demosObject);
var t = iteration(
pattern('0.1'), function(stack){
return compare(stack);
}
)(_demosObject);
*/
function compare(stack){
console.log(stack, 444, 00)
if(typeof(stack)=='undefined') return false;
return stack.children || stack;
}
function pattern(str){
if(!/\./.test(str)) return [+str];
return str.split('.');
}
function compared(stack){
console.log(stack, 333);
if(typeof(stack)=='undefined') return false;
return stack.children || stack;
};
//console.log(s, 'at the result');
//console.log(t, 'on the other hand');
/////Trampolin
///no es complicado recibe la function encapsulada en contexto
//f, comprueba su tipo(fundamental en cualquier programacion)
/// y si es function entonces ejecuta, en otro caso retorna el valor informado
/// el avance que propone la web de readme es un array,
///que hace de pila
/////////////////////////////////////////////////////////
function trampoline(f) {
while (f && f instanceof Function) {
f = f();////es aqui cuando lo llama f()
}
return f;
}
//////y ahora lo voy a aplicar
//////impreeeeesionante tecnica.
/////parece mas light, y sencilla bastante
///// modelo abstracto de objeto
function deepAbstractSearch(stack, compare, next){
var founded =[];
function find(stack){
for(k in stack){
if(compare(stack[k])){
founded.push(stack[k]);
}
if(next(stack[k])){
trampoline(find.bind(null, stack[k]));
}
}
/////recupero los encontrados
return founded;
}
///pero solo se añade a trampoline 1 vez!!1,
///sin embargo esta por cada bind previo
return trampoline(find.bind(null, stack));
}
//aplico la solucion de busqueda.
/*var ss = deepSearch(_demosObject, function(o){
return (o.id===8);
}, function(o){return (o.children);});*/
<<<<<<< HEAD
}
}
});
=======
>>>>>>> immutable
// console.log(ss, ' jjajajja deep search nested!!!!');
$.get( '/demo/esprima.json', function( data ) {
console.log(data);
self.items = data;
var t = deepAbstractSearch(data, function(o){
console.log();
return (o && o.callee && o.callee.object && o.callee.object.name=='console' && o.arguments && o.arguments.length==2 && o.arguments[1].value=='is 9999999999999999');
},
function(o){
return (Object.prototype.toString.call(o) === '[object Array]' || Object.prototype.toString.call(o) === '[object Object]');
});
console.log(t, 'poppp');
});<file_sep>/app/vue/components/actState.jsx
import Vue from 'vue';
Vue.component('actState', {
render (h) {
return (<div class="row">
<ol class="breadcrumb col-md-4 col-md-offset-4">
<li class="active">{this.text}</li>
</ol>
</div>);
},
props:{
text: {
type: String,
required: true
}
}
});<file_sep>/app/js/base/base.js
var base = function(){
}
/**
Objeto List
uses __<name_function> to declare private methods;
uses __<name_property> to declare private properties.
*/
var List = function (){
__position = 0;
__object = {};
return {
get: get,
index: index,
next: next,
push: push,
pull:pull,
stack:stack,
jumper:jumper,
sinon:sinon
}
//__contructor(arguments);
function __contructor(){
console.log(arguments, 'load');
}
function get(){return __object;}
function __getNextKeyValue(){
}
function index(){
return _.size(__object) || __position;
}
function next(){
__position++;
return (__object.length<=__position)? __object[__position]: false;
}
function push(name, value){
__position++;
__object[name] = value;
return __object;
}
function pull(){
}
/**
Creacion de un scope dinámico
//stack==apilar
*/
function stack(resolve){
//primero le inyectamos el metodo(resolve)
//el cual devolvemos, como function predicativa que es!!
return function(k, v){
//si no existe se crea!!
//joder es la misma puerta logica.
//Si no existe lo crea. y devuelve
//crea u
var stack = __object[k] || [];
__object[k] = resolve(stack, v);
return __object;
}
}
/**
function que recorre internamente un array, ofreciendoles, los keys
integrando el arbol hacia el interior
*/
function jumper(resolve){
return function(k, arr){
var _return = resolve(k,arr[k].children) || false;
return _return;
}
}
function obten(){
}
/**
vamos por pasos.
Lo primero sinon, solo me hace falta para crear un metodo nomad
*/
function sinon(o, pattern, resolve){
__object = o;
__pattern = str;
__init = 0;
__seed = str.split('.');
console.log(__object, __pattern, '|| pattern', __init, '|| init');
return function(arr, k){
function iterator(arr){
return resolve(arr, __init);
}
__init++;
iterator(__object);
}
/*rerurn function(k, arr){
return resolve(k, arr);
}*/
}
}
<file_sep>/app/vue/reducers/actions.js
export const addState = text => {
return {
type: 'ADD_STATE',
text
}
}
<file_sep>/app/vue/store/mutations.js
import { Map, List } from 'immutable';
export const state = {
current: -1,
states: []
};
export const mutations = {
addState (state, texts) {
return state.states.push(Map({text: List(texts)}));
},
setState(state, current){
state.current = current;
}
}
<file_sep>/app/vue/reducers/index.js
import {combineReducers} from 'redux-immutable';
import todos from './todos.js'
const stateApp = combineReducers({todos});
export default stateApp;<file_sep>/app/vue/components/myComponent.jsx
import Vue from 'vue';
import actState from './actState.jsx';
import { mapMutations, mapGetters } from 'vuex'
Vue.component('myComponent', {
computed: {
...mapGetters({
state: 'getState',
states: 'getAllStates'
})
},
render (h) {
return (<div class="row">
{this.state.map((el)=>{
return (<act-state text={el}></act-state>);
})}
<div class="row">
<ol class="breadcrumb col-md-4 col-md-offset-4">
{ this.states.map((el, i)=>{
return (<li><a href={'#'+(i+1)} on-click={(e)=>this.resetState(i)}>{i+1}</a></li>);
})}
</ol>
</div>
<p class="col-md-4 col-md-offset-4 text-primary">{ this.vAkira }</p>
<div class="row">
<form class="col-md-4 col-md-offset-4" on-submit={(e) => this.onsubmit(e)}>
<div class="form-group">
<label for="myelm">{ this.iLabel }:</label>
<input type="text" class="form-control" on-input={(e) => this.sync('vAkira', e.target.value)} id="myelm" placeholder={ this.vAkira } />
</div>
</form>
</div>
</div>);
},
methods: {
... mapMutations([
'addState',
'setState'
]),
check() {
this.checked = !this.checked;
},
resetState(i){
this.setState(i);
this.addState(this.state);
},
sync (prop, value) {
this[prop] = value
},
onsubmit(e){
e.preventDefault();
this.state.push(this.vAkira);
this.addState(this.state);
this.vAkira = '';
document.getElementById('myelm').value = this.vAkira;
return false;
}
},
data () {
return {
vAkira: 'ddasddasdasd',
iLabel: 'Akira',
msg: 'Mi componente',
checked: true,
title: 'Check me'
};
}
});<file_sep>/es5.js
var fs = require("fs"),
vueify = require('vueify'),
babelify = require('babelify'),
watchify = require('watchify'),
browserify = require("browserify");
var _convert = [
///{in: 'app/vue/immutable/index.js' , out: 'app/js/immutable/bundle.js'},
{in: 'app/vue/index.js' , out: 'app/js/vue.js'},
];
for(var i=0; i<_convert.length; i++){
var b = browserify({
entries: [`${_convert[i].in}`],
cache: {},
debug: true,
packageCache: {},
plugin: [watchify]
})
.transform(vueify)
.transform(babelify, {presets: ["es2015"], plugins: ["transform-vue-jsx", "transform-object-rest-spread"]});
b.on('update', bundle)
.bundle()
.pipe(fs.createWriteStream(`${_convert[i].out}`));
console.log(`${_convert[i].in} created code at ${new Date().toISOString()}`);
}
function getFile(_file){
// if(_file.lastIndexOf('vue')){
return _convert[0].out;
// }
// if(_file.lastIndexOf('immutable')){
// return _convert[0].out;
// }
}
function bundle(ids){
var _file = getFile(ids);
console.log('updated code at '+new Date().toISOString(), _file);
b.bundle().pipe(fs.createWriteStream(_file));
}
<file_sep>/README.md
# functional Study
Case Study of programming functional with react and flux( will change :))
Me siento con ganas y estoy creando el objeto <List>, como ejercicio de programacion funcional.
Añadiendo Vue js como motor de render, server nativo con http-statics de node js.
Pendiente de implementar.
`node static_server.js`
desde http://127.0.0.1:9001
He añadido la librería de Vuex para uso del concepto Redux en Vuejs, y agrego el mantenimiento del Satate con immutable.
```javascript
var t = new LazyChain($scope)
.invoke('one', 90)
.invoke('two', $scope.value)
.invoke('toString')
.force();
```
Lazy load chaining, combine n functions, ideal para angular. Ya que actualiz el $scope, en cada invocación y then force.
Validación de Object by string en validQueryObject, retorna false si no existe, en caso de existir la posición pedida:
```javascript
var isValid = validQueryObject('_demosObject[0].children[0].ids')(_demosObject);
console.log(isValid, 9999);
return position of object or final value of object if is founded or false if is not exists.
```
```javascript
var result = iterator(pattern)(object);
```
recorre un object localizando los children, debo darle una vuelta para:
1. que el pattern, sea una function personal
2. que el filtro de busqueda tambien
```javascript
function pattern(){}
```
ahora inyecto la function de patron, la cual crea un array de mapa.
```javascript
function compare()
```
Me estaba complicando en exceso a la hora de reiniciar el object. En el bucle que recorre el patron se resetea con el compare. Este metodo es semi anonimo, en el return.
bien ahora estoy estudiando el punto de recursividad.
Encuentro las funciones trampoline, las cuales de una forma muy simple, evitando TCO ["tail call optimisation"](http://www.integralist.co.uk/posts/js-recursion.html)
consigo hacer busqueda en deep ( nested tree, vamos el que quiera, greaaat.)
```javascript
function deepSearch(stack, compare, next);
```
| 8256989aec848f571d69236dadb90f1622dfb91d | [
"JavaScript",
"Markdown"
]
| 13 | JavaScript | kasselTrankos/functional-react-flux | a9880e22a1df74e3956293fcc0b3b8d4ff0324b2 | b7151fbf3866c043d9e79cb2ccdf8c4ef8568a0f |
refs/heads/master | <file_sep>import {cardsDataArr} from './data.js';
import {LayoutController} from './controllers/layout.js';
import {BoardController} from './controllers/board.js';
const TASK_START_COUNT = 3;
const LOAD_MORE_TASK_COUNT = 8;
const mainContainer = document.querySelector(`main`);
const layoutController = new LayoutController(mainContainer);
layoutController.init();
// массив данных карточек для отрисовки (в нём нет архивных):
const cardsToRender = cardsDataArr.filter((t) => t.isArchive === false);
const boardController = new BoardController(mainContainer, cardsToRender, TASK_START_COUNT, LOAD_MORE_TASK_COUNT);
boardController.init();
<file_sep>import {shuffle} from '../utils.js';
const getTaskHashTagsHtml = (tags, count) => {
const tagsHtml = tags ? shuffle(Array.from(tags))
.slice(0, count)
.map((tag) => `
<span class="card__hashtag-inner">
<span class="card__hashtag-name">
#${tag}
</span>
</span>`
)
.join(``) : ``;
return `
<div class="card__hashtag">
<div class="card__hashtag-list">
${tagsHtml}
</div>
</div>`;
};
export {getTaskHashTagsHtml};
<file_sep>import {TaskController} from '../controllers/task.js';
import {BoardComponent} from '../components/board.js';
import {TaskListСomponent} from '../components/task_list.js';
import {SortComponent} from '../components/sorting.js';
import {completedMessage} from '../components/message_tasksCompleted.js';
import {LoadMoreButtonComponent} from '../components/loadmore_button';
import {render, unrender} from '../utils.js';
class BoardController {
/**
* @param {object} container - DOM-контейнер для вставки компонента
* @param {Array} tasks -массив данных по карточкам
* @param {number} firstTasksCount - число карточек для первоначального вывода на экран
* @param {number} loadMoreCount - число карточек для вывода при клике по loadMore
*/
constructor(container, tasks, firstTasksCount, loadMoreCount) {
this._container = container;
// весь массив данных:
this._allTasks = tasks;
this._board = new BoardComponent();
this._sort = new SortComponent();
this._taskList = new TaskListСomponent();
this._loadMoreButton = new LoadMoreButtonComponent();
this._count = firstTasksCount;
this._completedMessage = completedMessage;
this._loadMoreCount = loadMoreCount;
this._onChangeView = this._onChangeView.bind(this);
this._onDataChange = this._onDataChange.bind(this);
this._subscriptions = [];
}
init() {
render(this._container, this._board.getElement(), `beforeend`);
render(this._board.getElement(), this._sort.getElement(), `beforeend`);
render(this._board.getElement(), this._taskList.getElement(), `beforeend`);
this._renderFirstTaskCards();
}
// ------------
clearBoard() {
unrender(this._taskList.getElement());
this._taskList.removeElement();
}
_renderFirstTaskCards() {
// если не пуст, то рендерим, иначе показываем сообщение
if (this._allTasks.length) {
this._getTasksToRender();
this._renderTasksToBoard(this._tasks, this._count);
} else {
render(this._taskList.getElement(), this._completedMessage, `afterbegin`);
}
// кнопка LOAD-MORE
if (this._tasks.length) {
render(this._board.getElement(), this._loadMoreButton.getElement(), `beforeend`);
}
this._sort.getElement()
.addEventListener(`click`, (evt) => this._onSortLinkClick(evt));
this._loadMoreButton.getElement()
.addEventListener(`click`, (evt) => this._onLoadMoreButtonClick(evt));
}
_getTasksToRender() {
this._tasks = this._allTasks.slice();
}
_renderTask(task) {
const taskController = new TaskController(this._taskList.getElement(), task, this._onDataChange, this._onChangeView);
taskController.render();
this._subscriptions.push(taskController.setDefaultView.bind(taskController));
}
_onChangeView() {
this._subscriptions.forEach((it) => it());
}
_onDataChange(newData, oldData, oldController, container) {
// находим нужную и меняем данные
this._allTasks[this._tasks.findIndex((it) => it === oldData)] = newData;
// по новым данным новый контроллер:
const taskController = new TaskController(this._taskList.getElement(), newData, this._onDataChange, this._onChangeView);
// замена карточек:
container.replaceChild(taskController._task.getElement(), oldController._taskEdit.getElement());
oldController = null; // TODO: приведёт ли это действие к тому, что из памяти очистятся все старые компоненты?
}
/**
* @param {object[]} dataArr - cards Data
* @param {number} count - number of cards to render
*/
_renderTasksToBoard(dataArr, count) {
const realCount = (dataArr.length > count) ? count : dataArr.length;
for (let i = 0; i < realCount; i++) {
this._renderTask(dataArr.pop());
}
}
// ---------------- обработчик сортировки
_onSortLinkClick(evt) {
evt.preventDefault();
if (evt.target.tagName !== `A`) {
return;
}
this._taskList.getElement().innerHTML = ``;
switch (evt.target.dataset.sortType) {
case `date-up`:
this._tasks = this._allTasks.slice().sort((a, b) => a.dueDate - b.dueDate).reverse();
break;
case `date-down`:
this._tasks = this._allTasks.slice().sort((a, b) => b.dueDate - a.dueDate).reverse();
break;
case `default`:
this._tasks = this._allTasks.slice();
break;
}
this._renderTasksToBoard(this._tasks, this._count);
}
// --------------- обработчик кнопки LOAD MORE
_onLoadMoreButtonClick(evt) {
evt.preventDefault();
const renderMoreTasks = (data, count) => {
this._renderTasksToBoard(data, count);
if (data.length === 0) {
this._loadMoreButton.getElement()
.classList.add(`visually-hidden`);
return;
}
};
renderMoreTasks(this._tasks, this._loadMoreCount);
}
}
export {BoardController};
<file_sep>import {createElement} from '../utils.js';
const html = `
<p class="board__no-tasks">
Congratulations, all tasks were completed! To create a new click on
«add new task» button.
</p>`.trim();
const completedMessage = createElement(html);
export {completedMessage};
<file_sep>import {shuffle} from './utils.js';
const MAX_TASK_COUNT = 30; // просто для заполнения мок-массива
// генерирует данные для карточки задачи:
const getTaskData = () => ({
description: [
`Изучить теорию`,
`Сделать домашку`,
`Пройти интенсив на соточку`,
][Math.floor(Math.random() * 3)],
// Дата = плюс-минус неделя от текущей:
dueDate: Date.now() + (Math.floor(Math.random() * 15) - 7) * 24 * Math.round(Math.random() * 60) * Math.round(Math.random() * 60) * 1000,
repeatingDays: {
'mo': false,
'tu': Boolean(Math.round(Math.random())),
'we': false,
'th': Boolean(Math.round(Math.random())),
'fr': false,
'sa': Boolean(Math.round(Math.random())),
'su': false,
},
tags: new Set(shuffle([
`homework`,
`theory`,
`practice`,
`intensive`,
`keks`,
]).slice(0, Math.floor(Math.random() * 5))),
color: [
`black`,
`yellow`,
`blue`,
`green`,
`pink`,
][Math.floor(Math.random() * 5)],
isFavorite: Boolean(Math.round(Math.random())),
isArchive: Boolean(Math.round(Math.random())),
isDeadLine: Boolean(Math.round(Math.random())),
});
// данные для первой карточки с формой редактирования:
// const addCardDataArr = [{
// description: `This is example of new task, you can add picture, set date and time, add tags.`,
// color: `black`,
// isFavorite: true,
// isArchive: true,
// }];
// массив данных для всех карточек:
const cardsDataArr = new Array(Math.floor(3 + Math.random() * MAX_TASK_COUNT))
.fill(``)
.map(getTaskData);
// возвращает массив с данными для отрисовки фильтров
const getFiltersData = () => [
{title: `All`, isChecked: true, disabled: false, count: 13},
{title: `Overdue`, isChecked: false, disabled: true, count: 0},
{title: `Today`, isChecked: false, disabled: true, count: 0},
{title: `Favorites`, isChecked: false, disabled: false, count: 1},
{title: `Repeating`, isChecked: false, disabled: false, count: 1},
{title: `Tags`, isChecked: false, disabled: false, count: 1},
{title: `Archive`, isChecked: false, disabled: false, count: 115},
];
export {cardsDataArr, getFiltersData};
<file_sep>import {MenuComponent} from '../components/main_menu.js';
import {SearchBlockComponent} from '../components/search_block.js';
import {FiltersComponent} from '../components/main_filters.js';
import {getFiltersData} from './../data.js';
import {render} from './../utils.js';
class LayoutController {
constructor(container) {
this._container = container;
this._menu = new MenuComponent();
this._searchBlock = new SearchBlockComponent();
this._filters = new FiltersComponent(getFiltersData());
}
init() {
// меню
const menuContainer = document.querySelector(`.main__control.control.container`);
render(menuContainer, this._menu.getElement(), `beforeend`);
// блок поиска
render(this._container, this._searchBlock.getElement(), `beforeend`);
// фильтры
render(this._container, this._filters.getElement(), `beforeend`);
}
}
export {LayoutController};
<file_sep>import {TaskComponent} from '../components/task_card.js';
import {TaskEditComponent} from '../components/edit_task.js';
import {render} from '../utils.js';
import moment from 'moment';
class TaskController {
constructor(container, taskData, onDataChange, onChangeView) {
this._container = container;
this._taskData = taskData;
this._onDataChange = onDataChange;
this._onChangeView = onChangeView;
this._task = new TaskComponent(taskData);
this._taskEdit = new TaskEditComponent(taskData);
this.create();
}
create() {
// по нажатию на Esc меняем this._taskEdit на this._task
const onEscKeyDown = (evt) => {
if (evt.key === `Escape` || evt.key === `Esc`) {
this._container.replaceChild(this._task.getElement(), this._taskEdit.getElement());
document.removeEventListener(`keydown`, onEscKeyDown);
}
};
// обработчики на кнопку edit
this._task.getElement()
.querySelector(`.card__btn--edit`)
.addEventListener(`click`, () => {
// скрываю открытые карточки, если есть
this._onChangeView();
this._container.replaceChild(this._taskEdit.getElement(), this._task.getElement());
document.addEventListener(`keydown`, onEscKeyDown);
});
// если поле ввода в фокусе, то снимаем обработчик onEscKeyDown
this._taskEdit.getElement().querySelector(`textarea`)
.addEventListener(`focus`, () => {
document.removeEventListener(`keydown`, onEscKeyDown);
});
// не в фокусе, вешаем обратно
this._taskEdit.getElement().querySelector(`textarea`)
.addEventListener(`blur`, () => {
document.addEventListener(`keydown`, onEscKeyDown);
});
// обработчик SAVE: сохранение данных, замена карточки
this._taskEdit.getElement()
.querySelector(`.card__save`)
.addEventListener(`click`, (evt) => {
evt.preventDefault();
const formData = new FormData(this._taskEdit.getElement().querySelector(`.card__form`));
const entry = {
description: formData.get(`text`),
color: formData.get(`color`),
tags: new Set(formData.getAll(`hashtag`)),
dueDate: moment(formData.get(`date`)).toDate(),
repeatingDays: formData.getAll(`repeat`)
.reduce((acc, it) => {
acc[it] = true;
return acc;
}, {
'mo': false,
'tu': false,
'we': false,
'th': false,
'fr': false,
'sa': false,
'su': false,
}),
};
document.removeEventListener(`keydown`, onEscKeyDown);
// замена данных карточки
this._onDataChange(entry, this._data, this, this._container);
});
}
render() {
// рендерит карточку в контейнер
render(this._container, this._task.getElement(), `beforeend`);
}
// чтоб заменить открытую карточку при открытии следующей
setDefaultView() {
if (this._container.contains(this._taskEdit.getElement())) {
this._container.replaceChild(this._task.getElement(), this._taskEdit.getElement());
}
}
}
export {TaskController};
<file_sep>import {AbstractComponent} from './abstract-component.js';
import moment from 'moment';
class TaskComponent extends AbstractComponent {
constructor({description, dueDate, repeatingDays, tags, color, isFavorite, isArchive, isDeadLine} = {}) {
super();
this._description = description || ``;
this._dueDate = new Date(dueDate) || new Date(Date.now());
this._repeatingDays = repeatingDays;
this._tags = tags;
this._color = color || `black`;
this._isFavorite = isFavorite || false;
this._isArchive = isArchive || false;
this._isDeadLine = isDeadLine || false;
this._tagsMaxCount = 3; // по условию задания
}
// возвращает css-классы для карточки:
getArticleClasses() {
const cssClasses = [`card--${this._color}`];
if (Object.values(this._repeatingDays).some((d) => d)) {
cssClasses.push(`card--repeat`);
}
if (this._isDeadLine) {
cssClasses.push(`card-deadline`);
}
return cssClasses.join(` `);
}
// возвращает разметку хэштэгов
getTaskHashTagsHtml() {
const tagsHtml = Array.from(this._tags)
.slice(0, this._tagsMaxCount)
.map((tag) => `
<span class="card__hashtag-inner">
<span class="card__hashtag-name">
#${tag}
</span>
</span>`
)
.join(``);
return `
<div class="card__hashtag">
<div class="card__hashtag-list">
${tagsHtml}
</div>
</div>`;
}
get tagsMaxCount() {
return this._tagsMaxCount;
}
set tagsMaxCount(value) {
if (isNaN(value)) {
throw new Error(`непонятное кол-во хэштэгов: ${value}`);
}
this._tagsMaxCount = parseInt(value, 10);
}
// возвращает разметку для карточки
getTemplate() {
return `
<article class="card ${ this.getArticleClasses()}">
<div class="card__form">
<div class="card__inner">
<div class="card__control">
<button
type="button"
class="card__btn card__btn--edit">
edit
</button>
<button
type="button"
class="card__btn ${this._isArchive ? `card__btn--archive` : ``}">
archive
</button>
<button
type="button"
class="card__btn ${this._isFavorite ? `card__btn--favorites` : ``} card__btn--disabled"
>
favorites
</button>
</div>
<div class="card__color-bar">
<svg class="card__color-bar-wave" width="100%" height="10">
<use xlink:href="#wave"></use>
</svg>
</div>
<div class="card__textarea-wrap">
<p class="card__text">${this._description}</p>
</div>
<div class="card__settings">
<div class="card__details">
<div class="card__dates">
<div class="card__date-deadline">
<p class="card__input-deadline-wrap">
<span class="card__date">
${moment(this._dueDate).format(`DD MMMM`)}
</span>
<span class="card__time">
${moment(this._dueDate).format(`hh:mm A`)}
</span>
</p>
</div>
</div>
${this.getTaskHashTagsHtml()}
</div>
</div>
</div>
</div>
</article>`.trim();
}
}
export {TaskComponent};
<file_sep>import {AbstractComponent} from './abstract-component.js';
import '../../node_modules/flatpickr/dist/themes/light.css';
import flatpickr from 'flatpickr';
import moment from 'moment';
class TaskEditComponent extends AbstractComponent {
constructor({description, dueDate, repeatingDays, tags, color, isFavorite, isArchive, isDeadLine} = {}) {
super();
this._description = description || ``;
this._dueDate = new Date(dueDate) || new Date(Date.now());
this._repeatingDays = repeatingDays;
this._tags = tags;
this._color = color || `black`;
this._isFavorite = isFavorite || false;
this._isArchive = isArchive || false;
this._isDeadLine = isDeadLine || false;
this._isRepeat = Object.values(this._repeatingDays).some((d) => d) || false;
this._tagsMaxCount = 3; // по условию задания
this._subscribeOnEvents();
this._checkRepeatStatus();
}
static getPossibleColor() {
return [`black`, `yellow`, `blue`, `green`, `pink`];
}
// возвращает css-классы для карточки:
getArticleClasses() {
const cssClasses = [`card--${this._color}`];
if (this._isRepeat) {
cssClasses.push(`card--repeat`);
}
if (this._isDeadLine) {
cssClasses.push(`card-deadline`);
}
return cssClasses.join(` `);
}
getTaskRepeatingDaysHtml() {
return Object.keys(this._repeatingDays)
.map((day) => `
<input
class="visually-hidden card__repeat-day-input"
type="checkbox"
id="repeat-${day}-4"
name="repeat"
value="${day}"
${this._repeatingDays[day] ? `checked` : ``}
/>
<label class="card__repeat-day" for="repeat-${day}-4"
>${day}</label
>`).join(``);
}
_getTagHtml(tag) {
return `
<span class="card__hashtag-inner">
<input
type="hidden"
name="hashtag"
value="${tag}"
class="card__hashtag-hidden-input"
/>
<p class="card__hashtag-name">
#${tag}
</p>
<button type="button" class="card__hashtag-delete">
delete
</button>
</span>`.trim();
}
getTaskTagsHtml() {
return Array.from(this._tags)
.map((tag) => (this._getTagHtml(tag))).join(``);
}
getColorsListHtml() {
return TaskEditComponent.getPossibleColor().map((color) => `
<input
type="radio"
id="color-${color}-4"
class="card__color-input card__color-input--${color} visually-hidden"
name="color"
value="${color}"
${(color === this._color) ? `checked` : ``}
/>
<label
for="color-${color}-4"
class="card__color card__color--${color}"
>yellow</label
>`).join(``);
}
getTemplate() {
return `
<article class="card card--edit ${this.getArticleClasses()}">
<form class="card__form" method="get">
<div class="card__inner">
<div class="card__control">
<button type="button" class="card__btn card__btn--archive">
archive
</button>
<button
type="button"
class="card__btn card__btn--favorites card__btn--disabled"
>
favorites
</button>
</div>
<div class="card__color-bar">
<svg class="card__color-bar-wave" width="100%" height="10">
<use xlink:href="#wave"></use>
</svg>
</div>
<div class="card__textarea-wrap">
<label>
<textarea
class="card__text"
placeholder="Start typing your text here..."
name="text"
>${this._description}</textarea>
</label>
</div>
<div class="card__settings">
<div class="card__details">
<div class="card__dates">
<button class="card__date-deadline-toggle" type="button">
date:
<span class="card__date-status">
${this._dueDate ? `yes` : `no`}
</span>
</button>
<fieldset class="card__date-deadline">
<label class="card__input-deadline-wrap">
<input
class="card__date ${this._dueDate ? `` : `visually-hidden`}"
type="text"
placeholder=""
name="date"
value="${moment(this._dueDate).format(`DD MMMM hh:mm A`)}"
/>
</label>
</fieldset>
<button class="card__repeat-toggle" type="button">
repeat:
<span class="card__repeat-status">
${this._isRepeat ? `yes` : `no`}
</span>
</button>
<fieldset class="card__repeat-days">
<div class="card__repeat-days-inner">
${this.getTaskRepeatingDaysHtml()}
</div>
</fieldset>
</div>
<div class="card__hashtag">
<div class="card__hashtag-list">
${this.getTaskTagsHtml()}
</div>
<label>
<input
type="text"
class="card__hashtag-input"
name="hashtag-input"
placeholder="Type new hashtag here"
/>
</label>
</div>
</div>
<div class="card__colors-inner">
<h3 class="card__colors-title">Color</h3>
<div class="card__colors-wrap">
${this.getColorsListHtml()}
</div>
</div>
</div>
<div class="card__status-btns">
<button class="card__save" type="submit">save</button>
<button class="card__delete" type="button">delete</button>
</div>
</div>
</form>
</article>`.trim();
}
_checkRepeatStatus() {
const repeatStatus = this.getElement().querySelector(`.card__repeat-status`);
const repeatDaysInner = this.getElement().querySelector(`.card__repeat-days-inner`);
const repeatDaysInputs = this.getElement().querySelectorAll(`.card__repeat-day-input`);
const daykeys = Object.keys(this._repeatingDays);
if (this.getElement().classList.contains(`card--repeat`)) {
repeatStatus.textContent = `yes`;
repeatDaysInner.classList.remove(`visually-hidden`);
} else {
repeatStatus.textContent = `no`;
daykeys.forEach((day) => {
this._repeatingDays[day] = false;
});
repeatDaysInputs.forEach((input) => {
input.checked = false;
});
repeatDaysInner.classList.add(`visually-hidden`);
}
}
_checkDateStatus() {
const dateStatus = this.getElement().querySelector(`.card__date-status`);
const dateInput = this.getElement().querySelector(`.card__date`);
switch (dateInput.classList.contains(`visually-hidden`)) {
case true:
dateStatus.textContent = `no`;
dateInput.value = ``;
break;
case false:
dateStatus.textContent = `yes`;
break;
}
}
_subscribeOnEvents() {
flatpickr(this.getElement().querySelector(`.card__date`), {
altInput: true,
altFormat: `j F h:i K`,
allowInput: true,
enableTime: true,
// eslint-disable-next-line camelcase
time_24hr: true,
defaultDate: this._dueDate,
dateFormat: `Y-m-d H:i`,
});
// обработчик на новый хэштэг
this.getElement()
.querySelector(`.card__hashtag-input`).addEventListener(`keydown`, (evt) => {
if (evt.key === `Enter`) {
evt.preventDefault();
this.getElement()
.querySelector(`.card__hashtag-list`)
.insertAdjacentHTML(`beforeEnd`, this._getTagHtml(evt.target.value));
evt.target.value = ``;
}
});
// обработчик на удаление хэштэга
this.getElement().addEventListener(`click`, (evt) => {
if (!evt.target.classList.contains(`card__hashtag-delete`)) {
return;
}
evt.target.closest(`.card__hashtag-inner`).remove();
});
// обработчик клика на repeat
const repeatStatusToggle = this.getElement().querySelector(`.card__repeat-toggle`);
repeatStatusToggle.addEventListener(`click`, () => {
this.getElement().classList.toggle(`card--repeat`);
this._checkRepeatStatus();
});
// TODO: не пойму почему этот обработчик 2 раза срабатывает при одном клике?
const repeatDaysInner = this.getElement().querySelector(`.card__repeat-days-inner`);
repeatDaysInner.addEventListener(`click`, () => {
const days = Array.from(this.getElement().querySelectorAll(`.card__repeat-day-input`));
if (days.some((it) => it.checked === true)) {
this.getElement().classList.add(`card--repeat`);
} else {
this.getElement().classList.remove(`card--repeat`);
}
this._checkRepeatStatus();
});
// обработчик клика на DATE
const dateButton = this.getElement().querySelector(`.card__date-deadline-toggle`);
const dateInput = this.getElement().querySelector(`.card__date`);
dateButton.addEventListener(`click`, () => {
dateInput.classList.toggle(`visually-hidden`);
this._checkDateStatus();
});
// обработчик выбора цвета
this.getElement().querySelector(`.card__colors-wrap`).addEventListener(`click`, (evt) => {
if (!evt.target.classList.contains(`card__color-input`)) {
return;
}
this.getElement().classList.remove(`card--${this._color}`);
this._color = evt.target.value;
this.getElement().classList.add(`card--${evt.target.value}`);
});
}
}
export {TaskEditComponent};
<file_sep>const Position = {
AFTERBEGIN: `afterbegin`,
BEFOREEND: `beforeend`
};
// возвращает элемент созданный на основе разметки из template
const createElement = (template) => {
const newElement = document.createElement(`div`);
newElement.insertAdjacentHTML(`afterbegin`, template);
return newElement.firstChild;
};
// Рендер и анрендер для компонент
const render = (container, element, place) => {
switch (place) {
case Position.AFTERBEGIN:
container.prepend(element);
break;
case Position.BEFOREEND:
container.append(element);
break;
}
};
const unrender = (element) => {
if (element) {
element.remove();
}
};
// генерирует разметку используя ф-ию getHtmlforElement на каждом эл-те массива dataList
const getHtml = (dataList, getHtmlforElement) =>
dataList.map(getHtmlforElement).join(`\n`);
// перемешивает массив
const shuffle = (arr) => {
let j; let temp;
for (let i = arr.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
return arr;
};
export {shuffle, getHtml, createElement, render, unrender};
<file_sep>import {getHtml} from '../utils.js';
import {AbstractComponent} from './abstract-component.js';
class FiltersComponent extends AbstractComponent {
constructor(filtersList) {
super();
this._filtersList = filtersList;
}
static getFilterHtml({title = ``, isChecked = false, isDisabled = false, count} = {}) {
const id = title ? title.toLowerCase() : `title`;
return `
<input
type="radio"
id="filter__${id}"
class="filter__input visually-hidden"
name="filter"
${isChecked ? `checked` : ``}
${isDisabled ? `disabled` : ``}
/>
<label for="filter__${id}" class="filter__label">
${id} <span class="filter__${id}-count">${count ? count : ``}</span>
</label>`.trim();
}
getTemplate() {
return `
<section class="main__filter filter container">
${getHtml(this._filtersList, FiltersComponent.getFilterHtml)}
</section>`.trim();
}
}
export {FiltersComponent};
| 10bebec7de2c4b125f0cd63cfc60ed9601a51582 | [
"JavaScript"
]
| 11 | JavaScript | RylkovAlex/859429-taskmanager-9 | 5ddae047bc79a65d1d068935f4805d8999a27958 | bc6bdc9fc56a034fa99fe9a56d53de72e8932869 |
refs/heads/main | <repo_name>naitax/solution_c<file_sep>/datatext.py
import json
a_file = open("convert_to_txt.txt", "r")
yourResult = [line.split(',') for line in a_file.readlines()]
print(json.dumps(yourResult))
#converts text from txt file to json dictonary
<file_sep>/solution.py
''' Testing #1
test = {
'viewonly': [1, 2, 3, 4, 5, 6, 7],
'admin': [4, 5, 6, 111, 23, 45]
}
s = input()
numbers = set(map(int, s.split()))
l = len(test)
x = []
new_set_roles = []
keys = []
dicts = {}
new_set_roles = list(test.keys())
new_dicts = []
for i in range(l):
new_set = numbers.intersection(set(list(test.values())[i]))
x.append(new_set)
k = len(new_set)
keys.append(k)
dicts[keys[i]] = x[i]
#new_dicts[new_set_roles[i]] = dicts[i]
print(new_set_roles)
#print(dicts)
# print maximum value
#maximum = max(dicts, key=dicts.get) # Just use 'min' instead of 'max' for minimum.
#print(maximum, dicts[maximum])
print(dicts)
dicts_sorted_keys = sorted(dicts, key=dicts.get, reverse=True)
for r in dicts_sorted_keys:
print('Number of corresponding programs: {}, list of programs: {}'.format(r, dicts[r]))
#print(test.values())
'''
#################################################################
import json
with open('data.json') as json_file:
test = json.load(json_file)
s = input('Please enter names of programs you need to have access to: ').upper()
numbers = set(map(str, s.split()))
l = len(test)
x = []
new_set_roles = []
keys = []
dicts = {}
new_set_roles = list(test.keys())
new_dicts = []
for i in range(l):
new_set = numbers.intersection(set(list(test.values())[i]))
x.append(new_set)
k = new_set_roles[i]
keys.append(k)
dicts[keys[i]] = x[i]
dicts_sorted_keys = sorted(dicts, key=dicts.get, reverse=True)
for r in dicts_sorted_keys:
if len(dicts[r]) == 0:
continue
print('Role: {}, number of programs: {}/{}, list of corresponding programs: {}, total list of programs: {}'.format(r.upper(), len(dicts[r]), len(numbers), dicts[r], len(test[r])))
| 054e5e389fad84b216d6c315b5531ab84a32778f | [
"Python"
]
| 2 | Python | naitax/solution_c | 6691485a5d5401ee8b9e4067562e3ad160ad151e | 30f856f661b6117fa917f404a2161a02cfd70af3 |
refs/heads/master | <repo_name>DongyeolLee/JspWithServlet<file_sep>/src/main/java/com/edu/test/FirstAnotherServlet.java
package com.edu.test;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
@WebServlet("/hello2")
public class FirstAnotherServlet extends HttpServlet {
private static final long serialVersionUID = 4383965599350483058L;
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("Init()-2 method is called");
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("Service()-2 method is called");
}
}
<file_sep>/src/main/java/com/edu/test/FirstServlet.java
package com.edu.test;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = -4565570147942702873L;
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("Init() method is called");
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("Service() method is called");
}
}
| d880fca2f1dbe5439e1e30f5bc3c90fbdbbfb869 | [
"Java"
]
| 2 | Java | DongyeolLee/JspWithServlet | 0dfff26c40be7188955a2662c6bc15df2ab679f1 | 2af7435adcef42e15cd129f66d61c6bad291325a |
refs/heads/main | <file_sep>print("Hello World This is my First code")
| b10d8017982f06cddc2569d2402c68087e704fa9 | [
"Python"
]
| 1 | Python | MitCodes/py_beginners | 11bcfb38ba11d4eec15bcb2ab46d2a8e44f5a77e | 0bb4b1c39b65f49cd53697b189f7028cc9a37630 |
refs/heads/master | <repo_name>VGoose/CrappyCurry<file_sep>/curry.js
/**
* Transforms a function to a one-step partially applied function. Subsequent call to the
* returned function will always invoke it.
*
* @param {function} fn function to be Curried
*
* @param {any} args any additional arguments supplied will be captured and be
* partially applied or applied to fn
*
* @returns {function or any} either returns a partially applied function or return value
* of fn
*/
var curry = function (fn) {
if(typeof fn !== 'function') {
throw new Error('First argument must be a function');
}
var arity = fn.length;
var args = Array.prototype.slice.call(arguments, 1);
var remainingArgs = arity - args.length;
if (remainingArgs <= 0) {
return fn.apply(null, args);
}else if (remainingArgs > 0) {
return function() {
var new_args = Array.prototype.slice.call(arguments);
args = args.concat(new_args);
return fn.apply(null, args);
}
}
}
module.exports = curry; | 6efdb1692366524ee281332c2be08fb7115a28d9 | [
"JavaScript"
]
| 1 | JavaScript | VGoose/CrappyCurry | d65f5489673b643240707321043dd8d231549cdd | d0af29d3bb5b396215d2551eeb0659aba8f2e7a7 |
refs/heads/master | <repo_name>grglzrv/vagrant-k8s-cluster<file_sep>/bootstrap.sh
#!/usr/bin/env bash
# Install Python for running Ansible
sudo apt-get update -qq && \
sudo apt-get install -qq -y python-minimal htop
<file_sep>/deploy_cluster.sh
#!/usr/bin/env bash
echo -e "Creating VM's for K8s cluster"
vagrant up
echo -e "Installing Ansible dependencies"
ansible-galaxy install -r requirements.yml
echo -e "Wait a bit before deploying K8s"
sleep 30
echo -e "Deploying K8s"
ansible-playbook -i inventory/k8s-cluster playbook.yml
<file_sep>/README.md
# Vagrant Kubernetes cluster
This project will allow you to create a VM k8s cluster using Virtualbox and Vagrant.
## VM Definition
To add new VM's to the cluster, you only need to create a new definition in the clusters section:
```javascript
# Cluster definition
clusters = [
{
:prefix => "k8s-master",
:domain => "local.net",
:box => "ubuntu/bionic64",
:nodes => 1,
:cpu => 2,
:mem => 2048,
:publan => IPAddr.new("192.168.33.0/24"),
:publan_start => 130
},
{
:prefix => "k8s-node",
:domain => "local.net",
:box => "ubuntu/bionic64",
:nodes => 2,
:cpu => 2,
:mem => 2048,
:publan => IPAddr.new("192.168.33.0/24"),
:publan_start => 140
}
]
```
And then run `vagrant up --provision` in order to create the new nodes and provision them with python.
## Install Kubernetes (latest)
Execute the file `deploy_cluster.sh`:
```bash
$ ./deploy_cluster.sh
```
## TODO
Compatibility with CentOS.
| 0fff80e3592c29c8d179ff4f4f61915023c117ae | [
"Markdown",
"Shell"
]
| 3 | Shell | grglzrv/vagrant-k8s-cluster | 794155f539329fe5b9f6747ceab2b67ca26d3e4c | a96675f4a0dcff9db4f37b0a89f74c7f322bd372 |
refs/heads/main | <repo_name>evanGunning/VChat<file_sep>/src/Router.js
import { BrowserRouter, Switch, Route } from 'react-router-dom'
import SignIn from './Register_Login/SignIn'
import Landing from './Landing'
import Register from './Register_Login/Register'
function Router() {
return (
<BrowserRouter>
<Switch>
<Route path="/" exact>
<SignIn />
</Route>
<Route path="/userlanding">
<Landing />
</Route>
<Route path="/register">
<Register />
</Route>
</Switch>
</BrowserRouter>
)
}
export default Router
| e30e5b0503ec8d46c0fb3393d76a60593d0b9a11 | [
"JavaScript"
]
| 1 | JavaScript | evanGunning/VChat | c874bebf09d421ecdd11099f35f87dc8dfa45664 | 69b8b526723e41207e0280c9559c61d30debe4c7 |
refs/heads/master | <file_sep>package jinhaoxia.handler.ready.util;
import com.google.common.collect.Lists;
import jinhaoxia.handler.ready.model.request.HttpRequest;
import jinhaoxia.handler.ready.model.request.HttpRequestHandler;
import jinhaoxia.support.pattern.Group;
import jinhaoxia.support.pattern.Transaction;
import java.util.*;
import java.util.stream.Collectors;
/**
* 把所有信息都整合成 一个 Item Set
*/
public class HttpRequestItemSetEncoder implements IHttpRequestEncoder {
// name type key value
private static final Integer TYPE_METHOD = 1;//int //0 Integer
private static final Integer TYPE_SCHEME = 2;//int //0 String
private static final Integer TYPE_PORT = 3;//int //0 Integer
private static final Integer TYPE_AUTHORITY = 4;//int //Integer String
private static final Integer TYPE_PATH = 5;//int //Integer String
private static final Integer TYPE_QUERY_STRING = 6;//int //String String
private static class Meta {
public Comparable type;
public Comparable key;
public Comparable value;
public Meta(Comparable type, Comparable key, Comparable value) {
this.type = type;
this.key = key;
this.value = value;
}
}
private static final Comparator<Meta> META_COMPARATOR = new Comparator<Meta>() {
@Override
public int compare(Meta o1, Meta o2) {
int cmp;
cmp = o1.type.compareTo(o2.type);
if (cmp != 0) return cmp;
cmp = o1.key.compareTo(o2.key);
if (cmp != 0) return cmp;
if (o1.value == o2.value) return 0;
if (o1.value == null) return -1;
if (o2.value == null) return 1;
return o1.value.compareTo(o2.value);
}
};
private SortedMap<Meta, Integer> dict = new TreeMap<>(META_COMPARATOR);
private SortedMap<Integer, Meta> reversedDict = new TreeMap<>();
public HttpRequestItemSetEncoder() {
}
@Override
public Transaction encode(HttpRequest req) {
Group grp = new Group();
int size = 3 * 2;
size += req.getAuthoritySegments().size() * 2;
size += req.getPathSegments().size() * 2;
size += req.getQueryStringMapping().size() * 2;
grp.type = Group.TYPE_ITEM_SET;
grp.array = new int[size];
// 处理基本信息
{
grp.array[0] = lookupOrUpdate(new Meta(TYPE_METHOD, 0, null));
grp.array[1] = lookupOrUpdate(new Meta(TYPE_METHOD, 0, req.getMethod()));
grp.array[2] = lookupOrUpdate(new Meta(TYPE_SCHEME, 0, null));
grp.array[3] = lookupOrUpdate(new Meta(TYPE_SCHEME, 0, req.getScheme()));
grp.array[4] = lookupOrUpdate(new Meta(TYPE_PORT, 0, null));
grp.array[5] = lookupOrUpdate(new Meta(TYPE_PORT, 0, req.getPort()));
}
int c = 6;
// 处理域名信息
{
int n = req.getAuthoritySegments().size();
for (int i = 0; i < n; i++) {
grp.array[c++] = lookupOrUpdate(new Meta(TYPE_AUTHORITY, n - i, null));
grp.array[c++] = lookupOrUpdate(new Meta(TYPE_AUTHORITY, n - i, req.getAuthoritySegments().get(i)));
}
}
// 处理路径信息
{
int n = req.getPathSegments().size();
for (int i = 0; i < n; i++) {
grp.array[c++] = lookupOrUpdate(new Meta(TYPE_PATH, i + 1, null));
grp.array[c++] = lookupOrUpdate(new Meta(TYPE_PATH, i + 1, req.getPathSegments().get(i)));
}
}
// 处理查询部分
{
for (String key : req.getQueryStringMapping().keySet()) {
grp.array[c++] = lookupOrUpdate(new Meta(TYPE_QUERY_STRING, key, null));
grp.array[c++] = lookupOrUpdate(new Meta(TYPE_QUERY_STRING, key, req.getQueryStringMapping().get(key)));
}
}
Arrays.sort(grp.array);
Transaction tran = new Transaction();
tran.add(grp);
return tran;
}
private Integer lookupOrUpdate(Meta meta) {
if (!dict.containsKey(meta)) {
dict.put(meta, dict.size() + 1);
reversedDict.put(dict.size(), meta);
}
return dict.get(meta);
}
@Override
public void prepare(Iterable<HttpRequest> requests) {
dict.clear();
reversedDict.clear();
for (HttpRequest req : requests) {
// 处理简单信息
{
lookupOrUpdate(new Meta(TYPE_METHOD, 0, null));
lookupOrUpdate(new Meta(TYPE_METHOD, 0, req.getMethod()));
lookupOrUpdate(new Meta(TYPE_SCHEME, 0, null));
lookupOrUpdate(new Meta(TYPE_SCHEME, 0, req.getScheme()));
lookupOrUpdate(new Meta(TYPE_PORT, 0, null));
lookupOrUpdate(new Meta(TYPE_PORT, 0, req.getPort()));
}
// 处理域名部分
{
int n = req.getAuthoritySegments().size();
for (int i = 0; i < n; i++) {
lookupOrUpdate(new Meta(TYPE_AUTHORITY, n - i, null));
lookupOrUpdate(new Meta(TYPE_AUTHORITY, n - i, req.getAuthoritySegments().get(i)));
}
}
// 处理路径部分
{
int n = req.getPathSegments().size();
for (int i = 0; i < n; i++) {
lookupOrUpdate(new Meta(TYPE_PATH, i + 1, null));
lookupOrUpdate(new Meta(TYPE_PATH, i + 1, req.getPathSegments().get(i)));
}
}
// 处理查询部分
{
for (String key : req.getQueryStringMapping().keySet()) {
lookupOrUpdate(new Meta(TYPE_QUERY_STRING, key, null));
lookupOrUpdate(new Meta(TYPE_QUERY_STRING, key, req.getQueryStringMapping().get(key)));
}
}
}
}
@Override
public HttpRequestHandler decode(Transaction tran) {
Integer method = null;
String scheme = null;
Integer port = null;
SortedMap<Integer, String> auth = new TreeMap<>();
SortedMap<Integer, String> path = new TreeMap<>();
SortedMap<String, String> qs = new TreeMap<>();
for (int x : tran.headGroup().array) {
Meta meta = reversedDict.get(x);
if (meta.type == TYPE_METHOD) {
if (method == null) method = (Integer) meta.value;
} else if (meta.type == TYPE_SCHEME) {
if (scheme == null) scheme = (String) meta.value;
} else if (meta.type == TYPE_PORT) {
if (port == null) port = (Integer) meta.value;
} else if (meta.type == TYPE_AUTHORITY) {
if (auth.get(meta.key) == null) auth.put((Integer) meta.key, (String) meta.value);
} else if (meta.type == TYPE_PATH) {
if (path.get(meta.key) == null) path.put((Integer) meta.key, (String) meta.value);
} else if (meta.type == TYPE_QUERY_STRING) {
if (qs.get(meta.key) == null) qs.put((String) meta.key, (String) meta.value);
} else {
assert false;
return null;
}
}
List<String> authSegments = Lists.reverse(auth.keySet().stream().map(auth::get).collect(Collectors.toList()));
List<String> pathSegments = path.keySet().stream().map(path::get).collect(Collectors.toList());
return new HttpRequestHandler(method, scheme, port, authSegments, pathSegments, qs);
}
}
<file_sep>package jinhaoxia.handler.ready.model.request;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public
class Support {
private HttpRequestHandler handler;
private List<HttpRequest> requests;
public Support(HttpRequestHandler handler) {
this.handler = handler;
this.requests = new ArrayList<>();
}
public HttpRequestHandler getHandler() {
return handler;
}
public List<HttpRequest> getRequests() {
return requests;
}
public void reOrderRequests() {
Collections.shuffle(requests, new Random(0));
}
}
<file_sep>package jinhaoxia.handler.ready.util;
import com.google.common.collect.Lists;
import jinhaoxia.handler.ready.model.request.HttpRequest;
import jinhaoxia.handler.ready.model.request.HttpRequestHandler;
import jinhaoxia.support.pattern.Group;
import jinhaoxia.support.pattern.Transaction;
import java.util.*;
import java.util.stream.Collectors;
public class HttpRequestEncoder implements IHttpRequestEncoder {
private class Meta {
public static final int PART_PROT = 1;
public static final int PART_AUTH = 2;
public static final int PART_PATH = 3;
public static final int PART_QSMD = 4;
Comparable part;
Comparable key;
Comparable value;
public Meta(Comparable part, Comparable key, Comparable value) {
this.part = part;
this.key = key;
this.value = value;
}
}
private Map<Meta, Integer> dict = new TreeMap<>(new Comparator<Meta>() {
@Override
public int compare(Meta o1, Meta o2) {
int cmp;
cmp = o1.part.compareTo(o2.part);
if (cmp != 0) return cmp;
cmp = o1.key.compareTo(o2.key);
if (cmp != 0) return cmp;
if (o1.value == o2.value) return 0;
if (o1.value == null) return -1;
if (o2.value == null) return 1;
return o1.value.compareTo(o2.value);
}
});
private Map<Integer, Meta> reverseDict = new TreeMap<>();
private static final int KEY_FOR_METHOD = 1;
private static final int KEY_FOR_SCHEME = 2;
private static final int KEY_FOR_PORT = 3;
private SortedSet<String> qsKeys = new TreeSet<>();
@Override
public Transaction encode(HttpRequest req) {
int[] info = new int[]{
dict.get(new Meta(Meta.PART_PROT, KEY_FOR_METHOD, req.getMethod())),
dict.get(new Meta(Meta.PART_PROT, KEY_FOR_SCHEME, req.getScheme())),
dict.get(new Meta(Meta.PART_PROT, KEY_FOR_PORT, req.getPort()))
};
Arrays.sort(info);
int[] qs = new int[qsKeys.size()];
{
int i = 0;
for (String key : qsKeys) {
qs[i++] = dict.get(new Meta(Meta.PART_QSMD, key, req.getQueryStringMapping().get(key)));
}
Arrays.sort(qs);
}
int[] auth = new int[req.getAuthoritySegments().size() * 2];
{
int c = 0;
int l = req.getAuthoritySegments().size();
for (int i = 0; i < l; i++) {
int keyForExist = (l - i - 1) * 2 + 1;
int keyForValue = (l - i - 1) * 2 + 2;
auth[c++] = dict.get(new Meta(Meta.PART_AUTH, keyForExist, 0));
auth[c++] = dict.get(new Meta(Meta.PART_AUTH, keyForValue, req.getAuthoritySegments().get(i)));
}
}
int[] path = new int[req.getPathSegments().size() * 2];
{
int c = 0;
for (int i = 0; i < req.getPathSegments().size(); i++) {
int keyForExist = 2 * i + 1;
int keyForValue = 2 * i + 2;
path[c++] = dict.get(new Meta(Meta.PART_PATH, keyForExist, 0));
path[c++] = dict.get(new Meta(Meta.PART_PATH, keyForValue, req.getPathSegments().get(i)));
}
}
Transaction tran = new Transaction();
tran.add(new Group(Group.TYPE_ITEM_SET, info));
tran.add(new Group(Group.TYPE_SEQUENCE, auth));
tran.add(new Group(Group.TYPE_SEQUENCE, path));
tran.add(new Group(Group.TYPE_ITEM_SET, qs));
return tran;
}
@Override
public void prepare(Iterable<HttpRequest> reqs) {
qsKeys.clear();
dict.clear();
reverseDict.clear();
int authWidth = 0;
int pathWidth = 0;
for (HttpRequest req : reqs) {
this.qsKeys.addAll(req.getQueryStringMapping().keySet());
if (req.getAuthoritySegments().size() > authWidth)
authWidth = req.getAuthoritySegments().size();
if (req.getPathSegments().size() > pathWidth)
pathWidth = req.getPathSegments().size();
}
for (HttpRequest req : reqs) {
// METHOD + SCHEME + PORT
{
Meta meta = new Meta(Meta.PART_PROT, KEY_FOR_METHOD, req.getMethod());
if (!dict.containsKey(meta)) dict.put(meta, dict.size());
meta = new Meta(Meta.PART_PROT, KEY_FOR_SCHEME, req.getScheme());
if (!dict.containsKey(meta)) dict.put(meta, dict.size());
meta = new Meta(Meta.PART_PROT, KEY_FOR_PORT, req.getPort());
if (!dict.containsKey(meta)) dict.put(meta, dict.size());
}
// Authority
{
int l = req.getAuthoritySegments().size();
for (int i = 0; i < l; i++) {
int keyForExist = (l - i - 1) * 2 + 1;
int keyForValue = (l - i - 1) * 2 + 2;
Meta meta = new Meta(Meta.PART_AUTH, keyForExist, 0);
if (!dict.containsKey(meta)) dict.put(meta, dict.size());
meta = new Meta(Meta.PART_AUTH, keyForValue, req.getAuthoritySegments().get(i));
if (!dict.containsKey(meta)) dict.put(meta, dict.size());
}
}
// Path
for (int i = 0; i < req.getPathSegments().size(); i++) {
int keyForExist = 2 * i + 1;
int keyForValue = 2 * i + 2;
Meta meta = new Meta(Meta.PART_PATH, keyForExist, 0);
if (!dict.containsKey(meta)) dict.put(meta, dict.size());
meta = new Meta(Meta.PART_PATH, keyForValue, req.getPathSegments().get(i));
if (!dict.containsKey(meta)) dict.put(meta, dict.size());
}
// QueryString
for (String key : qsKeys) {
String rawValue = req.getQueryStringMapping().get(key);
Meta meta = new Meta(Meta.PART_QSMD, key, rawValue);
if (!dict.containsKey(meta)) dict.put(meta, dict.size());
}
}
dict.keySet().stream().forEach(key -> reverseDict.put(dict.get(key), key));
}
@Override
public HttpRequestHandler decode(Transaction tran) {
Integer method = null;
String scheme = null;
Integer port = null;
Map<Integer, String> authMap = new TreeMap<>();
Map<Integer, String> pathMap = new TreeMap<>();
List<String> authoritySegments = new ArrayList<>();
List<String> pathSegments;
SortedMap<String, String> queryStringMapping = new TreeMap<>();
Group infoGroup = tran.headGroup();
Group authGroup = tran.tailTransaction().headGroup();
Group pathGroup = tran.tailTransaction().tailTransaction().headGroup();
Group qsGroup = tran.tailTransaction().tailTransaction().tailTransaction().headGroup();
for (int x : infoGroup.array) {
Meta meta = reverseDict.get(x);
if (meta.key.compareTo(KEY_FOR_METHOD) == 0)
method = (Integer) meta.value;
else if (meta.key.compareTo(KEY_FOR_SCHEME) == 0)
scheme = (String) meta.value;
else if (meta.key.compareTo(KEY_FOR_PORT) == 0)
port = (Integer) meta.value;
else
assert false;
}
for (int x : authGroup.array) {
Meta meta = reverseDict.get(x);
int key = (int) meta.key;
if (key % 2 == 1) {
if (!pathMap.containsKey((key + 1) / 2)) {
authMap.put((key + 1) / 2, null);
}
} else {
authMap.put(key / 2, (String) meta.value);
}
}
authoritySegments = authMap.keySet().stream().map(key -> authMap.get(key)).collect(Collectors.toList());
authoritySegments = Lists.reverse(authoritySegments);
for (int x : pathGroup.array) {
Meta meta = reverseDict.get(x);
int key = (int) meta.key;
if (key % 2 == 1) {
if (!pathMap.containsKey((key + 1) / 2)) {
pathMap.put((key + 1) / 2, null);
}
} else {
pathMap.put(key / 2, (String) meta.value);
}
}
pathSegments = pathMap.keySet().stream().map(key -> pathMap.get(key)).collect(Collectors.toList());
for (int x : qsGroup.array) {
Meta meta = reverseDict.get(x);
String key = (String) meta.key;
String rawValue = (String) meta.key;
queryStringMapping.put(key, rawValue);
}
return new HttpRequestHandler(method, scheme, port, authoritySegments, pathSegments, queryStringMapping);
}
}
<file_sep>package jinhaoxia.handler.ready;
import jinhaoxia.handler.ready.io.ScannerHttpRequestReader;
import jinhaoxia.handler.ready.model.request.HttpRequest;
import jinhaoxia.handler.ready.model.request.HttpRequestHandler;
import jinhaoxia.handler.ready.model.request.Support;
import jinhaoxia.handler.ready.util.HttpRequestItemSetEncoder;
import jinhaoxia.handler.ready.util.IHttpRequestEncoder;
import jinhaoxia.support.pattern.AlgoGISM;
import jinhaoxia.support.pattern.Database;
import jinhaoxia.support.pattern.Transaction;
import java.util.*;
import java.util.stream.Collectors;
public final class HandlerReady {
private HandlerReady() {
}
public static List<HttpRequestHandler> learn(Collection<HttpRequest> requests) {
return learn(requests, 0.01);
}
public static List<HttpRequestHandler> learn(Collection<HttpRequest> requests, double minSupport) {
// encoding requests to itemset database
IHttpRequestEncoder encoder = new HttpRequestItemSetEncoder();
encoder.prepare(requests);
List<Transaction> transactions = requests.stream().map(req -> encoder.encode(req)).collect(Collectors.toList());
Database database = new Database(transactions);
// launching FPClose to mine the frequent patterns
AlgoGISM gism = new AlgoGISM();
gism.runAlgorithm(database, minSupport, null);
// receiving the mined frequent patterns & converting them to handlers.
List<HttpRequestHandler> handlers = gism.getPatterns().stream().map(tran -> encoder.decode(tran)).collect(Collectors.toList());
// sorting and returning handlers.
Collections.sort(handlers);
return handlers;
}
/**
*
* @param handlers
* @param requests
* @return Handlers with no support will be ignored in this phase.
*/
public static List<Support> handlers2supports(Collection<HttpRequestHandler> handlers, Collection<HttpRequest> requests) {
List<Support> supports = handlers.stream().map(handler -> new Support(handler)).collect(Collectors.toList());
List<HttpRequest> homeless = new ArrayList<>();
// assign requests to different handlers
for (HttpRequest req : requests) {
boolean assigned = false;
for (Support s : supports) {
if (s.getHandler().hit(req)) {
s.getRequests().add(req);
assigned = true;
break;
}
}
if (!assigned) {
homeless.add(req);
}
}
// assign handlers, which are not be assigned to any handlers, to a special handler null.
Support support4homeless = new Support(null);
support4homeless.getRequests().addAll(homeless);
supports.add(support4homeless);
supports = supports.stream().filter(s -> s.getRequests().size() > 0).collect(Collectors.toList());
return supports;
}
public static List<List<HttpRequest>> sample(Collection<Support> supports) {
List<List<HttpRequest>> requests = new ArrayList<>();
supports.forEach(Support::reOrderRequests);
for (int level = 0; ; level++) {
List<HttpRequest> reqs = new ArrayList<>();
for (Support s : supports) {
if (s.getRequests().size() > level) {
reqs.add(s.getRequests().get(level));
}
}
if (reqs.size() != 0) requests.add(reqs);
else break;
}
return requests;
}
}
<file_sep>package jinhaoxia.handler.ready.util;
import jinhaoxia.handler.ready.model.request.HttpRequest;
import jinhaoxia.handler.ready.model.request.HttpRequestHandler;
import jinhaoxia.support.pattern.Transaction;
public interface IHttpRequestEncoder {
Transaction encode(HttpRequest req);
void prepare(Iterable<HttpRequest> requests);
HttpRequestHandler decode(Transaction tran);
}
<file_sep>package jinhaoxia.support.pattern.cmclasp;
import jinhaoxia.support.pattern.cmclasp.clasp_AGP.AlgoCM_ClaSP;
import jinhaoxia.support.pattern.cmclasp.clasp_AGP.dataStructures.abstracciones.ItemAbstractionPair;
import jinhaoxia.support.pattern.cmclasp.clasp_AGP.dataStructures.creators.AbstractionCreator;
import jinhaoxia.support.pattern.cmclasp.clasp_AGP.dataStructures.creators.AbstractionCreator_Qualitative;
import jinhaoxia.support.pattern.cmclasp.clasp_AGP.dataStructures.database.SequenceDatabase;
import jinhaoxia.support.pattern.cmclasp.clasp_AGP.dataStructures.patterns.Pattern;
import jinhaoxia.support.pattern.cmclasp.clasp_AGP.idlists.creators.IdListCreator;
import jinhaoxia.support.pattern.cmclasp.clasp_AGP.idlists.creators.IdListCreatorStandard_Map;
import jinhaoxia.support.pattern.cmclasp.clasp_AGP.savers.Saver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class MyCMClaSP {
public List<int[]> cmclasp(List<int[]> data, double minSupport) {
// Load a sequence database
double support = minSupport;
boolean keepPatterns = true;
boolean verbose = false;
boolean findClosedPatterns = true;
boolean executePruningMethods = true;
boolean outputSequenceIdentifiers = false;
AbstractionCreator abstractionCreator = AbstractionCreator_Qualitative.getInstance();
IdListCreator idListCreator = IdListCreatorStandard_Map.getInstance();
SequenceDatabase sequenceDatabase = new SequenceDatabase(abstractionCreator, idListCreator);
double relativeSupport = sequenceDatabase.loadDatabase(data, minSupport);
AlgoCM_ClaSP algorithm = new AlgoCM_ClaSP(relativeSupport, abstractionCreator, findClosedPatterns, executePruningMethods);
try {
List<Pattern> patterns = new ArrayList<>();
Saver saver = new Saver() {
@Override
public void savePattern(Pattern p) {
patterns.add(p);
}
@Override
public void finish() {
}
@Override
public void clear() {
patterns.clear();
}
@Override
public String print() {
return patterns.toString();
}
};
algorithm.runAlgorithm(sequenceDatabase, keepPatterns, verbose, saver);
return patterns.stream().map(pattern -> convertPattern(pattern)).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
return Collections.emptyList();
}
}
private int[] convertPattern(Pattern pattern) {
int[] tmp = new int[pattern.getElements().size()];
int i = 0;
for (ItemAbstractionPair elem : pattern.getElements()) {
tmp[i++] = (Integer) elem.getItem().getId();
}
return tmp;
}
}
<file_sep>package jinhaoxia.support.pattern;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Transaction extends ArrayList<Group> {
public Transaction() {
super();
}
public Transaction(List<Group> groups) {
super(groups);
}
public Transaction tailTransaction() {
if (this.size() <= 1) return new Transaction();
return new Transaction(this.subList(1, this.size()));
}
public Group headGroup() {
if (this.size() == 0) return null;
return this.get(0);
}
List<Integer> getGroupTypes() {
if (this.size() == 0) return Collections.emptyList();
ArrayList<Integer> types = new ArrayList<>();
for (Group grp : this) {
types.add(grp.type);
}
return types;
}
}
<file_sep>Handler-Ready
=============
This project is the method `handler-ready` proposed in the paper `An Efficient Black-Box Vulnerability Scanning Method for Web Application`.
The method `handler-ready` is designed to learn the HTTP requests' frequent patterns(so called `handler`).
The algorithms of FPClose and CM-Clasp are imported from SPMF http://www.philippe-fournier-viger.com/spmf/index.php . | 87404d581aada487d3679b60f69eaf2cf0dd5e6d | [
"Markdown",
"Java"
]
| 8 | Java | jinhaoxia/handler-ready | 580ffa994c0492666658502a79aaa345af5754e4 | 96d7e40139423b358cfc9dc9802d8d48f1b3aa37 |
refs/heads/master | <repo_name>jefflarkin/openacc-interoperability<file_sep>/Makefile
EXES=cuda_main openacc_c_main openacc_c_cublas openacc_c_cublas_v2 thrust cuda_map acc_malloc openacc_streams openacc_cuda_device
ifeq "$(PE_ENV)" "CRAY"
# Cray Compiler
CXX=CC
CXXFLAGS=-hlist=a
CC=cc
CFLAGS=-hlist=a
CUDAC=nvcc
CUDAFLAGS=-gencode arch=compute_60,code=sm_60 -gencode arch=compute_70,code=sm_70 -gencode arch=compute_75,code=sm_75 -gencode arch=compute_80,code=sm_80
FC=ftn
FFLAGS=-ra
LDFLAGS=-L$(CUDA_HOME)/lib64 -lcudart
else
# PGI Compiler
EXES+=cuf_main cuf_openacc_main openacc_cublas
CXX=nvc++
CXXFLAGS=-fast -acc -Minfo=accel -gpu=cc60,cc70,cc75,cc80
CC=nvc
CFLAGS=-fast -acc -Minfo=accel -gpu=cc60,cc70,cc75,cc80
CUDAC=nvcc
# Hard-coded architectures to avoid build issue when arches are added or
# removed from compilers
CUDAFLAGS=-gencode arch=compute_60,code=sm_60 -gencode arch=compute_70,code=sm_70 -gencode arch=compute_75,code=sm_75 -gencode arch=compute_80,code=sm_80
FC=nvfortran
FFLAGS=-fast -acc -Minfo=accel -gpu=cc60,cc70,cc75,cc80
LDFLAGS=-Mcuda
endif
all: $(EXES)
openacc_cublas: openacc_cublas.o
$(FC) -o $@ $(CFLAGS) $^ $(LDFLAGS) -Mcudalib=cublas
openacc_c_cublas: openacc_c_cublas.o
$(CC) -o $@ $(CFLAGS) $^ $(LDFLAGS) -Mcudalib=cublas
openacc_c_cublas_v2: openacc_c_cublas_v2.o
$(CC) -o $@ $(CFLAGS) $^ $(LDFLAGS) -Mcudalib=cublas
openacc_c_main: saxpy_cuda.o openacc_c_main.o
$(CXX) -o $@ $(CFLAGS) $^ $(LDFLAGS)
cuda_main: saxpy_openacc_c.o cuda_main.o
$(CXX) -o $@ $(CFLAGS) $^ $(LDFLAGS)
cuf_main: cuf_main.o
$(FC) -o $@ $(FFLAGS) $^ $(LDFLAGS) -Mcuda
cuf_openacc_main: kernels.o openacc_main.o
$(FC) -o $@ $(FFLAGS) $^ $(LDFLAGS) -Mcuda
thrust: saxpy_openacc_c.o thrust.o
$(CXX) -o $@ $(CXXFLAGS) $^ $(LDFLAGS) -lstdc++
cuda_map: saxpy_openacc_c_mapped.o cuda_map.o
$(CXX) -o $@ $(CXXFLAGS) $^ $(LDFLAGS)
acc_malloc: saxpy_openacc_c.o acc_malloc.o
$(CC) -o $@ $(CXXFLAGS) $^ $(LDFLAGS)
openacc_cuda_device: saxpy_cuda_device.o openacc_cuda_device.o
$(CXX) -o $@ $(CXXFLAGS) $^ $(LDFLAGS)
saxpy_cuda_device.o: saxpy_cuda_device.cu
$(CUDAC) $(CUDAFLAGS) -rdc true -c $<
openacc_streams: saxpy_cuda_async.o openacc_streams.o
$(CXX) -o $@ $(CXXFLAGS) $^ $(LDFLAGS)
.SUFFIXES:
.SUFFIXES: .c .o .f90 .cu .cpp .cuf
.c.o:
$(CC) $(CFLAGS) -c $<
.cpp.o:
$(CXX) $(CXXFLAGS) -c $<
.f90.o:
$(FC) $(FFLAGS) -c $<
.cuf.o:
$(FC) $(FFLAGS) -c $<
.cu.o:
$(CUDAC) $(CUDAFLAGS) -c $<
.PHONY: clean
clean:
rm -rf *.o *.ptx *.cub *.lst *.mod $(EXES)
<file_sep>/openacc_c_cublas_v2.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "cublas_v2.h"
int main(int argc, char **argv)
{
float *x, *y, tmp;
int n = 2000, i;
cublasStatus_t stat = CUBLAS_STATUS_SUCCESS;
x = (float*)malloc(n*sizeof(float));
y = (float*)malloc(n*sizeof(float));
#pragma acc enter data create(x[0:n]) create(y[0:n])
cublasHandle_t handle;
stat = cublasCreate(&handle);
if ( CUBLAS_STATUS_SUCCESS != stat ) {
printf("CUBLAS initialization failed\n");
}
#pragma acc kernels
{
for( i = 0; i < n; i++)
{
x[i] = 1.0f;
y[i] = 0.0f;
}
}
#pragma acc host_data use_device(x,y)
{
const float alpha = 2.0f;
stat = cublasSaxpy(handle, n, &alpha, x, 1, y, 1);
if (stat != CUBLAS_STATUS_SUCCESS) {
printf("cublasSaxpy failed\n");
}
stat = cublasSnrm2(handle, n, x, 1, &tmp);
if (stat != CUBLAS_STATUS_SUCCESS) {
printf("cublasSnrm2 failed\n");
}
}
cublasDestroy(handle);
#pragma acc exit data copyout(x[0:n]) copyout(y[0:n])
fprintf(stdout, "y[0] = %f\n",y[0]);
fprintf(stdout, "x[0] = %f\n",x[0]);
fprintf(stdout, "norm2(x) = %f\n",tmp);
return 0;
}
<file_sep>/openacc_cuda_device.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#pragma acc routine seq
extern "C" float saxpy_dev(float, float, float);
int main(int argc, char **argv)
{
float *x, *y, tmp;
int n = 1<<20, i;
x = (float*)malloc(n*sizeof(float));
y = (float*)malloc(n*sizeof(float));
#pragma acc data create(x[0:n]) copyout(y[0:n])
{
#pragma acc kernels
{
for( i = 0; i < n; i++)
{
x[i] = 1.0f;
y[i] = 0.0f;
}
}
#pragma acc parallel loop
for( i = 0; i < n; i++ )
{
y[i] = saxpy_dev(2.0, x[i], y[i]);
}
}
fprintf(stdout, "y[0] = %f\n",y[0]);
return 0;
}
<file_sep>/acc_malloc.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <openacc.h>
void saxpy(int,float,float*,float*);
void set(int,float,float*);
int main(int argc, char **argv)
{
float *x, *y, tmp;
int n = 1<<20;
x = acc_malloc((size_t)n*sizeof(float));
y = acc_malloc((size_t)n*sizeof(float));
set(n,1.0f,x);
set(n,0.0f,y);
saxpy(n, 2.0, x, y);
acc_memcpy_from_device(&tmp,y,(size_t)sizeof(float));
acc_free(x);
acc_free(y);
printf("%f\n",tmp);
return 0;
}
<file_sep>/README.md
Stupid OpenACC (Interoperability) Tricks
========================================
Author: <NAME> <<EMAIL>>
This repository demonstrates interoperability between OpenACC and various other
GPU programming models. An OpenACC-enabled compiler is required. The default
makefile has been written for PGI and tested with PGI 20.9, although most if
not all examples will work with earlier versions.
If building with the Cray Compiler Environment the makefile will detect this
and adjust compiler flags and targets accordingly. Some targets rely on PGI
CUDA Fortran features, these targets will be disabled when building with CCE.
Build Instructions:
-------------------
$ make
Examples
--------
* cuda\_main - calling OpenACC from CUDA C
* openacc\_c\_main - Calling CUDA from OpenACC in C
* openacc\_c\_cublas - Calling CUBLAS from OpenACC in C
* thrust - Mixing OpenACC and Thrust in C++
* cuda\_map - Using OpenACC acc\_map\_data with CUDA in C
* cuf\_main - Calling OpenACC from CUDA Fortran
* cuf\_openacc\_main - Calling CUDA Fortran from OpenACC
* openacc\_cublas - Calling CUBLAS from OpenACC in CUDA Fortran
* acc\_malloc - Same as cuda\_main, but using the OpenACC API
* openacc\_streams - Mixes OpenACC async queues and CUDA streams
* openacc\_cuda\_device - Calls a CUDA \_\_device\_\_ kernel within an OpenACC
region
<file_sep>/saxpy_openacc_c_mapped.c
#include <openacc.h>
void map(float * restrict harr, float * restrict darr, int size)
{
acc_map_data(harr, darr, size);
}
void saxpy(int n, float a, float * restrict x, float * restrict y)
{
#pragma acc kernels present(x,y)
{
for(int i=0; i<n; i++)
{
y[i] += a*x[i];
}
}
}
void set(int n, float val, float * restrict arr)
{
#pragma acc kernels present(arr)
{
for(int i=0; i<n; i++)
{
arr[i] = val;
}
}
}
<file_sep>/saxpy_openacc_c.c
void saxpy(int n, float a, float * restrict x, float * restrict y)
{
#pragma acc kernels deviceptr(x,y)
{
for(int i=0; i<n; i++)
{
y[i] += a*x[i];
}
}
}
void set(int n, float val, float * restrict arr)
{
#pragma acc kernels deviceptr(arr)
{
for(int i=0; i<n; i++)
{
arr[i] = val;
}
}
}
<file_sep>/openacc_c_main.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
extern void saxpy(int,float,float*,float*);
int main(int argc, char **argv)
{
float *x, *y, tmp;
int n = 1<<20, i;
x = (float*)malloc(n*sizeof(float));
y = (float*)malloc(n*sizeof(float));
#pragma acc data create(x[0:n]) copyout(y[0:n])
{
#pragma acc kernels
{
for( i = 0; i < n; i++)
{
x[i] = 1.0f;
y[i] = 0.0f;
}
}
#pragma acc host_data use_device(x,y)
{
saxpy(n, 2.0, x, y);
}
}
fprintf(stdout, "y[0] = %f\n",y[0]);
return 0;
}
| 5f4a631cbf1ef382fa112aa94a4901966444ca0b | [
"Markdown",
"C",
"Makefile",
"C++"
]
| 8 | Makefile | jefflarkin/openacc-interoperability | 17e9515db77d3c1fb92331b8e3d8ee482ce0c734 | e57b1632335e34e6f58a4f964a1b474cd2492d4e |
refs/heads/main | <file_sep>#include "types.h"
#include "user.h"
int main() {
int mode = 0x13;
int x;
int y;
int colour = 0;
greeting();
setvideomode(mode);
for (x = 0; x <= 320; x++)
{
for (y = 0; y <= 200; y++)
{
//printf(1, "%d, %d, %d\n", x, y, c);
setpixel(x,y,colour);
}
}
drawline(10,10,310,190,1);
drawline(10,100,150,190,2);
drawline(150,10,310,100,4);
sleep(200);
setvideomode(0x03);
/* greeting();
int a = 6;
int b = 12;
int c = add(a,b);
*/
greeting();
sleep(200);
exit();
}
<file_sep># xv6-LineDrawing
#Run program using 'make' , 'make qemu' , 'Demo'
#Program will run through showing 13h line drawing and after a few seconds change to 3h and show a message.
<file_sep>#include "types.h"
#include "defs.h"
int sys_getch(void) {
return consoleget();
}
// TODO: Implement your system call for switching video modes (and any other video-related syscalls)
// in here.
int sys_greeting(void) {
cprintf("Hello, user\n");
return 0;
}
int sys_setvideomode(void){
int m;
if (argint(0, &m) < 0) {
return -1;
}
// cprintf("Getting here");
return consolevgamode(m);
}
int sys_setpixel(void){
int x;
int y;
int c;
if (argint(0, &x) < 0 || argint(1, &y) < 0 || argint(2, &c) < 0) {
return -1;
}
//cprintf("Hello, user x: %d, y: %d, c: %d \n", x,y,c);
uchar* p;
p = consolevgabuffer()+ 320 * y + x;
*p = c;
return 0;
}
int sys_drawline(void){
int x0;
int y0;
int x1;
int y1;
int c;
if (argint(0, &x0) < 0 || argint(1, &y0) < 0 || argint(2, &x1) < 0 || argint(3, &y1) < 0 || argint(4, &c) < 0) {
return -1;
}
cprintf("x0:%d,y0:%d,x1:%d,y1:%d,c:%d\n",x0,y0,x1,y1,c);
int dx, dy, x, y;
dx=x1-x0;
dy=y1-y0;
x=x0;
y=y0;
if(dx<0){
dx = 0 - dx;
}
if(dy<0){
dy = 0 - dy;
}
if(dx > dy){
uchar* p;
p = consolevgabuffer()+ 320 * y + x;
*p = c;
int pk = (2*dy) - dx;
for(int i = 0; i < dx; i++){
x++;
if(pk < 0){
pk = pk + (2*dy);
} else {
y++;
pk = pk + (2*dy) - (2*dx);
}
uchar* p;
p = consolevgabuffer()+ 320 * y + x;
*p = c;
}
} else {
uchar* p;
p = consolevgabuffer()+ 320 * y + x;
*p = c;
int pk = (2*dx) - dy;
for(int i = 0; i < dy; i++){
y++;
if(pk < 0){
pk = pk + (2*dx);
} else {
x++;
pk = pk + (2*dx) - (2*dy);
}
uchar* p;
p = consolevgabuffer()+ 320 * y + x;
*p = c;
}
}
return 0;
}
| 54392660859c7772b404a3ff2b60b4a8378241bd | [
"Markdown",
"C"
]
| 3 | C | DavidMorgan1999/xv6-LineDrawing | ffda0e9cfee74a8058ecc27e71a15bb76c295415 | 4f2fff692e9b15eced610df0cdb8065268e2c4e1 |
refs/heads/master | <file_sep>using OA.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OA.Service
{
public interface IUserService
{
IEnumerable<Course> GetUsers();
Course GetUser(long id);
void InsertUser(Course user);
void UpdateUser(Course user);
void DeleteUser(long id);
}
}
<file_sep># AngularJS-2-Token-based-Authentication-using-Asp.net-Core-Web-API-and-JSON-Web-Token
http://logcorner.com/angular2-token-based-authentication-using-asp-net-core-web-api-and-json-web-token/
ASP.NET Core Identity is designed to enable us to easily use a number of different storage providers for our ASP.NET applications. We can use the supplied identity providers that are included with the .NET Framework, or we can implement our own providers.
In this tutorial, we will build a Token-Based Authentication using ASP.NET Core Identity , ASP.NET Core Web API and Angular2
With Token-Based Authentication, the client application is not dependent on a specific authentication mechanism. The token is generated by the server and the Web API have some APIs to understand, validate the token and perform the authentication. This approach provides Loose Coupling between client and the Web API.
this toturial is not for beginners, to follow it, you must understand Angular2 and Asp.NET REST Services
2
Securing our web application consists of two scenarios Authentication and Authorization
1. Authentication identifies the user. So the user must be registered first, using login and password or third party logins like Facebook, Twitter, etc...
2. Authorization talks about permission for authenticated users
- What is the user (authenticated) allowed to do ?
- What ressources can the user access ?
We have build our back end service using ASP.NET WEB API Core, web api provides an internal authorization server using OWIN MIDDLEWARE
The authorization server and the authentication filter are both called into an OWIN middleware component that handles OAuth2
3
This article is the third part of a series of 3 articles
Token Based Authentication using Asp.net Core Web Api
Asp.Net Core Web Api Integration testing using EntityFrameworkCore LocalDb and XUnit2
Angular2 Token Based Authentication using Asp.net Core Web API and JSON Web Token
BUILDING WEB API RESSOURCE SERVER AND AUTHORIZATION SERVER
In the first part Token Based Authentication using Asp.net Core Web API, I talked about how to configure an ASP.NET Web API Core Token Based Authentication using JWT. So in this tutorial I will talk about an Angular2 client that connect to the Web Api Authorization server Using a JWT Token
BUILDING ANGULAR2 WEB CLIENT
Create an ASP.NET Empty WebSite and structure it as follow
Structure
Package.json
"dependencies": {
"@angular/common": "~2.4.0",
"@angular/compiler": "~2.4.0",
"@angular/core": "~2.4.0",
"@angular/forms": "~2.4.0",
"@angular/http": "~2.4.0",
"@angular/platform-browser": "~2.4.0",
"@angular/platform-browser-dynamic": "~2.4.0",
"@angular/router": "~3.4.0",
"systemjs": "0.19.40",
"angular2-jwt": "^0.2.3",
"bootstrap": "^3.3.7",
"core-js": "^2.4.1",
"rxjs": "^5.0.1",
"zone.js": "^0.7.4"
},
Package.json defines some dependencies , so use npm to restore them : npm install
Main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
Here, we import AppModule and bootstrap it using platformBrowserDynamic. Because we run our application on the browser. platformBrowserDynamic use a specific way of bootstrapping the application and is defined in @angular/platform-browser-dynamic
There are many way to setup an angular2 project (Webpack or System.js), but we can use the angular project template in visual studio 2017
app.module.ts file
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { PageNotFoundComponent } from './page-not-found.component';
import { UserModule } from './user/user.module';
import { CommonService } from './shared/common.service';
@NgModule({
imports: [
BrowserModule,
HttpModule,
ReactiveFormsModule,
UserModule,
AppRoutingModule
],
declarations: [
AppComponent,
HomeComponent,
PageNotFoundComponent
],
providers: [
CommonService
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.module contains sections like :
Imports : import dependencies
declarations : components
providers : injected services
index.html
<!DOCTYPE html>
<html>
<head>
<script>document.write('<base href="' + document.location + '" />');</script>
<title>AngularJS 2 Token based Authentication using Asp.net Core Web API and JSON Web Token</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="/">
<link href="node_modules/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<link rel="stylesheet" href="styles.css">
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app/main.js').catch(function (err) { console.error(err); });
</script>
</head>
<body>
<jwt-app>Starting Client Application, please wait ...</jwt-app>
</body>
</html>
Index.html is the entry point of our SPA application, the selector jwt-app will be replaced dynamically by the template of the current route
app.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { IProfile } from './user/user.model';
import { UserService } from './user/user.service';
import { UserProfile } from './user/user.profile';
@Component({
selector: 'jwt-app',
templateUrl: './app/app.component.html'
})
export class AppComponent implements OnInit {
pageTitle: string = 'Welcome to AngularJS 2 Token based Authentication using Asp.net Core Web API and JSON Web Token';
loading: boolean = true;
Profile: IProfile;
constructor(private authService: UserService,
private authProfile: UserProfile,
private router: Router) {
}
ngOnInit(): void {
this.Profile = this.authProfile.userProfile;
}
logOut(): void {
this.authService.logout();
this.router.navigateByUrl('/home');
}
}
common.service.ts
Lets create a common.service.ts file and CommonService class and decorate it as @Injectable()
import { Injectable } from '@angular/core';
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/throw';
import { Response } from '@angular/http';
@Injectable()
export class CommonService {
private baseUrl = 'http://localhost:58834/api';
constructor() { }
getBaseUrl(): string {
return this.baseUrl;
}
handleFullError(error: Response) {
return Observable.throw(error);
}
handleError(error: Response): Observable<any> {
let errorMessage = error.json();
console.error(errorMessage);
return Observable.throw(errorMessage.error || 'Server error');
}
}
Here, we implement common functionalities such as error handling, baseUrl to call API, (http://localhost:58834/api is the API endpoint)
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { PageNotFoundComponent } from './page-not-found.component';
import { AuthGuard } from './common/auth.guard';
@NgModule({
imports: [
RouterModule.forRoot([
{ path: 'home', component: HomeComponent },
{
path: 'products',
canActivate: [AuthGuard],
data: { preload: true },
loadChildren: 'app/products/product.module#ProductModule'
},
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
], { useHash: true })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
app-routing module enable us to define routing strategy :
http://localhost:3276/home : loads HomeComponent
Empty URL : loads HomeComponent also
Enexisting URL : loads PageNotFoundComponent
app.component.html
<div>
<nav class="navbar navbar-default ">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">AngularJS 2 Token based Authentication using Asp.net Core Web API and JSON Web Token</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li *ngIf="authService.isAuthenticated()">
<a>Welcome {{ Profile.currentUser.userName }}</a>
</li>
<li *ngIf="!authService.isAuthenticated()">
<a [routerLink]="['/login']">Log In</a>
</li>
<li *ngIf="!authService.isAuthenticated()">
<a [routerLink]="['/signup']">Register</a>
</li>
<li *ngIf="authService.isAuthenticated()">
<span> <a (click)="logOut()">Log Out</a></span>
</li>
</ul>
</div>
<div>
<ul class="nav navbar-nav">
<li routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">
<a [routerLink]="['/home']">Home</a>
</li>
<li>
<a [routerLink]="['/products']">Products</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-10">
<router-outlet></router-outlet>
</div>
<div class="col-md-2">
<router-outlet name="popup"></router-outlet>
</div>
</div>
</div>
</div>
home.component.ts
import { Component } from '@angular/core';
@Component({
templateUrl: './app/home/home.component.html'
})
export class HomeComponent {
public pageTitle: string = 'Welcome';
}
home.component.html
<div class="panel panel-success">
<div class="panel-heading">
{{pageTitle}}
</div>
</div>
export interface IProduct {
id: number;
name: string;
description: string;
price: number;
}
product.service.ts
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
import { IProduct } from './product.model';
import { UserProfile } from '../user/user.profile'
import { CommonService } from '../shared/common.service'
@Injectable()
export class ProductService {
constructor(private http: Http,
private authProfile: UserProfile,
private commonService: CommonService) { }
getProducts(): Observable<IProduct[]> {
let url = this.commonService.getBaseUrl() + '/product';
let options = null;
let profile = this.authProfile.getProfile();
if (profile != null && profile != undefined) {
let headers = new Headers({ 'Authorization': 'Bearer ' + profile.token });
options = new RequestOptions({ headers: headers });
}
let data: Observable<IProduct[]> = this.http.get(url, options)
.map(res => <IProduct[]>res.json())
.do(data => console.log('getProducts: ' + JSON.stringify(data)))
.catch(this.commonService.handleError);
return data;
}
}
ProductService.getProducts is the protected ressource, so to get products users must be logged in first and retrive a token. and finally put the token in the header of the request :
if (profile != null && profile != undefined) {
let headers = new Headers({ 'Authorization': 'Bearer ' + profile.token });
options = new RequestOptions({ headers: headers });
ProductListComponent is protected by a guard .So we must add the guard to any protected route. here AuthGuard.canActivate must be equal to true but AuthGuard.canActivate return true only if the user is authenticated
RouterModule.forRoot([
{ path: 'home', component: HomeComponent },
{
path: 'products',
canActivate: [AuthGuard],
data: { preload: true },
loadChildren: 'app/products/product.module#ProductModule'
},
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
], { useHash: true })
product-list.component.ts
import { Component, OnInit } from '@angular/core';
import { IProduct } from './product.model';
import { ProductService } from './product.service';
@Component({
templateUrl: './app/products/product-list.component.html',
styleUrls: ['./app/products/product-list.component.css']
})
export class ProductListComponent implements OnInit {
pageTitle: string = 'Product List';
products: IProduct[];
constructor(private productService: ProductService) { }
ngOnInit(): void {
this.productService.getProducts()
.subscribe(products => this.products = products,
error => console.log(error));
}
}
product-list.component.html
<div class="panel panel-success">
<div class="panel-heading">
{{pageTitle}}
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4">
</div>
</div>
<div class="row">
<div class="col-md-6">
</div>
</div>
<div class="table-responsive">
<table class="table"
*ngIf="products && products.length">
<thead>
<tr>
<th>Id</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let product of products ">
<td>
{{product.id}}
</td>
<td>
{{product.name}}
</td>
<td>{{ product.price }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Register User
signup.component.ts
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { UserService } from '../user/user.service';
@Component({
templateUrl: './app/signup/signup.component.html'
})
export class SignupComponent {
errorMessage: string;
pageTitle = 'signup';
constructor(private authService: UserService,
private router: Router) { }
register(signupForm: NgForm) {
if (signupForm && signupForm.valid) {
let userName = signupForm.form.value.userName;
let password = <PASSWORD>Form.form.value.password;
let confirmPassword = signupForm.form.value.confirmPassword;
var result = this.authService.register(userName, password, confirmPassword)
.subscribe(
response => {
if (this.authService.redirectUrl) {
this.router.navigateByUrl(this.authService.redirectUrl);
} else {
this.router.navigate(['/']);
}
},
error => {
var results = error['_body'];
this.errorMessage = error.statusText + ' ' +
error.text();
}
);
} else {
this.errorMessage = 'Please enter a user name and password.';
};
}
}
signup.component.html
<div class="panel panel-success">
<div class="panel-heading">
{{pageTitle}}
</div>
<div class="panel-body">
<form class="form-horizontal"
novalidate
(ngSubmit)="register(signupForm)"
#signupForm="ngForm"
autocomplete="off">
<fieldset>
<div class="form-group"
[ngClass]="{'has-error': (userNameVar.touched ||
userNameVar.dirty) &&
!userNameVar.valid }">
<label class="col-md-2 control-label"
for="userNameId">User Name</label>
<div class="col-md-8">
<input class="form-control"
id="userNameId"
type="text"
placeholder="<NAME> (required)"
required
(ngModel)="userName"
name="userName"
#userNameVar="ngModel" />
<span class="help-block" *ngIf="(userNameVar.touched ||
userNameVar.dirty) &&
userNameVar.errors">
<span *ngIf="userNameVar.errors.required">
User name is required.
</span>
</span>
</div>
</div>
<div class="form-group"
[ngClass]="{'has-error': (passwordVar.touched ||
passwordVar.dirty) &&
!passwordVar.valid }">
<label class="col-md-2 control-label" for="passwordId">Password</label>
<div class="col-md-8">
<input class="form-control"
id="passwordId"
type="<PASSWORD>"
placeholder="<PASSWORD> (required)"
required
(ngModel)="password"
name="password"
#passwordVar="ngModel" />
<span class="help-block" *ngIf="(passwordVar.touched ||
passwordVar.dirty) &&
passwordVar.errors">
<span *ngIf="passwordVar.errors.required">
Password is required.
</span>
</span>
</div>
</div>
<div class="form-group"
[ngClass]="{'has-error': (confirmPasswordVar.touched ||
confirmPasswordVar.dirty) &&
!confirmPasswordVar.valid }">
<label class="col-md-2 control-label" for="confirmPasswordId">confirmPassword</label>
<div class="col-md-8">
<input class="form-control"
id="confirmPasswordId"
type="password"
placeholder="confirmPassword (required)"
required
(ngModel)="confirmPassword"
name="confirmPassword"
#confirmPasswordVar="ngModel" />
<span class="help-block" *ngIf="(confirmPasswordVar.touched ||
confirmPasswordVar.dirty) &&
confirmPasswordVar.errors">
<span *ngIf="confirmPasswordVar.errors.required">
confirmPassword is required.
</span>
</span>
</div>
</div>
<div class="form-group">
<div class="col-md-4 col-md-offset-2">
<span>
<button class="btn btn-success"
type="submit"
style="width:80px;margin-right:10px"
[disabled]="!signupForm.valid">
Sign Up
</button>
</span>
<span>
<a class="btn btn-default"
[routerLink]="['/']">
Cancel
</a>
</span>
</div>
</div>
</fieldset>
</form>
<div class="has-error" *ngIf="errorMessage">{{errorMessage}}</div>
</div>
</div>
2. Authenticate User
login.component.ts
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { UserService } from '../user/user.service';
@Component({
templateUrl: './app/login/login.component.html'
})
export class LoginComponent {
errorMessage: string;
pageTitle = 'Log In';
constructor(private authService: UserService,
private router: Router) { }
login(loginForm: NgForm) {
if (loginForm && loginForm.valid) {
let userName = loginForm.form.value.userName;
let password = <PASSWORD>.form.value.password;
var result = this.authService.login(userName, password).subscribe(
response => {
if (this.authService.redirectUrl) {
this.router.navigateByUrl(this.authService.redirectUrl);
} else {
this.router.navigate(['/products']);
}
},
error => {
var results = error['_body'];
this.errorMessage = error.statusText + ' ' +
error.text();
});
} else {
this.errorMessage = 'Please enter a user name and password.';
};
}
}
login.component.html
<div class="panel panel-success">
<div class="panel-heading">
{{pageTitle}}
</div>
<div class="panel-body">
<form class="form-horizontal"
novalidate
(ngSubmit)="login(loginForm)"
#loginForm="ngForm"
autocomplete="off">
<fieldset>
<div class="form-group"
[ngClass]="{'has-error': (userNameVar.touched ||
userNameVar.dirty) &&
!userNameVar.valid }">
<label class="col-md-2 control-label"
for="userNameId">User Name</label>
<div class="col-md-8">
<input class="form-control"
id="userNameId"
type="text"
placeholder="<NAME> (required)"
required
(ngModel)="userName"
name="userName"
#userNameVar="ngModel" />
<span class="help-block" *ngIf="(userNameVar.touched ||
userNameVar.dirty) &&
userNameVar.errors">
<span *ngIf="userNameVar.errors.required">
User name is required.
</span>
</span>
</div>
</div>
<div class="form-group"
[ngClass]="{'has-error': (passwordVar.touched ||
passwordVar.dirty) &&
!passwordVar.valid }">
<label class="col-md-2 control-label" for="passwordId">Password</label>
<div class="col-md-8">
<input class="form-control"
id="passwordId"
type="<PASSWORD>"
placeholder="<PASSWORD> (required)"
required
(ngModel)="password"
name="password"
#passwordVar="ngModel" />
<span class="help-block" *ngIf="(passwordVar.touched ||
passwordVar.dirty) &&
passwordVar.errors">
<span *ngIf="passwordVar.errors.required">
Password is required.
</span>
</span>
</div>
</div>
<div class="form-group">
<div class="col-md-4 col-md-offset-2">
<span>
<button class="btn btn-success"
type="submit"
style="width:80px;margin-right:10px"
[disabled]="!loginForm.valid">
Log In
</button>
</span>
<span>
<a class="btn btn-default"
[routerLink]="['/']">
Cancel
</a>
</span>
</div>
</div>
</fieldset>
</form>
<div class="has-error" *ngIf="errorMessage">{{errorMessage}}</div>
</div>
</div>
3. Auth Gard
auth.guard.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { UserService } from '../user/user.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authService: UserService) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.authService.isAuthorized()) {
return true;
}
this.authService.redirectUrl = state.url;
this.router.navigate(['/login']);
return false;
}
}
user.model.ts
export interface IProfile {
token: string;
expiration: string;
claims: IClaim[];
currentUser: IUser;
}
interface IClaim {
type: string;
value: string;
}
interface IUser {
id: string;
userName: string;
email: string;
}
user.module.ts
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { LoginComponent } from '../login/login.component';
import { SignupComponent } from '../signup/signup.component';
import { AuthGuard } from '../common/auth.guard';
import { SharedModule } from '../shared/shared.module';
import {
UserService,
UserProfile
} from './index'
@NgModule({
imports: [
SharedModule,
RouterModule.forChild([
{ path: 'login', component: LoginComponent },
{ path: 'signup', component: SignupComponent },
])
],
declarations: [
LoginComponent,
SignupComponent
],
providers: [
UserService,
AuthGuard,
UserProfile
]
})
export class UserModule { }
user.profile.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Headers } from '@angular/http';
import {
IProfile
} from './index'
@Injectable()
export class UserProfile {
userProfile: IProfile = {
token: "",
expiration: "",
currentUser: { id: '', userName: '', email: '' },
claims: null
};
constructor(private router: Router) {
}
setProfile(profile: IProfile): void {
var nameid = profile.claims.filter(p => p.type == 'nameid')[0].value;
var userName = profile.claims.filter(p => p.type == 'sub')[0].value;
var email = profile.claims.filter(p => p.type == 'email')[0].value;
sessionStorage.setItem('access_token', profile.token);
sessionStorage.setItem('expires_in', profile.expiration);
sessionStorage.setItem('nameid', nameid);
sessionStorage.setItem('userName', userName);
sessionStorage.setItem('email', email);
}
getProfile(authorizationOnly: boolean = false): IProfile {
var accessToken = sessionStorage.getItem('access_token');
if (accessToken) {
this.userProfile.token = accessToken;
this.userProfile.expiration = sessionStorage.getItem('expires_in');
if (this.userProfile.currentUser == null) {
this.userProfile.currentUser = { id: '', userName: '', email: '' }
}
this.userProfile.currentUser.id = sessionStorage.getItem('nameid');
this.userProfile.currentUser.userName = sessionStorage.getItem('userName');
}
return this.userProfile;
}
resetProfile(): IProfile {
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('expires_in');
this.userProfile = {
token: "",
expiration: "",
currentUser: null,
claims: null
};
return this.userProfile;
}
}
user.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Router } from '@angular/router';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { CommonService } from '../shared/common.service';
import { contentHeaders } from '../common/headers';
import { UserProfile } from './user.profile';
import { IProfile } from './user.model';
@Injectable()
export class UserService {
redirectUrl: string;
errorMessage: string;
constructor(
private http: Http,
private router: Router,
private authProfile: UserProfile,
private commonService: CommonService) { }
isAuthenticated() {
let profile = this.authProfile.getProfile();
var validToken = profile.token != "" && profile.token != null;
var isTokenExpired = this.isTokenExpired(profile);
return validToken && !isTokenExpired;
}
isAuthorized() {
let profile = this.authProfile.getProfile();
var validToken = profile.token != "" && profile.token != null;
var isTokenExpired = this.isTokenExpired(profile);
return validToken && !isTokenExpired;
}
isTokenExpired(profile: IProfile) {
var expiration = new Date(profile.expiration)
return expiration < new Date();
}
login(userName: string, password: string) {
if (!userName || !password) {
return;
}
let options = new RequestOptions(
{ headers: contentHeaders });
var credentials = {
grant_type: 'password',
email: userName,
password: <PASSWORD>
};
let url = this.commonService.getBaseUrl() + '/auth/token';
return this.http.post(url, credentials, options)
.map((response: Response) => {
var userProfile: IProfile = response.json();
this.authProfile.setProfile(userProfile);
return response.json();
}).catch(this.commonService.handleFullError);
}
register(userName: string, password: string, confirmPassword: string) {
if (!userName || !password) {
return;
}
let options = new RequestOptions(
{ headers: contentHeaders });
var credentials = {
email: userName,
password: <PASSWORD>,
confirmPassword: <PASSWORD>
};
let url = this.commonService.getBaseUrl() + '/auth/register';
return this.http.post(url, credentials, options)
.map((response: Response) => {
return response.json();
}).catch(this.commonService.handleFullError);
}
logout(): void {
this.authProfile.resetProfile();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace MasterWebApiCore.Server.Models
{
public class Batch
{
[Key]
public int Id { get; set; }
public string Batch_Name { get; set; }
public string Description { get; set; }
public Nullable<int> Course_Id { get; set; }
public string Del_Status { get; set; }
public string App_Status { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public Nullable<System.DateTime> EndDate { get; set; }
public Nullable<System.DateTime> Created_Date { get; set; }
public Nullable<int> Acedemic_Year { get; set; }
}
}
<file_sep>using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using MasterWebApiCore.Server.Repository;
using MasterWebApiCore.Server.Models;
using Microsoft.AspNetCore.Authorization;
namespace MasterWebApiCore.Server.Controllers
{
[Route("api/[controller]")]
// [Authorize]
public class CourseController : Controller
{
IDataAccess<Course, int> _CourseRepo;
public CourseController(IDataAccess<Course, int> b)
{
_CourseRepo = b;
}
// GET: api/values
[HttpGet]
public IEnumerable<Course> Get()
{
var Courses = _CourseRepo.Get();
return Courses;
}
// GET api/values/5
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var Course = _CourseRepo.Get(id);
if (Course == null)
{
return NotFound();
}
return Ok(Course);
}
// POST api/values
[HttpPost]
public IActionResult Post([FromBody]Course b)
{
int res = _CourseRepo.Add(b);
if (res != 0)
{
return Ok();
}
return Forbid();
}
// PUT api/values/5
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]Course b)
{
if (id == b.Id)
{
int res = _CourseRepo.Update(id,b);
if (res != 0)
{
return Ok(res);
}
return NotFound();
}
return NotFound();
}
// DELETE api/values/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
int res = _CourseRepo.Delete(id);
if (res != 0)
{
return Ok();
}
return NotFound();
}
}
}
<file_sep>using OA.Data;
using System;
using System.Collections.Generic;
using System.Text;
namespace IBusinessServices
{
public interface ICoursService
{
IEnumerable<Cours> GetCourss();
Cours GetCours(long id);
void InsertCours(Cours user);
void UpdateCours(Cours user);
void DeleteCours(long id);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MasterWebApiCore.Server.Models;
namespace MasterWebApiCore.Server.Repository
{
public class BatchRepository:IDataAccess<Batch,int>
{
SecurityContext ctx;
public BatchRepository(SecurityContext c)
{
ctx = c;
}
public int Add(Batch b)
{
ctx.Batchs.Add(b);
int res = ctx.SaveChanges();
return res;
}
public int Delete(int id)
{
int res = 0;
var Batch = ctx.Batchs.FirstOrDefault(b => b.Id == id);
if (Batch != null)
{
ctx.Batchs.Remove(Batch);
res = ctx.SaveChanges();
}
return res;
}
public Batch Get(int id)
{
var Batch = ctx.Batchs.FirstOrDefault(b => b.Id == id);
return Batch;
}
public IEnumerable<Batch> Get()
{
var Batchs = ctx.Batchs.ToList();
return Batchs;
}
public int Update(int id, Batch b)
{
int res = 0;
var Batch = ctx.Batchs.Find(id);
if (Batch != null)
{
Batch.Batch_Name = b.Batch_Name;
Batch.Description = b.Description;
res = ctx.SaveChanges();
}
return res;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace OA.Data
{
public class Cours: BaseEntity
{
public string Course_Name { get; set; }
public string Description { get; set; }
public string Del_Status { get; set; }
public string App_Status { get; set; }
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using MasterWebApiCore.Server.Models;
namespace MasterWebApiCore.Server.Repository
{
public class CourseRepository : IDataAccess<Course, int>
{
SecurityContext ctx;
public CourseRepository(SecurityContext c)
{
ctx = c;
}
public int Add(Course b)
{
ctx.Courses.Add(b);
int res = ctx.SaveChanges();
return res;
}
public int Delete(int id)
{
int res = 0;
var Course = ctx.Courses.FirstOrDefault(b => b.Id == id);
if (Course != null)
{
ctx.Courses.Remove(Course);
res = ctx.SaveChanges();
}
return res;
}
public Course Get(int id)
{
var Course = ctx.Courses.FirstOrDefault(b=>b.Id==id);
return Course;
}
public IEnumerable<Course> Get()
{
var Courses = ctx.Courses.ToList();
return Courses;
}
public int Update(int id,Course b)
{
int res = 0;
var Course = ctx.Courses.Find(id);
if (Course != null)
{
Course.Course_Name = b.Course_Name;
Course.Description = b.Description;
res = ctx.SaveChanges();
}
return res;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using OA.Data;
using OA.Repo;
namespace OA.Service
{
public class CoursService : ICoursService
{
private IRepository<Cours> coursRepository;
// private IRepository<Cours> userProfileRepository;
public CoursService(IRepository<Cours> coursRepository)
{
this.coursRepository = coursRepository;
}
public void DeleteCours(long id)
{
var objCor= coursRepository.Get(id);
coursRepository.Delete(objCor);
}
public Cours GetCours(long id)
{
return coursRepository.Get(id);
}
public IEnumerable<Cours> GetCourss()
{
return coursRepository.GetAll();
}
public void InsertCours(Cours course)
{
coursRepository.Insert(course);
}
public void UpdateCours(Cours course)
{
coursRepository.Update(course);
}
}
}
<file_sep>using OA.Data;
using OA.Repo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OA.Service
{
public class UserService:IUserService
{
private IRepository<Course> userRepository;
private IRepository<UserProfile> userProfileRepository;
public UserService(IRepository<Course> userRepository, IRepository<UserProfile> userProfileRepository)
{
this.userRepository = userRepository;
this.userProfileRepository = userProfileRepository;
}
public IEnumerable<Course> GetUsers()
{
return userRepository.GetAll();
}
public Course GetUser(long id)
{
return userRepository.Get(id);
}
public void InsertUser(Course user)
{
userRepository.Insert(user);
}
public void UpdateUser(Course user)
{
userRepository.Update(user);
}
public void DeleteUser(long id)
{
UserProfile userProfile = userProfileRepository.Get(id);
userProfileRepository.Remove(userProfile);
Course user = GetUser(id);
userRepository.Remove(user);
userRepository.SaveChanges();
}
}
}
<file_sep>using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace Token.WebApiCore.Server.Models
{
public class MyRole : IdentityRole
{
public string Description { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using OA.Service;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace MasterWebApiCore.Controllers
{
[Route("api/[controller]")]
public class UserController : Controller
{
private readonly IUserService userService;
private readonly IUserProfileService userProfileService;
public UserController(IUserService userService, IUserProfileService userProfileService)
{
this.userService = userService;
this.userProfileService = userProfileService;
}
[HttpGet]
public IEnumerable<string> Get()
{
var vr = userService.GetUsers().ToList();
// UserProfile userProfile = userProfileService.GetUserProfile(u.Id);
// var Courses = _CourseRepo.Get();
return new string[] { "value1", "value2" };
}
// public IActionResult Index()
//{
// return View();
//}
}
}
<file_sep><div class="panel panel-success">
<div class="panel-heading">
{{pageTitle}}
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4">
</div>
</div>
<div class="row">
<div class="col-md-6">
</div>
</div>
<div class="table-responsive">
<table class="table"
*ngIf="products && products.length">
<thead>
<tr>
<th>Batch_Id</th>
<th>Batch Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let product of products ">
<td>
{{product.Id}}
</td>
<td>
{{product.Batch_Name}}
</td>
<td>{{ product.Description }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div><file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using OA.Service;
using OA.Data;
using Microsoft.AspNetCore.Authorization;
namespace MasterWebApiCore.Controllers
{
[Route("api/[controller]")]
[Authorize]
public class CoursController : Controller
{
private readonly ICoursService coursService;
public CoursController(ICoursService coursService)
{
this.coursService = coursService;
}
[HttpGet]
public IEnumerable<Cours> Get()
{
return coursService.GetCourss().ToList();
// return vr.ToString();
// UserProfile userProfile = userProfileService.GetUserProfile(u.Id);
}
[HttpPost]
public IActionResult Post([FromBody]Cours b)
{
coursService.InsertCours(b);
return Ok(b);
// return Forbid();
}
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var Course = coursService.GetCours(id);
if (Course == null)
{
return NotFound();
}
return Ok(Course);
}
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]Cours b)
{
if (id == b.Id)
{
coursService.UpdateCours(b);
return Ok(b);
}
return NotFound();
}
// DELETE api/values/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
coursService.DeleteCours(id);
if (id != 0)
{
return Ok(id);
}
return NotFound();
}
}
}<file_sep>using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using MasterWebApiCore.Server.Models;
namespace MasterWebApiCore
{
public class SecurityContext : DbContext
{
public SecurityContext(DbContextOptions<SecurityContext> options)
: base(options)
{
}
public DbSet<Batch> Batchs { get; set; }
public DbSet<Course> Courses { get; set; }
}
}<file_sep>using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using MasterWebApiCore.Server.Repository;
using MasterWebApiCore.Server.Models;
using Microsoft.AspNetCore.Authorization;
namespace MasterWebApiCore.Server.Controllers
{
[Route("api/[controller]")]
[Authorize]
public class BatchController : Controller
{
IDataAccess<Batch, int> _BatchRepo;
public BatchController(IDataAccess<Batch, int> b)
{
_BatchRepo = b;
}
// GET: api/values
[HttpGet]
public IEnumerable<Batch> Get()
{
var Batchs = _BatchRepo.Get();
return Batchs;
}
// GET api/values/5
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var Batch = _BatchRepo.Get(id);
if (Batch == null)
{
return NotFound();
}
return Ok(Batch);
}
// POST api/values
[HttpPost]
public IActionResult Post([FromBody]Batch b)
{
int res = _BatchRepo.Add(b);
if (res != 0)
{
return Ok();
}
return Forbid();
}
// PUT api/values/5
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]Batch b)
{
if (id == b.Id)
{
int res = _BatchRepo.Update(id,b);
if (res != 0)
{
return Ok(res);
}
return NotFound();
}
return NotFound();
}
// DELETE api/values/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
int res = _BatchRepo.Delete(id);
if (res != 0)
{
return Ok();
}
return NotFound();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MasterWebApiCore.Server.Repository
{
public interface IDataAccess<TEntity, U> where TEntity : class
{
IEnumerable<TEntity> Get();
TEntity Get(U id);
int Add(TEntity b);
int Update(U id, TEntity b);
int Delete(U id);
}
}
| 74394025f6f458e81bc26a2361ea6408316c5513 | [
"Markdown",
"C#",
"HTML"
]
| 17 | C# | gyaneshwarkumar/sample-Code | 36c4610ebf3b1f93ec02bfe94e181148ede49135 | cd43a56de598430e6937ddf9deb6d31032e2cdd9 |
refs/heads/master | <file_sep>#!/bin/bash
# Kyligence Inc. License
source $(cd -P -- "$(dirname -- "$0")" && pwd -P)/header.sh
# source me
mkdir -p ${KYLIN_HOME}/var
hive_conf_dir="${KYLIN_HOME}/conf/kylin_hive_conf.xml"
hive_conf_prop="${KYLIN_HOME}/var/hive_props"
rm -rf ${hive_conf_prop}
export ENABLE_CHECK_ENV=false
${dir}/kylin.sh org.apache.kylin.tool.HiveConfigCLI ${hive_conf_dir} ${hive_conf_prop}
[[ 0 == $? ]] || quit "Can not parse xml file: ${hive_conf_dir}, please check it."
hive_conf_properties=`cat ${hive_conf_prop}`
<file_sep>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kylin.rest.msg;
/**
* Created by luwei on 17-4-12.
*/
public class Message {
private static Message instance = null;
protected Message() {
}
public static Message getInstance() {
if (instance == null) {
instance = new Message();
}
return instance;
}
// Cube
private final String CUBE_NOT_FOUND = "Cannot find cube '%s'.";
private final String SEG_NOT_FOUND = "Cannot find segment '%s'.";
private final String KAFKA_DEP_NOT_FOUND = "Could not find Kafka dependency.";
private final String BUILD_DRAFT_CUBE = "Could not build draft cube.";
private final String BUILD_BROKEN_CUBE = "Broken cube '%s' can't be built.";
private final String INCONSISTENT_CUBE_DESC_SIGNATURE = "Inconsistent cube desc signature for '%s', if it's right after an upgrade, please try 'Edit CubeDesc' to delete the 'signature' field. Or use 'bin/metastore.sh refresh-cube-signature' to batch refresh all cubes' signatures, then reload metadata to take effect.";
private final String DELETE_NOT_FIRST_LAST_SEG = "Cannot delete segment '%s' as it is neither the first nor the last segment.";
private final String DELETE_NOT_READY_SEG = "Cannot delete segment '%s' as its status is not READY. Discard the on-going job for it.";
private final String INVALID_BUILD_TYPE = "Invalid build type: '%s'.";
private final String NO_ACL_ENTRY = "There should have been an Acl entry for ObjectIdentity '%s'.";
private final String ACL_INFO_NOT_FOUND = "Unable to find ACL information for object identity '%s'.";
private final String ACL_DOMAIN_NOT_FOUND = "Acl domain object required.";
private final String PARENT_ACL_NOT_FOUND = "Parent acl required.";
private final String DISABLE_NOT_READY_CUBE= "Only ready cube can be disabled, status of '%s' is %s.";
private final String PURGE_NOT_DISABLED_CUBE = "Only disabled cube can be purged, status of '%s' is %s.";
private final String CLONE_BROKEN_CUBE = "Broken cube '%s' can't be cloned.";
private final String INVALID_CUBE_NAME = "Invalid Cube name '%s', only letters, numbers and underline supported.";
private final String CUBE_ALREADY_EXIST = "The cube named '%s' already exists.";
private final String CUBE_DESC_ALREADY_EXIST = "The cube desc named '%s' already exists.";
private final String BROKEN_CUBE_DESC = "Broken cube desc named '%s'.";
private final String ENABLE_NOT_DISABLED_CUBE= "Only disabled cube can be enabled, status of '%s' is %s.";
private final String NO_READY_SEGMENT = "Cube '%s' doesn't contain any READY segment.";
private final String ENABLE_WITH_RUNNING_JOB= "Enable is not allowed with a running job.";
private final String DISCARD_JOB_FIRST = "The cube '%s' has running or failed job, please discard it and try again.";
private final String IDENTITY_EXIST_CHILDREN = "Children exists for '%s'.";
private final String INVALID_CUBE_DEFINITION = "The cube definition is invalid.";
private final String EMPTY_CUBE_NAME = "Cube name should not be empty.";
private final String USE_DRAFT_MODEL = "Cannot use draft model '%s'.";
private final String UNEXPECTED_CUBE_DESC_STATUS = "CubeDesc status should not be %s.";
private final String EXPECTED_CUBE_DESC_STATUS = "CubeDesc status should be %s.";
private final String CUBE_DESC_RENAME = "Cube Desc renaming is not allowed: desc.getName(): '%s', cubeRequest.getCubeName(): '%s'.";
private final String INCONSISTENT_CUBE_DESC = "CubeDesc '%s' is inconsistent with existing. Try purge that cube first or avoid updating key cube desc fields.";
private final String UPDATE_CUBE_NO_RIGHT = "You don't have right to update this cube.";
private final String NOT_STREAMING_CUBE = "Cube '%s' is not a Streaming Cube.";
private final String NO_DRAFT_CUBE_TO_UPDATE = "Cube '%s' has no draft to update.";
private final String NON_DRAFT_CUBE_ALREADY_EXIST = "A non-draft cube with name '%s' already exists.";
private final String CUBE_RENAME = "Cube renaming is not allowed.";
private final String ORIGIN_CUBE_NOT_FOUND = "Origin cube not found.";
// Model
private final String INVALID_MODEL_DEFINITION = "The data model definition is invalid.";
private final String EMPTY_MODEL_NAME = "Model name should not be empty.";
private final String INVALID_MODEL_NAME = "Invalid Model name '%s', only letters, numbers and underline supported.";
private final String UNEXPECTED_MODEL_STATUS = "Model status should not be %s.";
private final String EXPECTED_MODEL_STATUS = "Model status should be %s.";
private final String DUPLICATE_MODEL_NAME = "Model name '%s' is duplicated, could not be created.";
private final String DROP_REFERENCED_MODEL = "Model is referenced by Cube '%s' , could not dropped";
private final String UPDATE_MODEL_KEY_FIELD = "Dimensions and measures in use and existing join tree cannot be modified.";
private final String BROKEN_MODEL_DESC = "Broken model desc named '%s'.";
private final String MODEL_NOT_FOUND = "Data Model with name '%s' not found.";
private final String EMPTY_PROJECT_NAME = "Project name should not be empty.";
private final String EMPTY_NEW_MODEL_NAME = "New model name should not be empty";
private final String UPDATE_MODEL_NO_RIGHT = "You don't have right to update this model.";
private final String NO_DRAFT_MODEL_TO_UPDATE = "Model '%s' has no draft to update.";
private final String NON_DRAFT_MODEL_ALREADY_EXIST = "A non-draft model with name '%s' already exists.";
private final String MODEL_RENAME = "Model renaming is not allowed.";
private final String ORIGIN_MODEL_NOT_FOUND = "Origin model not found.";
// Job
private final String ILLEGAL_TIME_FILTER = "Illegal timeFilter for job history: %s.";
private final String ILLEGAL_EXECUTABLE_STATE = "Illegal status: %s.";
private final String INVALID_JOB_STATE = "Invalid state: %s.";
private final String ILLEGAL_JOB_TYPE = "Illegal job type, id: %s.";
private final String INVALID_JOB_STEP_STATE = "Invalid state: %s.";
// Acl
private final String USER_NOT_EXIST = "User '%s' does not exist. Please make sure the user has logged in before";
// Project
private final String INVALID_PROJECT_NAME = "Invalid Project name '%s', only letters, numbers and underline supported.";
private final String PROJECT_ALREADY_EXIST = "The project named '%s' already exists.";
private final String PROJECT_NOT_FOUND = "Cannot find project '%s'.";
// Table
private final String HIVE_TABLE_NOT_FOUND = "Cannot find Hive table '%s'. ";
private final String TABLE_DESC_NOT_FOUND = "Cannot find table descriptor '%s'.";
private final String TABLE_IN_USE_BY_MODEL = "Table is already in use by models '%s'.";
// Cube Desc
private final String CUBE_DESC_NOT_FOUND = "Cannot find cube desc '%s'.";
// Streaming
private final String INVALID_TABLE_DESC_DEFINITION = "The TableDesc definition is invalid.";
private final String INVALID_STREAMING_CONFIG_DEFINITION = "The StreamingConfig definition is invalid.";
private final String INVALID_KAFKA_CONFIG_DEFINITION = "The KafkaConfig definition is invalid.";
private final String ADD_STREAMING_TABLE_FAIL = "Failed to add streaming table.";
private final String EMPTY_STREAMING_CONFIG_NAME = "StreamingConfig name should not be empty.";
private final String STREAMING_CONFIG_ALREADY_EXIST = "The streamingConfig named '%s' already exists.";
private final String SAVE_STREAMING_CONFIG_FAIL = "Failed to save StreamingConfig.";
private final String KAFKA_CONFIG_ALREADY_EXIST = "The kafkaConfig named '%s' already exists.";
private final String CREATE_KAFKA_CONFIG_FAIL = "StreamingConfig is created, but failed to create KafkaConfig.";
private final String SAVE_KAFKA_CONFIG_FAIL = "Failed to save KafkaConfig.";
private final String ROLLBACK_STREAMING_CONFIG_FAIL = "Action failed and failed to rollback the created streaming config.";
private final String ROLLBACK_KAFKA_CONFIG_FAIL = "Action failed and failed to rollback the created kafka config.";
private final String UPDATE_STREAMING_CONFIG_NO_RIGHT = "You don't have right to update this StreamingConfig.";
private final String UPDATE_KAFKA_CONFIG_NO_RIGHT = "You don't have right to update this KafkaConfig.";
private final String STREAMING_CONFIG_NOT_FOUND = "StreamingConfig with name '%s' not found.";
// Query
private final String QUERY_NOT_ALLOWED = "Query is not allowed in '%s' mode.";
private final String NOT_SUPPORTED_SQL = "Not Supported SQL.";
private final String TABLE_META_INCONSISTENT = "Table metadata inconsistent with JDBC meta.";
private final String COLUMN_META_INCONSISTENT = "Column metadata inconsistent with JDBC meta.";
// Access
private final String ACL_PERMISSION_REQUIRED = "Acl permission required.";
private final String SID_REQUIRED = "Sid required.";
private final String REVOKE_ADMIN_PERMISSION = "Can't revoke admin permission of owner.";
private final String ACE_ID_REQUIRED = "Ace id required.";
// Admin
private final String GET_ENV_CONFIG_FAIL = "Failed to get Kylin env Config.";
// User
private final String AUTH_INFO_NOT_FOUND = "Can not find authentication information.";
private final String USER_NOT_FOUND = "User '%s' not found.";
// Diagnosis
private final String DIAG_NOT_FOUND = "diag.sh not found at %s.";
private final String GENERATE_DIAG_PACKAGE_FAIL = "Failed to generate diagnosis package.";
private final String DIAG_PACKAGE_NOT_AVAILABLE = "Diagnosis package is not available in directory: %s.";
private final String DIAG_PACKAGE_NOT_FOUND = "Diagnosis package not found in directory: %s.";
// Encoding
private final String VALID_ENCODING_NOT_AVAILABLE = "can't provide valid encodings for datatype: %s.";
// ExternalFilter
private final String FILTER_ALREADY_EXIST = "The filter named '%s' already exists.";
private final String FILTER_NOT_FOUND = "The filter named '%s' does not exist.";
public String getCUBE_NOT_FOUND() {
return CUBE_NOT_FOUND;
}
public String getSEG_NOT_FOUND() {
return SEG_NOT_FOUND;
}
public String getKAFKA_DEP_NOT_FOUND() {
return KAFKA_DEP_NOT_FOUND;
}
public String getBUILD_DRAFT_CUBE() {
return BUILD_DRAFT_CUBE;
}
public String getBUILD_BROKEN_CUBE() {
return BUILD_BROKEN_CUBE;
}
public String getINCONSISTENT_CUBE_DESC_SIGNATURE() {
return INCONSISTENT_CUBE_DESC_SIGNATURE;
}
public String getDELETE_NOT_FIRST_LAST_SEG() {
return DELETE_NOT_FIRST_LAST_SEG;
}
public String getDELETE_NOT_READY_SEG() {
return DELETE_NOT_READY_SEG;
}
public String getINVALID_BUILD_TYPE() {
return INVALID_BUILD_TYPE;
}
public String getNO_ACL_ENTRY() {
return NO_ACL_ENTRY;
}
public String getACL_INFO_NOT_FOUND() {
return ACL_INFO_NOT_FOUND;
}
public String getACL_DOMAIN_NOT_FOUND() {
return ACL_DOMAIN_NOT_FOUND;
}
public String getPARENT_ACL_NOT_FOUND() {
return PARENT_ACL_NOT_FOUND;
}
public String getDISABLE_NOT_READY_CUBE() {
return DISABLE_NOT_READY_CUBE;
}
public String getPURGE_NOT_DISABLED_CUBE() {
return PURGE_NOT_DISABLED_CUBE;
}
public String getCLONE_BROKEN_CUBE() {
return CLONE_BROKEN_CUBE;
}
public String getINVALID_CUBE_NAME() {
return INVALID_CUBE_NAME;
}
public String getCUBE_ALREADY_EXIST() {
return CUBE_ALREADY_EXIST;
}
public String getCUBE_DESC_ALREADY_EXIST() {
return CUBE_DESC_ALREADY_EXIST;
}
public String getBROKEN_CUBE_DESC() {
return BROKEN_CUBE_DESC;
}
public String getENABLE_NOT_DISABLED_CUBE() {
return ENABLE_NOT_DISABLED_CUBE;
}
public String getNO_READY_SEGMENT() {
return NO_READY_SEGMENT;
}
public String getENABLE_WITH_RUNNING_JOB() {
return ENABLE_WITH_RUNNING_JOB;
}
public String getDISCARD_JOB_FIRST() {
return DISCARD_JOB_FIRST;
}
public String getIDENTITY_EXIST_CHILDREN() {
return IDENTITY_EXIST_CHILDREN;
}
public String getINVALID_CUBE_DEFINITION() {
return INVALID_CUBE_DEFINITION;
}
public String getEMPTY_CUBE_NAME() {
return EMPTY_CUBE_NAME;
}
public String getUSE_DRAFT_MODEL() {
return USE_DRAFT_MODEL;
}
public String getUNEXPECTED_CUBE_DESC_STATUS() {
return UNEXPECTED_CUBE_DESC_STATUS;
}
public String getEXPECTED_CUBE_DESC_STATUS() {
return EXPECTED_CUBE_DESC_STATUS;
}
public String getCUBE_DESC_RENAME() {
return CUBE_DESC_RENAME;
}
public String getINCONSISTENT_CUBE_DESC() {
return INCONSISTENT_CUBE_DESC;
}
public String getUPDATE_CUBE_NO_RIGHT() {
return UPDATE_CUBE_NO_RIGHT;
}
public String getNOT_STREAMING_CUBE() {
return NOT_STREAMING_CUBE;
}
public String getNO_DRAFT_CUBE_TO_UPDATE() {
return NO_DRAFT_CUBE_TO_UPDATE;
}
public String getNON_DRAFT_CUBE_ALREADY_EXIST() {
return NON_DRAFT_CUBE_ALREADY_EXIST;
}
public String getCUBE_RENAME() {
return CUBE_RENAME;
}
public String getORIGIN_CUBE_NOT_FOUND() {
return ORIGIN_CUBE_NOT_FOUND;
}
public String getINVALID_MODEL_DEFINITION() {
return INVALID_MODEL_DEFINITION;
}
public String getEMPTY_MODEL_NAME() {
return EMPTY_MODEL_NAME;
}
public String getINVALID_MODEL_NAME() {
return INVALID_MODEL_NAME;
}
public String getUNEXPECTED_MODEL_STATUS() {
return UNEXPECTED_MODEL_STATUS;
}
public String getEXPECTED_MODEL_STATUS() {
return EXPECTED_MODEL_STATUS;
}
public String getDUPLICATE_MODEL_NAME() {
return DUPLICATE_MODEL_NAME;
}
public String getDROP_REFERENCED_MODEL() {
return DROP_REFERENCED_MODEL;
}
public String getUPDATE_MODEL_KEY_FIELD() {
return UPDATE_MODEL_KEY_FIELD;
}
public String getBROKEN_MODEL_DESC() {
return BROKEN_MODEL_DESC;
}
public String getMODEL_NOT_FOUND() {
return MODEL_NOT_FOUND;
}
public String getEMPTY_PROJECT_NAME() {
return EMPTY_PROJECT_NAME;
}
public String getEMPTY_NEW_MODEL_NAME() {
return EMPTY_NEW_MODEL_NAME;
}
public String getUPDATE_MODEL_NO_RIGHT() {
return UPDATE_MODEL_NO_RIGHT;
}
public String getNO_DRAFT_MODEL_TO_UPDATE() {
return NO_DRAFT_MODEL_TO_UPDATE;
}
public String getNON_DRAFT_MODEL_ALREADY_EXIST() {
return NON_DRAFT_MODEL_ALREADY_EXIST;
}
public String getMODEL_RENAME() {
return MODEL_RENAME;
}
public String getORIGIN_MODEL_NOT_FOUND() {
return ORIGIN_MODEL_NOT_FOUND;
}
public String getILLEGAL_TIME_FILTER() {
return ILLEGAL_TIME_FILTER;
}
public String getILLEGAL_EXECUTABLE_STATE() {
return ILLEGAL_EXECUTABLE_STATE;
}
public String getINVALID_JOB_STATE() {
return INVALID_JOB_STATE;
}
public String getILLEGAL_JOB_TYPE() {
return ILLEGAL_JOB_TYPE;
}
public String getINVALID_JOB_STEP_STATE() {
return INVALID_JOB_STEP_STATE;
}
public String getUSER_NOT_EXIST() {
return USER_NOT_EXIST;
}
public String getINVALID_PROJECT_NAME() {
return INVALID_PROJECT_NAME;
}
public String getPROJECT_ALREADY_EXIST() {
return PROJECT_ALREADY_EXIST;
}
public String getPROJECT_NOT_FOUND() {
return PROJECT_NOT_FOUND;
}
public String getHIVE_TABLE_NOT_FOUND() {
return HIVE_TABLE_NOT_FOUND;
}
public String getTABLE_DESC_NOT_FOUND() {
return TABLE_DESC_NOT_FOUND;
}
public String getTABLE_IN_USE_BY_MODEL() {
return TABLE_IN_USE_BY_MODEL;
}
public String getCUBE_DESC_NOT_FOUND() {
return CUBE_DESC_NOT_FOUND;
}
public String getINVALID_TABLE_DESC_DEFINITION() {
return INVALID_TABLE_DESC_DEFINITION;
}
public String getINVALID_STREAMING_CONFIG_DEFINITION() {
return INVALID_STREAMING_CONFIG_DEFINITION;
}
public String getINVALID_KAFKA_CONFIG_DEFINITION() {
return INVALID_KAFKA_CONFIG_DEFINITION;
}
public String getADD_STREAMING_TABLE_FAIL() {
return ADD_STREAMING_TABLE_FAIL;
}
public String getEMPTY_STREAMING_CONFIG_NAME() {
return EMPTY_STREAMING_CONFIG_NAME;
}
public String getSTREAMING_CONFIG_ALREADY_EXIST() {
return STREAMING_CONFIG_ALREADY_EXIST;
}
public String getSAVE_STREAMING_CONFIG_FAIL() {
return SAVE_STREAMING_CONFIG_FAIL;
}
public String getKAFKA_CONFIG_ALREADY_EXIST() {
return KAFKA_CONFIG_ALREADY_EXIST;
}
public String getCREATE_KAFKA_CONFIG_FAIL() {
return CREATE_KAFKA_CONFIG_FAIL;
}
public String getSAVE_KAFKA_CONFIG_FAIL() {
return SAVE_KAFKA_CONFIG_FAIL;
}
public String getROLLBACK_STREAMING_CONFIG_FAIL() {
return ROLLBACK_STREAMING_CONFIG_FAIL;
}
public String getROLLBACK_KAFKA_CONFIG_FAIL() {
return ROLLBACK_KAFKA_CONFIG_FAIL;
}
public String getUPDATE_STREAMING_CONFIG_NO_RIGHT() {
return UPDATE_STREAMING_CONFIG_NO_RIGHT;
}
public String getUPDATE_KAFKA_CONFIG_NO_RIGHT() {
return UPDATE_KAFKA_CONFIG_NO_RIGHT;
}
public String getSTREAMING_CONFIG_NOT_FOUND() {
return STREAMING_CONFIG_NOT_FOUND;
}
public String getQUERY_NOT_ALLOWED() {
return QUERY_NOT_ALLOWED;
}
public String getNOT_SUPPORTED_SQL() {
return NOT_SUPPORTED_SQL;
}
public String getTABLE_META_INCONSISTENT() {
return TABLE_META_INCONSISTENT;
}
public String getCOLUMN_META_INCONSISTENT() {
return COLUMN_META_INCONSISTENT;
}
public String getACL_PERMISSION_REQUIRED() {
return ACL_PERMISSION_REQUIRED;
}
public String getSID_REQUIRED() {
return SID_REQUIRED;
}
public String getREVOKE_ADMIN_PERMISSION() {
return REVOKE_ADMIN_PERMISSION;
}
public String getACE_ID_REQUIRED() {
return ACE_ID_REQUIRED;
}
public String getGET_ENV_CONFIG_FAIL() {
return GET_ENV_CONFIG_FAIL;
}
public String getAUTH_INFO_NOT_FOUND() {
return AUTH_INFO_NOT_FOUND;
}
public String getUSER_NOT_FOUND() {
return USER_NOT_FOUND;
}
public String getDIAG_NOT_FOUND() {
return DIAG_NOT_FOUND;
}
public String getGENERATE_DIAG_PACKAGE_FAIL() {
return GENERATE_DIAG_PACKAGE_FAIL;
}
public String getDIAG_PACKAGE_NOT_AVAILABLE() {
return DIAG_PACKAGE_NOT_AVAILABLE;
}
public String getDIAG_PACKAGE_NOT_FOUND() {
return DIAG_PACKAGE_NOT_FOUND;
}
public String getVALID_ENCODING_NOT_AVAILABLE() {
return VALID_ENCODING_NOT_AVAILABLE;
}
public String getFILTER_ALREADY_EXIST() {
return FILTER_ALREADY_EXIST;
}
public String getFILTER_NOT_FOUND() {
return FILTER_NOT_FOUND;
}
} | 90114a1d20e5224088e29b9afae5af2bb62e55d0 | [
"Java",
"Shell"
]
| 2 | Shell | jtoka/kylin | 6914f3f409372dc1fd11cd140984aa67d31e5ac4 | 3b93d596ac6a47b2fa51f9666e02155b8f03e34c |
refs/heads/master | <repo_name>msgithub-hub/QHdemo1<file_sep>/demo1/src/api/user.js
import { axios } from 'castle-haozijunqaq-uni-utils'
/**
* PHP服务登录
* @param code 小程序登录code
* @returns {*}
*/
/**获取列表**/
export function getNewsList() {
return axios.postData('/test/getUserInfo');
}
<file_sep>/demo1/src/property.js
export default {
BASE_URL: 'https://easydoc.top/mock/ft9mJNIn',
} | ebfe02736537d89ca029a8dc2ac4f84a885a5934 | [
"JavaScript"
]
| 2 | JavaScript | msgithub-hub/QHdemo1 | 8e4bc64eae01eae0f090db0fe494e796b12b8091 | 8fcead8252083e1b038fde8868a11693e2307247 |
refs/heads/master | <repo_name>coinkite/coinkite-php<file_sep>/lib/CKException.php
<?php
class CKException extends Exception {
function __construct($code, $msg) {
$this->code = $code;
$this->msg = $msg;
error_log("[$code] " . $msg);
}
function __tostring() {
return $this->printMessage();
}
function printMessage() {
$code = $this->code;
$msg = $this->msg;
$msg_array = json_decode($msg, true);
switch ($code){
case 400:
$msg_text = "[$code] \"" . $msg_array['help_msg'] . '"';
break;
case 404:
$msg_text = "[$code] \"Problem with HTTPS connection to Coinkite server. " .
$msg_array['message'] . '"';
break;
case 504:
$msg_text = "[$code] \"A problem with the CF to Coinkite connection\"";
break;
default:
$msg_text = "[$code] \"" . $msg_array['message'] . '"';
}
return $msg_text;
}
}
<file_sep>/examples/example2.php
<?php
require('../lib/CKRequestor.php');
// Create Coinkite API requestor object
$CK_API = new CKRequestor('this-is-my-key', 'this-is-my-secret');
/* First, send the transaction request to the API.
This will send 0.1 BTC from the account called 'MyBTC' to dest.
This example sends an array of arguments to the put function,
note that a JSON string could also be sent */
$ck_send = $CK_API->put('/v1/new/send', array('account'=>'MyBTC',
'amount'=>0.1,
'dest'=>'bitcoinAddress'));
// Now authorize the payment to be sent
$ck_auth = $CK_API->put($ck_send['next_step']);
?>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>
Coinkite PHP API Example #2
</h1>
<h2>
This example creates and sends a transaction.<br/>
The HTML below summarizes the result with a refnum.
</h2>
<p>
[<?php echo $ck_auth['result']['CK_refnum']; ?>]
<?php echo $ck_auth['result']['amount']['pretty']; ?>
sent to address:
<?php echo $ck_auth['result']['destination']; ?>
</p>
</body>
</html>
<file_sep>/examples/sign.php
<?php
date_default_timezone_set('UTC');
function sign($endpoint, $force_ts=false)
{
# Replace these values.
$API_KEY = 'this-is-my-key';
$API_SECRET = 'this-is-my-secret';
if($force_ts) {
$ts = $force_ts;
} else {
$now = new DateTime();
$ts = $now->format(DateTime::ISO8601);
}
$data = $endpoint . '|' . $ts;
$hm = hash_hmac('sha256', $data, $API_SECRET);
return array($hm, $ts);
}
print_r(sign('/example/endpoint', '2014-06-03T17:48:47.774453'));
#print_r(sign('/example/endpoint'));
?>
<file_sep>/lib/CKRequestor.php
<?php
require_once('CKException.php');
date_default_timezone_set('UTC');
class CKRequestor {
public function __construct($api_key=null, $api_secret=null, $host=null, $client=null) {
// Provide API Key and secret
$this->api_key = $api_key;
$this->api_secret = $api_secret;
if (!$this->host = $host) {
$this->host = 'https://api.coinkite.com';
}
$this->client = $client;
}
public function request($method, $endpt, $args=null, $headers=null) {
/*
Low level method to perform API request: provide HTTP method and endpoint
Optional arguments:
$args = JSON document or an array of arguments
$headers = Extra headers to put on request, must be an array of headers
*/
$url = $this->host . $endpt;
$endpt = parse_url($url, PHP_URL_PATH);
$data = null;
if (substr($endpt, 0, 7) == '/public') {
$auth_headers = array();
} else {
$auth_headers = $this->auth_headers($endpt);
}
if (is_array($headers)) {
$hdrs = array_merge($auth_headers, $headers);
} else {
$hdrs = $auth_headers;
}
if (isset($args)) {
if (is_array($args)) {
$data = $args;
} else {
$data = json_decode($args, true);
}
if ($data && $method == 'GET') {
$url .= '?' . http_build_query($data);
}
}
while (true) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $hdrs);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/data/ca-certificates.crt');
$body_json = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status == 504) {
throw new CKException($status, $body_json);
}
$body = json_decode($body_json, true);
curl_close($curl);
if ($status == 429 && $body['wait_time']) {
sleep($body['wait_time']);
} else {
break;
}
}
if ($status != 200) {
throw new CKException($status, $body_json);
}
return $body;
}
private function make_signature($endpoint, $force_ts=false) {
// Pick a timestamp and perform the signature required
if ($force_ts) {
$ts = $force_ts;
} else {
$now = new DateTime();
$ts = $now->format(DateTime::ISO8601);
}
$data = $endpoint . '|' . $ts;
$hm = hash_hmac('sha256', $data, $this->api_secret);
return array($hm, $ts);
}
private function auth_headers($endpoint, $force_ts=false) {
// Make authorization headers that are needed to access indicated endpoint
if (!$this->api_key) {
throw new CKException(0, '{"message":"API Key for Coinkite is required"}');
}
if (!$this->api_secret) {
throw new CKException(0, '{"message":"API Secret for Coinkite is required"}');
}
$sig_ts = $this->make_signature($endpoint, $force_ts);
return array('X-CK-Key: ' . $this->api_key,
'X-CK-Timestamp: ' . $sig_ts[1],
'X-CK-Sign: ' . $sig_ts[0]);
}
public function get($endpt, $args=null) {
// Perform a GET on indicated resource (endpoint) with optional arguments
return $this->request('GET', $endpt, $args);
}
public function put($endpt, $args=null) {
// Perform a PUT on indicated resource (endpoint) with optional arguments
return $this->request('PUT', $endpt, $args);
}
public function get_iter($endpoint, $offset=0, $limit=null, $batch_size=25, $safety_limit=500, $args=null) {
// Return a Generator that will iterate over all results, regardless of how many
while(true) {
if ($limit && $limit < $batch_size) {
$batch_size = $limit;
}
if (isset($args)) {
if (is_array($args)) {
$data = $args;
} else {
$data = json_decode($args, true);
}
}
$data['offset'] = $offset;
$data['limit'] = $batch_size;
$rv = $this->get($endpoint, $data);
$here = $rv['paging']['count_here'];
$total = $rv['paging']['total_count'];
if ($total > $safety_limit) {
throw new CKException(0, "{\"message\":\"Too many results ($total); consider another approach\"}");
}
if (!$here) {
return;
}
foreach ($rv['results'] as $i) {
yield $i;
}
$offset += $here;
if ($limit) {
$limit -= $here;
if ($limit <= 0) {
return;
}
}
}
}
public function check_myself() {
return $this->request('GET', '/v1/my/self');
}
public function get_detail($refnum) {
// Get detailed-view of any CK object by reference number
$data = $this->request('GET', '/v1/detail/' . $refnum);
return $data['detail'];
}
public function get_accounts() {
// Get a list of accounts, doesn't include balances
$data = $this->request('GET', '/v1/my/accounts');
return $data['results'];
}
public function get_balance($account) {
// Get account details, including balance, by account name, number or refnum
$data = $this->request('GET', '/v1/account/' . $account);
return $data['account'];
}
public function get_list($what, $account=null, $just_count=false, $args=null) {
/*
Get a list of objects, using /v1/list/WHAT endpoints, where WHAT is:
activity
credits
debits
events
notifications
receives
requests
sends
sweeps
transfers
unauth_sends
watching
*/
$ep = '/v1/list/' . $what;
if (isset($account)) {
$args['account'] = $account;
}
if ($just_count) {
$args['limit'] = 0;
$data = $this->get($ep, $args);
return $data['paging']['total_count'];
}
return $this->get_iter($ep);
}
}
<file_sep>/README.md
# Coinkite API Code for PHP
[Learn more about Coinkite's API here](https://docs.coinkite.com/)
and visit the [Coinkite Main Site](https://coinkite.com/) to open your
account today!
## Introduction
Every request made to the Coinkite API requires three special header
lines. This code can generate the timestamp and signature value
required for 2 of those 3 headers. The remaining header is just
the API key itself.
Header lines you need:
X-CK-Key: <KEY>
X-CK-Timestamp: 2014-06-23T03:10:04.905376
X-CK-Sign: 0aa7755aaa45189a98a5a8a887a564aa55aa5aa4aa7a98aa2858aaa60a5a56aa
## How to Install
Replace the two values shown here.
````php
$API_KEY = 'this-is-my-key';
$API_SECRET = 'this-is-my-secret';
````
The keys you need can be created on
[Coinkite.com under Merchant / API]([https://coinkite.com/merchant/api).
## More about Coinkite
_Join The Most Powerful Bitcoin Platform_
Coinkite is the leading [bitcoin wallet](https://coinkite.com/faq/features) with
[multi-signature](https://coinkite.com/faq/multisig),
[bank-grade security](https://coinkite.com/faq/security),
[developer's API](https://coinkite.com/faq/developers) and [hardcore privacy](https://coinkite.com/privacy).
[Get Your Account Today!](https://coinkite.com/)
<file_sep>/examples/example1.php
<?php
require('../lib/CKRequestor.php');
// Create Coinkite API requestor object
$CK_API = new CKRequestor();
// Get rates from '/public/rates' endpoint
$rates = $CK_API->get('/public/rates');
?>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>
Coinkite PHP API Example #1
</h1>
<h2>
This example uses the '/public/rates' API endpoint to get market rates for
various currency pairs.<br/>
Note that no API keys are not required for this.
</h2>
<p>
The current Bitcoin (<?php echo $rates['currencies']['BTC']['sign']; ?>)
price in Canadian dollars is:
<?php echo $rates['rates']['BTC']['CAD']['pretty']; ?>
</p>
<p>
The current Litecoin (<?php echo $rates['currencies']['LTC']['sign']; ?>)
price in US dollars is:
<?php echo $rates['rates']['LTC']['USD']['pretty']; ?>
</p>
<p>
The current Blackcoin (<?php echo $rates['currencies']['BLK']['sign']; ?>)
price in Japanese Yen is:
<?php echo $rates['rates']['BLK']['JPY']['pretty']; ?>
</p>
</body>
</html>
| d62265d6658a93c288877c17b395faa4c79f19b1 | [
"Markdown",
"PHP"
]
| 6 | PHP | coinkite/coinkite-php | 2057ad47cc5a741a938dab53586bd4c2402526bd | d42ee56c8c6a9b4f7c3d68297de651190c497869 |
refs/heads/master | <repo_name>baniainurramdlan/demosiin<file_sep>/basic/views/budget/grafik-line.php
<?php
use yii\helpers\Html;
use sjaakp\gcharts\LineChart;
/* @var $this yii\web\View */
/* @var $searchModel app\models\BudgetSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'SIIN - Grafik Line';
//$this->params['breadcrumbs'][] = $this->title;
?>
<div class="budget-index">
<!-- <h1><?= Html::encode($this->title) ?></h1> -->
<?php //echo $this->render('_search', ['model' => $searchModel]); ?>
<!-- <?= Html::a('Create Budget', ['create'], ['class' => 'btn btn-success']) ?> -->
<div class="row" style="padding-top: 20px; padding-bottom: 20px;">
<div class="container">
<div class="col-md-4">
Dana : Rp. 10.000.000 <a type="button" class="btn btn-primary btn-sm" href="<?php echo \yii\helpers\Url::to(['/budget/list']); ?>"><span class="glyphicon glyphicon-stats" aria-hidden="true"> </span>List</a>
</div>
<div class="col-md-4">
<?php
echo Html::dropDownList('listname', null, [''=>'','totalfund'=>'Total Funding', 'cumulativefund'=>'Cumulative Funding'], ['class' => 'form-control', 'onchange'=>'javascript:pindah()','id'=>'idlistname']);
?>
<script>
function pindah() {
var e = $("#idlistname").val();
if (e == 'totalfund') {
window.location.href = "<?php echo \yii\helpers\Url::to(['/budget/grafik']); ?>";
} else if (e == 'cumulativefund') {
window.location.href = "<?php echo \yii\helpers\Url::to(['/budget/grafik-line']); ?>";
}
}
</script>
</div>
<div class="col-md-4"></div>
</div>
</div>
<br />
<div class="container">
<?= LineChart::widget([
'height' => '400px',
'dataProvider' => $dataProvider,
'columns' => [
'tahun:string',
'APBN',
'apbd',
'ln'
],
'options' => [
'title' => 'Cumulative Funding',
],
]) ?>
</div>
</div>
<file_sep>/basic/views/lembaga/departemen.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\BudgetSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'SIIN - Lembaga';
//$this->params['breadcrumbs'][] = $this->title;
?>
<div class="lembaga-index">
<!-- <h1><?= Html::encode($this->title) ?></h1> -->
<?php //echo $this->render('_search', ['model' => $searchModel]); ?>
<!-- <?= Html::a('Create Budget', ['create'], ['class' => 'btn btn-success']) ?> -->
<div class="container">
<h1><?php echo $model->{'nama'}; ?></h1>
<br />
<div class="col-md-12">
<div class="well">
<?php echo Html::a('<span class="glyphicon glyphicon-arrow-left" aria-hidden="true"></span> Semua Departemen', ['/lembaga/list', 'id' => $id_lembaga]); ?>
<?php echo " | " . $model->{'jumlah_peneliti'} . " Peneliti | " . $model->{'jumlah_dokumen'} . " Dokumen"; ?>
</div>
<?php echo $this->render('//peneliti/_search', ['model' => $searchModel]); ?>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
[
'label' => 'nama',
'format' => 'raw',
'value' => function ($data) {
return Html::a($data->nama, ['sdm/profile', 'id' => 3]);
},
],
'jumlah_paten',
'jumlah_paper',
//'id_departemen',
//['class' => 'yii\grid\ActionColumn'],
],
]);
?>
</div>
</div>
</div>
<file_sep>/basic/models/Budget.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "budget".
*
* @property integer $id
* @property double $dana
* @property string $sumber
* @property string $lembaga
* @property string $subject
* @property integer $tahun
*/
class Budget extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'budget';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['dana', 'sumber', 'lembaga', 'subject', 'tahun'], 'required'],
[['dana'], 'number'],
[['tahun'], 'integer'],
[['sumber', 'lembaga', 'subject'], 'string', 'max' => 100],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'dana' => 'Dana',
'sumber' => 'Sumber',
'lembaga' => 'Lembaga',
'subject' => 'Subject',
'tahun' => 'Tahun',
];
}
}
<file_sep>/basic/views/site/about.php
<?php
/* @var $this yii\web\View */
use yii\helpers\Html;
$this->title = 'About';
//$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-about">
<div class="row">
<div class="container">
<div class="col-md-12">
<h1>Sistem Informasi Iptek Nasional</h1>
<!--
<p>
This is the About page. You may modify the following file to customize its content:
</p>
<code><?= __FILE__ ?></code>
-->
<p>
Data dan informasi iptek untuk pengawasan dan perencanaan pembangunan iptek serta dapat dibandingkan dengan negara lain perlu gambaran kondisi iptek secara nasional.
</p>
<p>
Data dan informasi iptek yang memenuhi kebutuhan informasi pada:
</p>
<ul>
<li>UU No. 18 tahun 2002,</li>
<li>RUU pengganti UU No. 18 tahun 2002,</li>
<li>Renstra Kemenristekdikti tahun 2015-2019,</li>
<li>Frascatti Manual 2015.</li>
</ul>
</div>
</div>
</div>
</div>
<file_sep>/basic/views/layouts/main_admin.php
<?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AdminAsset;
AdminAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<?php $this->beginBody() ?>
<div class="wrapper">
<header class="main-header">
<a href="<?php echo \yii\helpers\Url::to(['/admin']); ?>" class="logo">
<span class="logo-mini"><b>S</b>IIN</span>
<span class="logo-lg"><b></b>SIIN (logo)</span>
</a>
<nav class="navbar navbar-static-top">
<a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<li class="messages-menu">
<a href="<?php echo \yii\helpers\Url::to(['/site/index']); ?>" class="">
<i class="fa fa-home"></i>
<span class="">Home</span>
</a>
</li>
<!-- Notifications: style can be found in dropdown.less -->
<li class="messages-menu">
<a href="<?php echo \yii\helpers\Url::to(['/site/about']); ?>" class="">
<i class="fa fa-black-tie"></i>
<span class="">About Us</span>
</a>
</li>
<li class="messages-menu">
<a href="<?php echo \yii\helpers\Url::to(['/site/contact']); ?>" class="">
<i class="fa fa-address-book-o"></i>
<span class="">Contact</span>
</a>
</li>
<?php if (Yii::$app->user->isGuest): ?>
<li class="messages-menu">
<a href="<?php echo \yii\helpers\Url::to(['/admin/index']); ?>" class="">
<i class="fa fa-user-circle"></i>
<span class="">Login</span>
</a>
</li>
<?php else: ?>
<li class="messages-menu">
<a href="<?php echo \yii\helpers\Url::to(['/site/logout']); ?>" class="">
<i class="fa fa-user-circle"></i>
<span class="">Logout (<?php echo Yii::$app->user->identity->username; ?>)</span>
</a>
</li>
<?php endif; ?>
</ul>
</div>
</nav>
</header>
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image">
<!-- <img src="img/Koala.jpg" class="img-circle" alt="User Image"> -->
<?= Html::img("@web/img/Koala.jpg", ['alt'=>'User Image', 'class'=>'img-circle', ]);?>
</div>
<div class="pull-left info">
<p>Admin SIIN</p>
<a href="#"><i class="fa fa-circle text-success"></i> Online</a>
</div>
</div>
<!-- search form -->
<form action="#" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
<!-- /.search form -->
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu">
<li class="header">MAIN NAVIGATION</li>
<li class="treeview">
<li>
<a href="<?php echo \yii\helpers\Url::to(['/admin']); ?>">
<i class="fa fa-home"></i> <span>Dashboard</span>
<span class="pull-right-container">
<small class="label pull-right bg-green">new</small>
</span>
</a>
</li>
<li>
<a href="<?php echo \yii\helpers\Url::to(['/admin-sdm']); ?>">
<i class="fa fa-user"></i> <span>SDM</span>
<span class="pull-right-container">
<small class="label pull-right bg-green">new</small>
</span>
</a>
</li>
<li>
<a href="<?php echo \yii\helpers\Url::to(['/admin-lembaga']); ?>">
<i class="fa fa-university"></i> <span>Lembaga</span>
<span class="pull-right-container">
<small class="label pull-right bg-green"></small>
</span>
</a>
</li>
<li>
<a href="<?php echo \yii\helpers\Url::to(['/admin-paper']); ?>">
<i class="fa fa-file-text"></i> <span>Output</span>
<span class="pull-right-container">
<small class="label pull-right bg-green"></small>
</span>
</a>
</li>
<li>
<a href="<?php echo \yii\helpers\Url::to(['/admin-paten']); ?>">
<i class="fa fa-calendar-plus-o"></i> <span>Aktivitas</span>
<span class="pull-right-container">
<small class="label pull-right bg-green"></small>
</span>
</a>
</li>
<li>
<a href="<?php echo \yii\helpers\Url::to(['/user-manajemen']); ?>">
<i class="fa fa-users"></i> <span>User Management</span>
<span class="pull-right-container">
<small class="label pull-right bg-green"></small>
</span>
</a>
</li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<div class="content-wrapper">
<?= $content ?>
</div>
</div>
<!-- <footer class="footer">
<div class="container">
<p class="pull-left">© My Company <?= date('Y') ?></p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer> -->
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
<file_sep>/basic/modules/v1/models/Sdm.php
<?php
namespace app\modules\v1\models;
use Yii;
/**
* This is the model class for table "sdm".
*
* @property integer $id
* @property string $nama
* @property string $gelar
* @property string $lembaga
* @property string $bidang_ilmu
*/
class Sdm extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'sdm';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['nama', 'gelar', 'lembaga', 'bidang_ilmu'], 'required'],
[['nama', 'lembaga', 'bidang_ilmu'], 'string', 'max' => 100],
[['gelar'], 'string', 'max' => 50],
];
}
public static function primaryKey()
{
return ['id'];
}
}
<file_sep>/basic/views/budget/_search.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\BudgetSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="budget-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<!--<?= $form->field($model, 'id') ?> -->
<div class="col-md-3">
<?= $form->field($model, 'dana') ->dropDownList ([
''=>''
,'10000000'=>'10.000.000'
,'20000000'=>'20.000.000'
,'30000000'=>'30.000.000'
,'40000000'=>'40.000.000'
,'50000000'=>'50.000.000'
,'60000000'=>'60.000.000'
])?>
</div>
<div class="col-md-3">
<?= $form->field($model, 'sumber') ->dropDownList ([
''=>''
,'apbd'=>'APBN'
,'apbn'=>'APBN'
,'ln'=>'LN'
])?>
</div>
<div class="col-md-3">
<?= $form->field($model, 'lembaga') ->dropDownList ([
''=>''
,'bpbd'=>'BPBD'
,'ristekdikti'=>'RISTEKDIKTI'
,'unces'=>'UNCES'
])?>
</div>
<div class="col-md-3">
<?= $form->field($model, 'subject') ->dropDownList ([
''=>''
,'bioteknologi'=>'Bioteknologi'
,'biofuel'=>'Biofuel'
,'meteorologi'=>'Meteorologi'
])?>
</div>
<!--
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
-->
<?php ActiveForm::end(); ?>
</div>
<file_sep>/basic/models/Paper.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "paper".
*
* @property integer $id
* @property string $nama
* @property string $lembaga
* @property string $bidang_ilmu
*/
class Paper extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'paper';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['nama', 'lembaga', 'bidang_ilmu'], 'required'],
[['nama', 'lembaga', 'bidang_ilmu'], 'string', 'max' => 100],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'nama' => 'Nama',
'lembaga' => 'Lembaga',
'bidang_ilmu' => 'Bidang Ilmu',
];
}
}
<file_sep>/basic/views/lembaga/list.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\BudgetSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'SIIN - Lembaga';
//$this->params['breadcrumbs'][] = $this->title;
?>
<div class="lembaga-index">
<!-- <h1><?= Html::encode($this->title) ?></h1> -->
<?php //echo $this->render('_search', ['model' => $searchModel]); ?>
<!-- <?= Html::a('Create Budget', ['create'], ['class' => 'btn btn-success']) ?> -->
<div class="container">
<h1><?php echo $model -> {'nama'}; ?></h1>
<h4><?php echo "<a href=".$model -> {'website'}.">" .$model -> {'website'}."</a>"; ?></h4>
<br />
<div class="col-md-12">
<div class="well">
<?php echo $model -> {'jumlah_departemen'} . " Departemen"; ?>
</div>
<?php echo $this->render('//departemen/_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
[
'label'=>'nama',
'format' => 'raw',
'value'=>function ($data) {
return Html::a($data->nama,['/lembaga/departemen','id_lembaga'=>$data->id_lembaga,'id_departemen'=>$data->id]);
},
],
'jumlah_peneliti',
'jumlah_dokumen',
//'id_lembaga',
//['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
</div>
</div>
<file_sep>/basic/views/sdm/list.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\BudgetSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'SIIN - List SDM';
//$this->params['breadcrumbs'][] = $this->title;
?>
<div class="sdm-index">
<!-- <h1><?= Html::encode($this->title) ?></h1> -->
<div class="row" style="padding-top: 20px; padding-bottom: 20px;">
<div class="col-sm-12 col-centered">
<div class="container">
<?php echo $this->render('_search', ['model' => $searchModel]); ?>
</div>
</div>
</div>
<p>
<!-- <?= Html::a('Create Budget', ['create'], ['class' => 'btn btn-success']) ?> -->
</p>
<br />
<div class="container">
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
//'nama',
[
'label'=>'nama',
'format' => 'raw',
'value'=>function ($data) {
return Html::a($data->nama,['sdm/profile','id'=>$data->id]);
},
],
'gelar',
'lembaga',
'bidang_ilmu',
//['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
</div>
<file_sep>/basic/controllers/SiteController.php
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use dosamigos\google\maps\LatLng;
use dosamigos\google\maps\services\DirectionsWayPoint;
use dosamigos\google\maps\services\TravelMode;
use dosamigos\google\maps\overlays\PolylineOptions;
use dosamigos\google\maps\services\DirectionsRenderer;
use dosamigos\google\maps\services\DirectionsService;
use dosamigos\google\maps\overlays\InfoWindow;
use dosamigos\google\maps\overlays\Marker;
use dosamigos\google\maps\Map;
use dosamigos\google\maps\services\DirectionsRequest;
use dosamigos\google\maps\overlays\Polygon;
use dosamigos\google\maps\layers\BicyclingLayer;
class SiteController extends Controller {
/**
* @inheritdoc
*/
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['get'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions() {
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* @return string
*/
public function actionIndex() {
if (!Yii::$app->user->isGuest){
$this->redirect(['/admin-sdm/index']);
}
$coord = new LatLng(['lat' => -2.245933, 'lng' => 119.481006 ]);
$map = new Map([
'center' => $coord,
'zoom' => 5,
'scrollwheel' => false,
'mapTypeControl' => false,
'scaleControl' => false,
'draggable' => true,
]);
$map->width = '100%';
$map->height = 400;
return $this->render('index',[
'map'=>$map,
]);
}
/**
* Login action.
*
* @return string
*/
public function actionLogin() {
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
/**
* Logout action.
*
* @return string
*/
public function actionLogout() {
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* @return string
*/
public function actionContact() {
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
return $this->render('contact', [
'model' => $model,
]);
}
/**
* Displays about page.
*
* @return string
*/
public function actionAbout() {
return $this->render('about');
}
}
<file_sep>/basic/models/Departemen.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "departemen".
*
* @property integer $id
* @property string $nama
* @property integer $jumlah_peneliti
* @property integer $jumlah_dokumen
* @property integer $id_lembaga
*
* @property Lembaga $idLembaga
* @property Peneliti[] $penelitis
*/
class Departemen extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'departemen';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['nama', 'jumlah_peneliti', 'jumlah_dokumen', 'id_lembaga'], 'required'],
[['jumlah_peneliti', 'jumlah_dokumen', 'id_lembaga'], 'integer'],
[['nama'], 'string', 'max' => 100],
[['id_lembaga'], 'exist', 'skipOnError' => true, 'targetClass' => Lembaga::className(), 'targetAttribute' => ['id_lembaga' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'nama' => 'Nama',
'jumlah_peneliti' => 'Jumlah Peneliti',
'jumlah_dokumen' => 'Jumlah Dokumen',
'id_lembaga' => 'Id Lembaga',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getIdLembaga()
{
return $this->hasOne(Lembaga::className(), ['id' => 'id_lembaga']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPenelitis()
{
return $this->hasMany(Peneliti::className(), ['id_departemen' => 'id']);
}
}
<file_sep>/basic/views/layouts/main.php
<?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<?php $this->beginBody() ?>
<div class="wrapper">
<header class="main-header">
<a href="<?php echo \yii\helpers\Url::to(['/site/index']); ?>" class="logo">
<span class="logo-mini"><b>S</b>IIN</span>
<span class="logo-lg"><b></b>SIIN (logo)</span>
</a>
<nav class="navbar navbar-static-top">
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<li class="messages-menu">
<a href="<?php echo \yii\helpers\Url::to(['/site/index']); ?>" class="">
<i class="fa fa-home"></i>
<span class="">Home</span>
</a>
</li>
<!-- Notifications: style can be found in dropdown.less -->
<li class="messages-menu">
<a href="<?php echo \yii\helpers\Url::to(['/site/about']); ?>" class="">
<i class="fa fa-black-tie"></i>
<span class="">About Us</span>
</a>
</li>
<li class="messages-menu">
<a href="<?php echo \yii\helpers\Url::to(['/site/contact']); ?>" class="">
<i class="fa fa-address-book-o"></i>
<span class="">Contact</span>
</a>
</li>
<?php if (Yii::$app->user->isGuest): ?>
<li class="messages-menu">
<a href="<?php echo \yii\helpers\Url::to(['/admin/index']); ?>" class="">
<i class="fa fa-user-circle"></i>
<span class="">Login</span>
</a>
</li>
<?php else: ?>
<li class="messages-menu">
<a href="<?php echo \yii\helpers\Url::to(['/site/logout']); ?>" class="">
<i class="fa fa-user-circle"></i>
<span class="">Logout (<?php echo Yii::$app->user->identity->username; ?>)</span>
</a>
</li>
<?php endif; ?>
</ul>
</div>
</nav>
</header>
<div class="" style="background-color: #ecf0f1; min-height: 550px;">
<?= $content ?>
</div>
</div>
<footer class="footer navbar-fixed-bottom">
<div class="container">
<p class="pull-left">© Ristekdikti <?= date('Y') ?></p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
<file_sep>/basic/views/paper/index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\PaperSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Papers';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="paper-index">
<div class="row" style="padding-top: 20px; padding-bottom: 20px;">
<div class="container">
<p>
<a type="button" class="btn btn-primary" href="<?php echo \yii\helpers\Url::to(['/paper']); ?>" disabled><span class="glyphicon glyphicon-paper" aria-hidden="true"></span>Paper</a>
| <a type="button" class="btn btn-primary" href="<?php echo \yii\helpers\Url::to(['/paten']); ?>"><span class="glyphicon glyphicon-block" aria-hidden="true"></span>Paten</a>
</p>
<br />
<p>
<?php echo $this->render('_search', ['model' => $searchModel]); ?>
</p>
</div>
</div>
<div class="row">
<div class="container">
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
'nama',
'lembaga',
'bidang_ilmu',
//['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
</div>
</div>
<file_sep>/basic/models/Lembaga.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "lembaga".
*
* @property integer $id
* @property string $nama
* @property string $website
* @property integer $jumlah_departemen
*
* @property Departemen[] $departemens
*/
class Lembaga extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'lembaga';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['nama', 'website', 'jumlah_departemen'], 'required'],
[['jumlah_departemen'], 'integer'],
[['nama'], 'string', 'max' => 100],
[['website'], 'string', 'max' => 200],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'nama' => 'Nama',
'website' => 'Website',
'jumlah_departemen' => 'Jumlah Departemen',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getDepartemens()
{
return $this->hasMany(Departemen::className(), ['id_lembaga' => 'id']);
}
}
<file_sep>/basic/views/paten/_search.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\PatenSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="paten-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<div class="col-md-6">
<?= $form->field($model, 'bidang_ilmu') ->dropDownList ([
''=>''
,'bioteknologi'=>'Bioteknologi'
,'biodiesel'=>'Biodiesel'
])?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'lembaga') ->dropDownList ([
''=>''
,'bppt'=>'BPPT'
,'itb'=>'ITB'
])?>
</div>
<div class="col-md-12">
<?= $form->field($model, 'nama', [
'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
])->textInput()->input('name', ['placeholder' => "Search..."])->label(false); ?>
</div>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::a('Reset',['/paten'], ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<file_sep>/basic/controllers/UserManajemenController.php
<?php
namespace app\controllers;
use Yii;
use app\models\Lembaga;
use app\models\LembagaSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
class UserManajemenController extends \yii\web\Controller
{
public function actionIndex()
{
$searchModel = new LembagaSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$this->layout = 'main_admin';
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
}
<file_sep>/basic/models/Peneliti.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "peneliti".
*
* @property integer $id
* @property string $nama
* @property integer $jumlah_paten
* @property integer $jumlah_paper
* @property integer $id_departemen
*
* @property Departemen $idDepartemen
*/
class Peneliti extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'peneliti';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['nama', 'jumlah_paten', 'jumlah_paper', 'id_departemen'], 'required'],
[['jumlah_paten', 'jumlah_paper', 'id_departemen'], 'integer'],
[['nama'], 'string', 'max' => 100],
[['id_departemen'], 'exist', 'skipOnError' => true, 'targetClass' => Departemen::className(), 'targetAttribute' => ['id_departemen' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'nama' => 'Nama',
'jumlah_paten' => 'Jumlah Paten',
'jumlah_paper' => 'Jumlah Paper',
'id_departemen' => 'Id Departemen',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getIdDepartemen()
{
return $this->hasOne(Departemen::className(), ['id' => 'id_departemen']);
}
}
<file_sep>/basic/views/admin-paten/create.php
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\Paten */
$this->title = 'Create Paten';
$this->params['breadcrumbs'][] = ['label' => 'Patens', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="container" style="padding-right:50px;">
<div class="row">
<div class="col-md-12">
<div class="paten-create">
<h2>Create Aktivitas</h2><br>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i>Home</a></li>
<li class="active">Aktivitas</li>
<li> Create</li>
</ol>
<div class="box box-info">
<div class="box-header with-border">
<div class="box-header with-border">
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
</div>
</div>
</div>
</div>
</div>
<file_sep>/basic/views/sdm/profile.php
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
$this->title = 'SIIN - Profile';
?>
<div class="row" style="padding-top: 20px; padding-bottom: 20px;">
<div class="container">
<div class="col-md-3">
<center>
<?php echo Html::img('@web/images/profile.png', ['width'=>'200', 'height'=>'200']) ?>
</center>
</div>
<div class="col-md-9">
<h3>
<?php echo $model -> {'nama'} ." ". $model -> {'gelar'}; ?>
</h3>
<p><span class="glyphicon glyphicon-home" aria-hidden="true"></span> <strong><?php echo $model -> {'lembaga'} ?> <?php echo $model -> {'bidang_ilmu'} ?></strong></p>
Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.
</div>
</div>
</div>
<br />
<div class="row">
<div class="container">
<div class="col-md-12">
<ul class="nav nav-tabs nav-justified">
<li class="active"><a data-toggle="tab" href="#paten">Paten</a></li>
<li><a data-toggle="tab" href="#paper">Paper</a></li>
<li><a data-toggle="tab" href="#tab1">Tab 1</a></li>
<li><a data-toggle="tab" href="#tab2">Tab 2</a></li>
</ul>
<div class="tab-content">
<div id="paten" class="tab-pane fade in active">
<br />
<div class="col-md-2">
<br />
<center>
<?php echo Html::img('@web/images/paper.png', ['width'=>'100', 'height'=>'100']) ?>
</center>
</div>
<div class="col-md-10">
<h3>Transgenerational Epigenetics, or the Spectral History of the Flesh</h3>
<p>
<span class="glyphicon glyphicon-bookmark" aria-hidden="true"></span> Bookmark |
<span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span> 98301 view |
<span class="glyphicon glyphicon-option-horizontal" aria-hidden="true"></span> more
</p>
</div>
</div>
<div id="paper" class="tab-pane fade">
<br />
<div class="col-md-2">
<br />
<center>
<?php echo Html::img('@web/images/paper.png', ['width'=>'100', 'height'=>'100']) ?>
</center>
</div>
<div class="col-md-10">
<h3>Outliers, Freaks, and Cheats: Constituting Normality in the Age of Enhancement</h3>
<p>
<span class="glyphicon glyphicon-bookmark" aria-hidden="true"></span> Bookmark |
<span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span> 4218 view |
<span class="glyphicon glyphicon-option-horizontal" aria-hidden="true"></span> more
</p>
</div>
</div>
<div id="tab1" class="tab-pane fade">
<h3>Tab 1</h3>
<p>Some content in Tab 1.</p>
</div>
<div id="tab2" class="tab-pane fade">
<h3>Tab 2</h3>
<p>Some content in Tab 2.</p>
</div>
</div>
</div>
</div>
</div>
<file_sep>/basic/views/site/index.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\Url;
/* @var $this yii\web\View */
$this->title = 'SIIN - Home';
?>
<div class="site-index">
<div class="row row-centered">
<div class="col-md-12">
<?=$map->display()?>
</div>
</div>
<div class="container" style="padding-top: 21px;padding-bottom: 21px">
<div class="row">
<div class="col-md-3">
<center><a style="background-color: #ecf0f1; border:0px solid transparent;" class="btn btn-default" href="<?php echo \yii\helpers\Url::to(['/budget']); ?>">
<?php echo Html::img('@web/images/budget.png', ['width'=>'100']) ?>
<br /><br /><strong>Budget »</strong></a></center>
</div>
<div class="col-md-3">
<center><a style="background-color: #ecf0f1; border:0px solid transparent;" class="btn btn-default" href="<?php echo \yii\helpers\Url::to(['/sdm']); ?>">
<?php echo Html::img('@web/images/sdm.png', ['width'=>'50', 'height'=>'50']) ?>
<br /><br /><strong>SDM »</strong></a></center>
</div>
<div class="col-md-3">
<center><a style="background-color: #ecf0f1; border:0px solid transparent;" class="btn btn-default" href="<?php echo \yii\helpers\Url::to(['/lembaga']); ?>">
<?php echo Html::img('@web/images/lembaga.png', ['width'=>'50', 'height'=>'50']) ?>
<br /><br /><strong>Lembaga »</strong></a></center>
</div>
<div class="col-md-3">
<center><a style="background-color: #ecf0f1; border:0px solid transparent;" class="btn btn-default" href="<?php echo \yii\helpers\Url::to(['/paper']); ?>">
<?php echo Html::img('@web/images/output.png', ['width'=>'50', 'height'=>'50']) ?>
<br /><br /><strong>Output »</strong></a></center>
</div>
</div>
</div>
</div>
<file_sep>/basic/views/user-manajemen/index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\DosenSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
// $this->title = 'Dosens';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="paten-index container" style="padding-right:50px;">
<div class="row">
<div class="col-md-12">
<div class="sdm-index">
<h2>User Manajemen</h2>
<ol class="breadcrumb">
<li><a href="<?php echo \yii\helpers\Url::to(['/admin']); ?>"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">User Manajemen</li>
</ol>
<div class="box">
<div class="box-header with-border">
<table class="table table-striped table-bordered"><thead>
<tr><th>#</th><th><a href="/demosiin/basic/web/admin-sdm/index?sort=nama" data-sort="nama">Usernama</a></th><th><a href="/demosiin/basic/web/admin-sdm/index?sort=gelar" data-sort="gelar">Last Seen </a></th><th><a href="/demosiin/basic/web/admin-sdm/index?sort=lembaga" data-sort="lembaga">Type</a></th><th><a href="/demosiin/basic/web/admin-sdm/index?sort=bidang_ilmu" data-sort="bidang_ilmu">First Seen</a></th><th class="action-column"></tr>
</thead>
<tbody>
<tr data-key="3"><td>1</td><td><EMAIL></td><td>9 days ago</td><td>BNN</td><td>8 days ago</td><td><a href="/demosiin/basic/web/admin-sdm/view?id=3" title="View" aria-label="View" data-pjax="0"></tr>
<tr data-key="4"><td>2</td><td><EMAIL></td><td>9 days ago</td><td>BNN</td><td>8 days ago</td><td><a href="/demosiin/basic/web/admin-sdm/view?id=4" title="View" aria-label="View" data-pjax="0"></tr>
<tr data-key="5"><td>3</td><td><EMAIL></td><td>9 days ago</td><td>KM</td><td>8 days ago</td><td><a href="/demosiin/basic/web/admin-sdm/view?id=5" title="View" aria-label="View" data-pjax="0"></tr>
<tr data-key="6"><td>4</td><td><EMAIL></td><td>9 days ago</td><td>BPP</td><td>8 days ago</td><td><a href="/demosiin/basic/web/admin-sdm/view?id=6" title="View" aria-label="View" data-pjax="0"></tr>
</tbody></table>
</div>
</div>
</div>
</div>
| 8c3d15a72b6833c3b7d6a4e3ef6e8dda3e031bfe | [
"PHP"
]
| 22 | PHP | baniainurramdlan/demosiin | 2b512759d3b1a9af515ae3590b73c86fa86f0beb | 2788722fe7a1600b1e8557333f4eb7a583db3249 |
refs/heads/master | <file_sep>package com.upgrad.FoodOrderingApp.service.businness;
import com.upgrad.FoodOrderingApp.service.dao.CustomerDao;
import com.upgrad.FoodOrderingApp.service.entity.CustomerEntity;
import com.upgrad.FoodOrderingApp.service.exception.SignUpRestrictedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class CustomerBusinessService {
@Autowired
private CustomerDao customerDao;
@Autowired
private PasswordCryptographyProvider passwordCryptographyProvider;
@Transactional(propagation = Propagation.REQUIRED)
public CustomerEntity signup(CustomerEntity customerEntity) throws SignUpRestrictedException {
if (CustomerDao.IsContactNumberExists(customerEntity.getContactNumber())){
throw new SignUpRestrictedException("SGR-001", "This contact number is already registered! Try other contact number.");
}
CustomerEntity signupUser = customerDao.createCustomer(customerEntity);
return signupUser;
}
}
| f131219ef4a544c4cb01134cec3fb01007964419 | [
"Java"
]
| 1 | Java | tbhuria/Capstone | 1d149f0ee34f4147cc4770a19ed9106cb05c23fd | aeb13daa64cff269b74b106ea86cc545f069e375 |
refs/heads/master | <repo_name>ritikmishra/javascript-daily<file_sep>/script.js
function FirstReverse(str) {
var output = str.split('');
var outputa = output.reverse();
var outputb = outputa.toString();
var outputc = outputb.replace(/,/g , '')
return outputc;
}
function LongestWord(sen) {
var input = sen.split(" ")
var position = 0;
var long_word;
var length = 0;
for(i = 0; i < input.length; i++) {
if (input[i].length > length){
length = input[i].length;
position = i;
long_word = input[i];
}
}
return long_word;
}
function readline(){
var input = document.getElementById("string").value;
document.getElementById("reverse-text").innerHTML = FirstReverse(input);
document.getElementById("longest_word").innerHTML = LongestWord(input);
}
function enterPressed(evn) /*For some reason this doesn't work in Fireox; you have to click the button*/
{
if (window.event && window.event.keyCode == 13) {/* key code 13 is both enter and numpad enter on the keyboard*/
readline();
}
else if (evn && evn.keyCode == 13) {
readline();
}
}
<file_sep>/README.md
javascript-daily
================
This is a repository as part of my new year's resolution: write some JavaScript every day and put it on GitHub
| 88b6d3b351d78cffea81a8d122d7e22d30b9d991 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | ritikmishra/javascript-daily | dfa73c07bc7116902f01d043fca46e0189849258 | c37054e19cf99b064105fbdcb8edb727fd431ce0 |
refs/heads/master | <repo_name>longtomjr/project_euler<file_sep>/solutions/problem_003.py
#! usr/bin/env python3
# This is an import statement. It is used to import modules with
# Numerous handy functions and types
# More on modules: https://docs.python.org/3/glossary.html#term-module
import math
def fermat_factors(N: int) -> tuple:
"""
Gets the factors of a odd number 'N' using Fermat's factorization
method.
:param N: Odd number to be factorized
:returns: A tuple containing the 2 Fermat factors
"""
# Does a check to see if the input was odd
if N % 2 == 0:
# Raising/Trowing an exeption (error) to make sure nothing
# happens that will break something bigger and make the error
# Easily traceable
raise SyntaxError("N should be odd")
# When using functions from a module, always write as
# 'module.function()' [Exept when using a 'for' import clause]
a = math.ceil(math.sqrt(N))
b2 = a**2 - N
while math.sqrt(b2) % 1 != 0:
a = a + 1
b2 = a**2 - N
# We are returning a tuple containing the 2 factors we got
# Tuples are a colletion data type
# more on tuples: https://docs.python.org/3/library/stdtypes.html#tuples
# Tuples are stored like (1, 2)
return (int(a - math.sqrt(b2)), int(a + math.sqrt(b2)))
def prime_factors(N: int) -> list:
"""
Returns the prime factors of an odd number 'N'
:param N: Odd number to be prime factorized
:returns: List of all the prime factors of 'N'
"""
factors = [fermat_factors(N)]
primes = []
for factor_pair in factors:
# If the first factor is 1, we know we have a prime
if factor_pair[0] == 1:
primes.append(factor_pair[1])
else:
factors.append(fermat_factors(factor_pair[0]))
factors.append(fermat_factors(factor_pair[1]))
return primes
def main():
primes = prime_factors(600851475143)
print(primes)
print(max(primes))
if __name__ == "__main__":
main()
<file_sep>/solutions/problem_011.py
#!/bin/bash/env python3
import csv
def get_grid():
"""
Gets the grid of the csv as a two dimensional array
"""
grid = []
grid_str = []
with open('problem_011_grid.csv') as f:
grid_reader = csv.reader(f, delimiter=" ", quoting=csv.QUOTE_NONE)
for row in grid_reader:
for n in row:
n = int(n)
grid_str.append(row)
# Changes the type of the entries in the nested array to int
for row in grid_str:
grid.append([int(x) for x in row])
return grid
def get_right_product(grid, x, y, n):
product = 1
for i in range(n):
product = product * grid[x][y + i]
return product
def get_down_product(grid, x, y, n):
product = 1
for i in range(n):
product = product * grid[x + i][y]
return product
def get_diagonal_right_product(grid, x, y, n):
product = 1
for i in range(n):
product = product * grid[x + i][y + i]
return product
def get_diagonal_left_product(grid, x, y, n):
product = 1
for i in range(n):
product = product * grid[x + i][y - i]
return product
def get_products(grid, x, y, n):
products = [
get_right_product(grid, x, y, n),
get_down_product(grid, x, y, n),
get_diagonal_right_product(grid, x, y, n),
get_diagonal_left_product(grid, x, y, n)
]
return products
def get_biggest_product(grid, n):
products = []
for idx_x, val in enumerate(grid):
for idx_y, val_y in enumerate(val):
try:
products.append(max(get_products(grid, idx_x, idx_y, n)))
except IndexError:
continue
return max(products)
def main():
print(get_biggest_product(get_grid(), 4))
return 0
if __name__ == "__main__":
main()
<file_sep>/solutions/problem_001.py
#!/usr/bin/env python3
# ^ Called a shabang -> easier to execute on Unix style OSes
def multiples(factor_list: list, maximum: int):
"""
Returns a list of the multiples of the given factors
:param factor_list: A 'list' of the factors to get the multiples of
:param maximum: The maximum number that is used to look for multiples
:returns: Returns a 'list' of the multiples of the given factors
"""
# Creates an empty list to later append to
multiples_list = []
# Loops over all the factors in the list
for factor in factor_list:
# loops over all the numbers from 1 to the maximum
for i in range(1, maximum):
# Checks if the factor can be divided "cleanly" and add it to the
# list if it can.
if i % factor == 0:
multiples_list.append(i)
# Continues if not a multiple (continues with the loop)
else:
continue
# 'multiples_list' changed to a 'set' (removes duplicates) and back to a
# list
# Read here: https://docs.python.org/3/library/stdtypes.html#types-set
# Set is a collection like 'list', but unordered and can only have unique
# entries therefore no duplicate entries. Very handy to remove duplicates
return list(set(multiples_list))
def sum(l: list) -> int:
"""
Gets the sum of all the entries in the given list
"""
s = 0
for i in l:
s += i
return s
def main():
# print(multiples([3, 5], 1000))
print(sum(multiples([3, 5], 1000)))
# "boilerplate" script to make sure python file is seen as a standalone
# executable. No need for you to use it.
if __name__ == "__main__":
main()
<file_sep>/solutions/problem_005.py
#!/usr/bin/env python3
# NOTE: range_floor is an optional parameter that has a default of 1
def even_divisible_min(range_ceiling: int, range_floor=1) -> int:
"""
Gets the smallest number that is evenly divisible by all the
numbers in the range specified
:param range_ceiling: The upper limit of the range of numbers to
be divided by
:param range_floor: The smallest number of the range (where it
should start)
:returns: The minimum evenly divisible number by the whole range
"""
n = 1
# infinite loop to re-run the 'for' loop everytime a number
# is not valid
while True:
for i in range(range_floor, range_ceiling + 1):
# Checks if 'n' is not evenly divisible by 'i'
# If so n is changed to be one larger and the for loop
# is exited so it can start again with the new number
if n % i != 0:
n = n + 1
break
# Checks if i is the upper limit and finishes the
# function if it is.
elif i == range_ceiling:
return n
else:
continue
def main():
print(even_divisible_min(20))
if __name__ == "__main__":
main()
<file_sep>/solutions/problem_010.py
#!/usr/bin/env python3
# import can be used to import any python file in the same folder
# the 'as' statemet can be used to import any module with
# a different name
import problem_007 as prime
def main():
print(sum(prime.sieve_eratosthenes(2000000)) - 1)
return 0
if __name__ == "__main__":
main()
<file_sep>/solutions/problem_002.py
#! usr/bin/env python3
def F(n: int) -> int:
"""
Function that is a python version of the mathematical
function
{0 - if n = 0;
F_n = {1 - if n = 1;
{F_n-1 + F_n-2 if n > 1.
:param n: The term of the sequance you want
:returns: The n-th term of the fibonacci sequance
"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return F(n - 1) + F(n - 2)
def fib(n: int) -> list:
"""
Generates a 'list' of the fibonacci sequance to the nth term
:param n: the length of the sequance
:returns: A list with the fibonacci sequence
"""
sequence = []
for i in range(n + 1):
sequence.append(F(i))
return sequence
def fibonacci_max_n(maximum: int) -> int:
"""
Gets 'n' of the largest fibonacci number less than the max
:param maximum: The number that may not be exeeded
:returns: 'n' of the largest number less than the max
"""
n = 0
# Infinite loop that will continue until broken
while True:
# Makes 'n' larger until the fibonacci number is to large
if F(n) < maximum:
n = n + 1
continue
else:
# Return will break the loop
# This 'else' clause will only be reached once n is one to large
# therefore I can get the correct value of n by just subtracting 1
return n-1
def sum_of_even_terms(l: list) -> int:
"""
Gets the sum of all the even terms in a list
:param l: The list to be used to get the sums
:returns: The sum of all the even terms in 'l'
"""
s = 0
for i in l:
# If a number is even, it will be a factor of 2
# therefore it will be cleanly divisible by 2
if i % 2 == 0:
s = s + i
else:
continue
return s
def main():
# Order of events:
# 1. Get max n
# 2. Get the sequence to n
# 3. Gets the sum of all the even terms
# 4. Prints the result
print(sum_of_even_terms(fib(fibonacci_max_n(4000000))))
"""
Footnotes:
- The code can be made a lot more efficient if you only have to get the
sequence once. (currently we get it with max_n, and fib)
- This is however was not a priority for me since it is easier to see
How it works this way. If you want to you can try and code a more
efficient example eliminating the 2nd sequence contstructing
- A way better implementaion would be using https://i.stack.imgur.com/SPYOU.gif
Since it is super fast to compute and way more efficient
- Chalenge: Try to rewrite this script using this equation
- Hint 1: Use the 'math' library "import math"
- If you are stuck go read this Stack Overflow Q and A
https://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python
"""
if __name__ == "__main__":
main()
<file_sep>/solutions/problem_006.py
#!/usr/bin/env python3
# Hierdie is pretty straight forward, figure dit self uit en kyk
# of jy dit kan improve
def sum_of_squares(n):
x = 0
for i in range(1, n+1):
x = x + i ** 2
return x
def square_of_sums(n):
return sum(range(1, n+1)) ** 2
def main():
print(square_of_sums(100) - sum_of_squares(100))
if __name__ == "__main__":
main()
<file_sep>/solutions/problem_009.py
#!/usr/bin/env python3
def euclid_pyth_triplet(n, m):
"""
Creates a pythagorean triplet using a variant of Euclid's formula
More here:
https://en.wikipedia.org/wiki/Pythagorean_triple#A_variant
http://www.friesian.com/pythag.htm
:param n: A odd integer to use for generating a triplet
:param m: An odd integer larger than 'n' for generating a triplet
:returns: List containing 3 integers that make up a pythagorean triplet
"""
if n % 2 == 0 or m % 2 == 0:
raise SyntaxError("n or m is even and should be odd")
a = n * m
b = (m**2 - n**2) / 2
c = (m**2 + n**2) / 2
return [int(a), int(b), int(c)]
def pyth_triplet_test(triplet):
"""
Checks if a given list of 3 integers is a pythagorean triplet
:param triplet: List of 3 integers to be tested
:returns: 'True' if 'triplet' is a pythagorean triplet, 'False' if not
"""
if triplet[0]**2 + triplet[1]**2 == triplet[2]**2:
return True
else:
return False
def triplet_sum(l, target):
"""
Checks if the sum of a given triplet is equal to the target sum
:param l: List containing 3 integers
:param target: The target sum
:returns: 'True' if the sum of 'l' is equal to the target sum
"""
if l[0] + l[1] + l[2] == target:
return True
else:
return False
def find_triplet_with_sum(range_max, target_sum):
"""
Creates several pythagorean triplets to find a triplet that adds up
to the target sum
:param range_max: The max range to be used to generate the triplets
:param target_sum: The sum that wants to be achieved
:returns: A list with 3 ints coresponding to a pythagorean triplet
that adds up to the target sum
"""
for i in range(1, range_max, 2):
for j in range(1, range_max, 2):
triplet = euclid_pyth_triplet(i, j)
if triplet_sum(triplet, target_sum):
return triplet
def main():
triplet = find_triplet_with_sum(50, 1000)
print(triplet)
print(triplet[0] * triplet[1] * triplet[2])
if __name__ == "__main__":
main()
<file_sep>/solutions/problem_004.py
#!/usr/bin/env python3
def max_palindrome_product(max_number: int) ->int:
"""
Gets the maximum product of two numbers less than the given
maximum that is a palindrome
:param max_number: The maximum value of the two numbers
:returns: The largest palindromic number
"""
palindromes = []
for x in range(max_number, 1, -1):
for y in range(max_number, 1, -1):
if is_palindrome(str(x * y)):
palindromes.append(x*y)
else:
continue
return max(palindromes)
def is_palindrome(s: str) -> bool:
"""
Check if a given string is a palindrome
:param s: String to be tested
:returns: True if a palindrome, False if not
"""
if s == s[::-1]:
return True
else:
return False
def main():
print(max_palindrome_product(999))
return 0
if __name__ == "__main__":
main()
<file_sep>/solutions/problem_007.py
#!/usr/bin/env python3
import math
def prime_range(n: int) -> list:
"""
Gets a range that the nth prime can reasonably be expected to be in
Found the formula (from the Prime Number Theorem) here:
https://math.stackexchange.com/questions/1257/is-there-a-known-mathematical-equation-to-find-the-nth-prime
:param n: The index for a prime number
:returns: A list with the lower an upper limit that the nth prime
number can be expected to be in
"""
# Note: math.log() returns the natural log if no base is specified
range_min = n * math.log(n) + n * (math.log(math.log(n)) - 1)
range_max = n * math.log(n) + n * math.log(math.log(n))
return [math.ceil(range_min), math.ceil(range_max)]
def sieve_eratosthenes(n: int) -> list:
"""
Finds all the Primes using the upper limit 'n' using
Eratosthenes's Sieve algorithm
More here: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode
:param n: The upper limit of numbers to be tested for bieng primes
:returns: list containing all the primes less than n
"""
A = [True] * n
primes = []
for i in range(2, math.ceil(math.sqrt(n))):
if A[i] is True:
for j in range(i**2, n, i):
A[j] = False
for i in range(len(A)):
if A[i] is True:
primes.append(i)
return (primes)
def P(n: int) -> list:
"""
Gets the n-th prime number
:param n: The index of the prime number
:returns: The n-th prime number
"""
return sieve_eratosthenes(prime_range(n)[1])[n + 1]
def main():
print(P(10001))
if __name__ == "__main__":
main()
| 59bd7f1bfb4815fa785cce9e3ea9f9781ec60c80 | [
"Python"
]
| 10 | Python | longtomjr/project_euler | 786a62f9815c28e00027426273feb088f30fd1de | 5b7cbabe384578f961939310565b7d1cd021545f |
refs/heads/master | <repo_name>jehingson/react-context-hook-giphy<file_sep>/src/paginas/Home.js
import React, { useState } from "react";
import { useLocation } from "wouter";
import ListaGifsTrue from "componentes/ListaGifsTrue";
import { useGifs } from "hooks/useGifs";
import Spinner from "componentes/Spinner";
import TrendingSearches from "componentes/TrendingSearches";
function Home() {
const [keyword, setkeyword] = useState("");
const value = useLocation();
const pushLocation = value[1];
const { loading, gifs } = useGifs();
const handleSubmit = (event) => {
event.preventDefault();
pushLocation(`/buscar/${keyword}`);
};
const handleChange = (event) => {
setkeyword(event.target.value);
};
return (
<>
{loading ? (
<Spinner />
) : (
<>
<form onSubmit={handleSubmit}>
<input
onChange={handleChange}
placeholder="buscar"
type="text"
value={keyword}
/>
<button>Buscar</button>
</form>
<h3 className="App-title">Ultima Busqueda</h3>
<ListaGifsTrue gifs={gifs} />
<h3 className="App-title">Los Gifs mas populares</h3>
<div className="App-Categoria">
<TrendingSearches name="Tendencias" />
</div>
</>
)}
</>
);
}
export default Home;
<file_sep>/src/hooks/useGlobalGIf.js
import { useContext } from "react";
import GifsContextProvider from "../Context/GifsContextProvider";
export default function useGlobalGifs() {
const { gifs } = useContext(GifsContextProvider);
return gifs;
}
<file_sep>/src/componentes/TrendingSearchesOn.js
import React, { useState, useEffect } from "react";
import getTrendingTemaService from "servicios/getTrendingTermaService";
import Categoria from "./Categoria";
export default function TrendingSearches() {
const [trends, setTrends] = useState([]);
useEffect(() => {
getTrendingTemaService().then(setTrends);
}, []);
return (
<>
<Categoria name="Tendencias" option={trends} />
</>
);
}
<file_sep>/src/hooks/useGifs.js
import { useEffect, useState, useContext } from "react";
import getGifs from "../servicios/getGifs";
import GifsContextProvider from "../Context/GifsContextProvider";
const INICIA_PAGE = 0;
export function useGifs({ keyword } = { keyword: null }) {
const [loading, setloading] = useState(false);
const [loadingNext, setLoadingNext] = useState(false);
const [page, setPage] = useState(INICIA_PAGE);
const value = useContext(GifsContextProvider);
const [gifs, setGifs] = value.gifs;
const keywordToUse =
keyword || localStorage.getItem("keywordAnterior") || "random";
useEffect(() => {
//keyword es una dependencia del efecto
async function gifs() {
setloading(true);
const losGifs = await getGifs({ keyword: keywordToUse });
setGifs(losGifs);
setloading(false);
localStorage.setItem("keywordAnterior", keywordToUse);
}
gifs();
}, [keyword, keywordToUse, getGifs]);
useEffect(() => {
if (page === INICIA_PAGE) return;
setLoadingNext(true);
getGifs({ keyword: keywordToUse, page }).then((nextGifs) => {
setGifs((prevGifs) => prevGifs.concat(nextGifs));
setLoadingNext(false);
});
}, [keyword, page, setGifs]);
return { loading, loadingNext, gifs, setPage };
}
<file_sep>/src/Context/StaticContext.js
import React from "react";
const Context = React.createContext({
name: "<NAME>",
midudev: " app gif",
});
export default Context;
<file_sep>/src/paginas/Perfil.js
import React from "react";
import Gif from "componentes/Gif";
import useGlobalGif from "hooks/useGlobalGIf";
function Pefil({ params }) {
const value = useGlobalGif();
const gifs = value[0];
const gif = gifs.find((singleGif) => singleGif.id === params.id);
return <Gif {...gif} />;
}
export default Pefil;
<file_sep>/src/servicios/configuracion.js
export const API_KEY = "<KEY>";
export const API_URL = "https://api.giphy.com/v1";
<file_sep>/src/servicios/getGifs.js
import { API_URL, API_KEY } from "./configuracion";
export default async function getGifs({
limit = 10,
keyword = "morty",
page = 0,
} = {}) {
const apiURL = `${API_URL}/gifs/search?api_key=${API_KEY}&q=${keyword}&limit=${limit}&offset=${
page * limit
}&rating=g&lang=es`;
const res = await fetch(apiURL);
const response = await res.json();
const { data = [] } = response;
if (Array.isArray(data)) {
const gifs = data.map((image) => {
const { images, title, id } = image;
const { url } = images.downsized_medium;
return { title, id, url };
});
return gifs;
}
}
<file_sep>/src/App.js
import React from "react";
import "App.css";
import "componentes/styles.css";
import ListaGifs from "componentes/ListaGifs";
import { Link, Route } from "wouter";
import Home from "paginas/Home";
import Perfil from "paginas/Perfil";
import StaticContext from "Context/StaticContext";
import { GifsContextProvider } from "Context/GifsContextProvider";
function App() {
/* const state = useState('');
const value = state[0];
const setValue = state[1];
*/
return (
<StaticContext.Provider value={{ name: "jehingos", canal: "pronto" }}>
<div className="App">
<section className="App-content">
<Link to="/">
<h1>App</h1>
</Link>
<GifsContextProvider>
<Route path="/" component={Home} />
<Route path="/buscar/:keyword" component={ListaGifs} />
<Route path="/gif/:id" component={Perfil} />
</GifsContextProvider>
</section>
</div>
</StaticContext.Provider>
);
}
export default App;
<file_sep>/src/componentes/TrendingSearches.js
import React, { Suspense } from "react";
import useNearScreen from "hooks/useNeaeScreen";
import Spinner from "./Spinner";
const TrendingSearchesOn = React.lazy(() => import("./TrendingSearchesOn"));
export default function LazyTrending() {
const { isNearScreen, elementRef } = useNearScreen({ distancia: "0px" });
console.log(isNearScreen);
return (
<div ref={elementRef}>
<Suspense fallback={<Spinner />}>
{isNearScreen ? <TrendingSearchesOn /> : <Spinner />}
</Suspense>
</div>
);
}
<file_sep>/src/componentes/Categoria.js
import React from "react";
import { Link } from "wouter";
const Categoria = ({ option = [], name }) => {
return (
<div className="Categoria">
<h3 className="App-title">Tendencia</h3>
<ul className="App-main">
{option.map((popularGif, index) => (
<li className="App-results" key={index}>
<Link to={`/buscar/${popularGif}`}>{popularGif}</Link>
</li>
))}
</ul>
</div>
);
};
export default Categoria;
| 88699051cf520322eca91739e7ead3b14e48983d | [
"JavaScript"
]
| 11 | JavaScript | jehingson/react-context-hook-giphy | 779540a280d78e584ee5a68c783f55a3140ea37d | 51b521a51db9a2ab6286248825a1e662eaf5e597 |
refs/heads/master | <file_sep>/**
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/* eslint-disable no-mixed-operators */
import * as THREE from 'three';
import _ from 'lodash';
import ConnectionView from '../base/connectionView';
import GlobalStyles from '../globalStyles';
const Console = console;
function distance (a, b) {
return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
}
function rotate (point, theta) {
return {
x: point.x * Math.cos(theta) - point.y * Math.sin(theta),
y: point.x * Math.sin(theta) + point.y * Math.cos(theta)
};
}
// Given three points, A B C, find the center of a circle that goes through all three.
function CalculateCircleCenter (A, B, C) {
const aSlope = (B.y - A.y) / (B.x - A.x);
const bSlope = (C.y - B.y) / (C.x - B.x);
if (aSlope === 0 || bSlope === 0) {
// rotate the points about origin to retry and then rotate the answer back.
// this should avoid div by zero.
// we could pick any acute angle here and be garuanteed this will take less than three tries.
// i've discovered a clever proof for this, but I don't have room in the margin.
const angle = Math.PI / 3;
return rotate(CalculateCircleCenter(rotate(A, angle), rotate(B, angle), rotate(C, angle)), -1 * angle);
}
const center = {};
center.x = (aSlope * bSlope * (A.y - C.y) + bSlope * (A.x + B.x) - aSlope * (B.x + C.x)) / (2 * (bSlope - aSlope));
center.y = -1 * (center.x - (A.x + B.x) / 2) / aSlope + (A.y + B.y) / 2;
return center;
}
class DnsConnectionView extends ConnectionView {
constructor (connection) {
super(connection, 20000, true);
this.updatePosition();
this.updateVolume();
this.drawAnnotations();
}
cleanup () {
super.cleanup();
_.each([
this.annotationMaterial,
this.annotationTexture,
this.annotationGeometry,
this.annotationMesh
], x => { try { x.dispose(); } catch (e) { Console.log(e); } });
}
setParticleLevels () {
super.setParticleLevels();
this.maxParticleDelay = 10000;
// After some testing, it's pretty hard to see the difference in density after
// 40. It's still a linear growth curve, but since there is so much overlapping
// differences much further than 40 are too difficult to spot
this.maxParticleMultiplier = 10;
}
drawAnnotations () {
if (!this.object.annotations || this.object.annotations.length === 0) {
return;
}
const dx = this.startPosition.x - this.endPosition.x;
const dy = this.startPosition.y - this.endPosition.y;
const width = Math.floor(Math.sqrt(dx * dx + dy * dy));
const bump = 40;
const headerFontSize = bump * 0.75;
const stubRadius = bump; // size of the arrow half-head
// make sure we are tall enough for all the annotations.
const height = this.object.annotations.length * bump * 4;
const annotationCanvas = this.createCanvas(width, height);
this.annotationTexture = new THREE.Texture(annotationCanvas);
this.annotationTexture.minFilter = THREE.LinearFilter;
this.annotationMaterial = new THREE.MeshBasicMaterial({ map: this.annotationTexture, side: THREE.DoubleSide, transparent: true });
this.annotationGeometry = new THREE.PlaneBufferGeometry(annotationCanvas.width, annotationCanvas.height);
this.annotationMesh = new THREE.Mesh(this.annotationGeometry, this.annotationMaterial);
this.container.add(this.annotationMesh);
// initially the connection canvas is flat at 0,0 in screen space, so we need to move it and rotate
this.annotationMesh.position.set((this.startPosition.x + this.endPosition.x) / 2, (this.startPosition.y + this.endPosition.y) / 2, 0);
this.annotationMesh.rotateZ(Math.atan2((this.endPosition.y - this.startPosition.y), (this.endPosition.x - this.startPosition.x)));
const ctx = annotationCanvas.getContext('2d');
ctx.clearRect(0, 0, annotationCanvas.width, annotationCanvas.height);
ctx.fillStyle = 'rgba(255,255,255,0.125)';
function drawText (text, style, i) {
ctx.fillStyle = style;
ctx.font = `700 ${headerFontSize}px 'Source Sans Pro', sans-serif`;
ctx.textBaseline = 'bottom';
ctx.fillText(text, width / 2, height / 2 - i * bump);
}
function drawCircle (point, startAngle, endAngle, radius, style) {
ctx.strokeStyle = style;
ctx.lineCap = 'round';
ctx.lineWidth = 10;
ctx.beginPath();
ctx.arc(point.x, point.y, radius, startAngle, endAngle);
ctx.stroke();
}
const nodeRadius = this.object.source.getView().radius;
function drawArrowHalfHead (style, i) {
const start = {
x: nodeRadius,
y: height / 2
};
const end = {
x: width - nodeRadius,
y: height / 2
};
// find the angle perpendicular to the vector between start and end on the clockwise side.
let theta = Math.atan((end.y - start.y) / (end.x - start.x));
if (start.x <= end.x) {
theta -= Math.PI / 2;
} else {
theta += Math.PI / 2;
}
// find a point perpendicular to the segment between start and end that is `bump` distance away.
const offset = {
x: (end.x + start.x) / 2 + Math.cos(theta) * bump * i,
y: (end.y + start.y) / 2 + Math.sin(theta) * bump * i
};
// get the center of the circle whose arc goes through all three points, its radius and connect the dots
const center = CalculateCircleCenter(start, end, offset);
const radius = Math.sqrt(Math.pow(start.x - center.x, 2) + Math.pow(start.y - center.y, 2));
const startAngle = Math.atan2(start.y - center.y, start.x - center.x);
const endAngle = Math.atan2(end.y - center.y, end.x - center.x);
drawCircle(center, startAngle, endAngle, radius, style);
// to draw the arrowhead, we create a small circle opposite the end point from the main arc's center
const t2 = Math.atan((end.y - center.y) / (end.x - center.x));
let stubCenter = {
x: end.x + Math.cos(t2) * stubRadius,
y: end.y + Math.sin(t2) * stubRadius
};
// if we didn't actually go on the *opposite* side of the end point, make sure we do that ;)
if (distance(stubCenter, center) < distance(end, center)) {
stubCenter = {
x: end.x - Math.cos(t2) * stubRadius,
y: end.y - Math.sin(t2) * stubRadius
};
}
const stubAngle = Math.atan2(end.y - stubCenter.y, end.x - stubCenter.x);
drawCircle(stubCenter, stubAngle, stubAngle + Math.PI / 4, stubRadius, style);
}
_.each(this.object.annotations, (annotation, index) => {
drawArrowHalfHead(GlobalStyles.getColorTraffic(annotation.class), index + 1);
});
_.each(this.object.annotations, (annotation, index) => {
if (!annotation.label) {
return;
}
drawText(annotation.label, GlobalStyles.getColorTraffic(annotation.class), index + 1);
});
this.annotationTexture.needsUpdate = true;
}
}
export default DnsConnectionView;
<file_sep>/**
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import _ from 'lodash';
import DnsConnection from './dnsConnection';
import DnsNode from './dnsNode';
import TrafficGraph from '../base/trafficGraph';
const Console = console;
function positionNodes (nodes, dimensions) {
const nodesByIndex = _.groupBy(nodes, (n) => {
try {
return n.metadata.layout.rank;
} catch (e) {
return Math.Infinity;
}
});
const ranks = _.map(Object.keys(nodesByIndex).sort(),
(idx) => _.sortBy(nodesByIndex[idx], (node) => {
try {
return node.metadata.layout.rank;
} catch (e) {
return Math.Infinity;
}
})
);
const nodeSize = 100;
const availableWidth = dimensions.width;
const availableHeight = dimensions.height;
const rankHeight = availableHeight / ranks.length;
let rankIndex = 1;
const yCenter = (ranks.length + 1) / 2.0;
_.each(ranks, rank => {
const y = -1 * rankHeight * (rankIndex - yCenter);
const fileWidth = availableWidth / rank.length;
let fileIndex = 1;
const xCenter = (rank.length + 1) / 2.0;
_.each(rank, node => {
node.size = nodeSize;
node.loaded = true;
node.position = {
x: fileWidth * (fileIndex - xCenter),
y: y
};
fileIndex++;
});
rankIndex++;
});
}
class DNSTrafficGraph extends TrafficGraph {
constructor (name, mainView, graphWidth, graphHeight) {
super(name, mainView, graphWidth, graphHeight, DnsNode, DnsConnection, true);
this.linePrecision = 50;
this.state = {
nodes: [],
connections: []
};
this.contextDivs = {};
this.dimensions = {
width: graphWidth,
height: graphHeight
};
this.hasPositionData = true;
}
setState (state) {
try {
_.each(state.nodes, node => {
const existingNodeIndex = _.findIndex(this.state.nodes, { name: node.name });
if (existingNodeIndex !== -1) {
this.state.nodes[existingNodeIndex] = node;
} else {
this.state.nodes.push(node);
}
});
_.each(state.connections, newConnection => {
const existingConnectionIndex = _.findIndex(this.state.connections, { source: newConnection.source, target: newConnection.target });
if (existingConnectionIndex !== -1) {
this.state.connections[existingConnectionIndex] = newConnection;
} else {
this.state.connections.push(newConnection);
}
});
// update maxVolume
// depending on how the data gets fed, we might not have a global max volume.
// If we do not, calculate it based on all the second level nodes max volume.
//
// Just for visual sake, we set the max volume to 150% of the greatest
// connection volume. This allows for buffer room for failover traffic to be
// more visually dense.
let maxVolume = state.maxVolume || 0;
if (!maxVolume) {
_.each(this.state.nodes, node => {
maxVolume = Math.max(maxVolume, node.maxVolume || 0);
});
}
this.state.maxVolume = maxVolume * 1.5;
} catch (e) {
Console.log(e);
}
positionNodes(this.state.nodes, this.dimensions);
super.setState(this.state);
}
}
export default DNSTrafficGraph;
| 14a52fc9653ae891fab1bab27c2d946cd8f38848 | [
"JavaScript"
]
| 2 | JavaScript | jbrekelmans/vizceral | 45ce079a19ad724ea7c865d7f114afb14a676749 | 0ae47a555e8308c48223d51cdb5666d9a73ce8d4 |
refs/heads/master | <repo_name>sanhuamao1/FlyLab<file_sep>/example/demo-jwt/index.js
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
console.log(token);
var decoded = jwt.verify(token, 'shhhhh');
console.log(decoded) // bar | 552dedfea700472cb2a05cb7b820dcfdf3fcbc2a | [
"JavaScript"
]
| 1 | JavaScript | sanhuamao1/FlyLab | 652ec65a3c195265b61dbbc592b30b8be7c4c9e7 | 6048bc5e43b3e12e2169dfbbb7c04138a71f25a3 |
refs/heads/master | <repo_name>lufimon/switchbutton<file_sep>/README.md
# switchbutton
reference https://github.com/zcweng/SwitchButton.git
[](https://jitpack.io/#lufimon/switchbutton)
<file_sep>/app/src/main/java/th/co/cdgs/mobile/switchbutton/MainActivity.kt
package th.co.cdgs.mobile.switchbutton
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import th.co.cdgs.mobile.lib.SwitchButton
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<SwitchButton>(R.id.sw_activitymain).setOnCheckedChangeListener(object : SwitchButton.OnCheckedChangeListener{
override fun onCheckedChanged(view: SwitchButton?, isChecked: Boolean) {
Toast.makeText(this@MainActivity, isChecked.toString(), Toast.LENGTH_SHORT).show()
}
})
}
} | d55c98fcd21185fb947ba83f42813d8d2155712d | [
"Markdown",
"Kotlin"
]
| 2 | Markdown | lufimon/switchbutton | d1910eea6438d5e8c1b9793ce9ba0df7c43e9353 | cc2189637189b07889d6fd92b6db05a882009fbe |
refs/heads/master | <file_sep># silver-basson
<file_sep>/*************************************************************************
> File Name: zuhecoin.c
> Author:
> Mail:
> Created Time: 2018年12月09日 星期日 09时31分58秒
************************************************************************/
#include<stdio.h>
int main(){
int m; // 5分的硬币有m个
int n; // 2分的硬币有n个
int f; // 1分的硬币有f个
/*
* 不适合在m,n=0
* 这样的初始化
* 在后面的 循环结构里面 这是不ok的, m每次循环都为0,这样m不能自加
*/
int k=0; // 解法有k个
for(m; m<=100/5; m++){
for(n; n<=(100-5*m)/2; n++){
f=100-5*m-2*n;
printf("5分的%d个,2分的%d个,1分的%d个\n",m,n,f);
k++;
}
}
printf("组合的方式有%d种\n",k);
return 0;
}
<file_sep>/*************************************************************************
> File Name: square.c
> Author:
> Mail:
> Created Time: 2018年12月09日 星期日 10时21分13秒
> mistake_1: 没有控制每行菱形开始的位置,所以输出为直角三角形
> Mistake_2: 因为每一行之间的步长=1,所以导致了菱形的形状出现问题,实则需要把每行之间的步长(等差)改为2.第一行一个*, 第二行3个,第三行4个
************************************************************************/
#include<stdio.h>
int main(){
int num; // 从键盘提示用户输入数字,代表这这个菱形的对角线宽度
printf("我们的程序是为了输出一个菱形,请您输入这个菱形的对角线宽度,我们将按照您的输入尺寸,输出菱形!\n请输入菱形尺寸(数字),回车结束.\n");
scanf("%d",&num);
int m,n,space; // 分别控制输出的行, 和每行里面有多少个字符,space 控制该行有多少个空格
for(m=1; m<=num; m++){ //上三角,控制每行升序字符数量
//输出每行的空格
for(space=num; space>m; space--){
printf("%c",32);
}
for(n=1; n<=2*m-1; n++){
printf("*");
}
printf("\n");
}
for(m=num-1; m>0; m--){// 控制行,减少字符
for(space=0;space<num-m;space++){//控制每行的空格增加
printf("%c",32);
}
for(n=2*m-1; n>0; n--){//循环多次输出"*"
printf("*");
}
printf("\n");//本行结束,换行
}
printf("输出的菱形的对角线是,您输出尺寸的2倍-1,如上图所示!\n");
printf("改变输入的尺寸,看看效果吧!这是个不错的游戏!\n");
return 0;
}
<file_sep>/*************************************************************************
> File Name: square_biancheng.c
> Author:
> Mail:
> Created Time: 2018年12月10日 星期一 08时10分07秒
************************************************************************/
#include<stdio.h>
#include <stdlib.h>
int main(){
int line; // 菱形的总的行数
int column; // 菱形总的列数
int i; //当前行
int j; //当前列
printf("请输入菱形的行数(奇数):");
scanf("%d", &line);
if(line%2==0){
printf("So sorry, It must be a 奇数\n");
exit(1);
}
column = line; // 总行数和总列数相同
for (i=1; i<=line; i++){
if (i<(line+1)/2 + 1){
for (j=1; j<=column; j++) {
if(((column + 1)/2 -(i - 1))<= j && j <= ((column + 1) / 2 + (i - 1))){ // 实验一下<= >= 符号的优先级是否是最低的
printf("*");
}else{
printf(" ");
}
}
}else{
for(j=1; j<=column; j++){
if((column + 1) / 2 - (line - i) <= j && j<= (column + 1)/2 + (line - i)){ // 实验证明 括号里外都是一样的
printf("*");
}else{
printf(" ");
}
}
}
printf("\n");
}
return 0;
}
<file_sep>/*************************************************************************
> File Name: I_love_the_world_PI.c
> Author:
> Mail:
> Created Time: 2018年12月10日 星期一 13时45分01秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
float s = 1;
float pi = 0;
float i = 1.0;
float n = 1.0;
while(fabs(i)>=1e-6){ // fabs求绝对值的有效方程式,from <MATH.H>
pi+=i;
n=n+2;
//pay attention, we change the positive/ negative operation
s = -s;
i = s / n;
}
pi = 4 * pi;
printf("Pi's value is: %.6f\n", pi);
return 0;
}
<file_sep>/*************************************************************************
> File Name: pai0.c
> Author:
> Mail:
> Created Time: 2018年12月10日 星期一 08时42分36秒
************************************************************************/
#include<stdio.h>
int main(){
int i; // 控制100次连乘的循环
float pai=4; // π的定义, 浮点数
printf("以下的程序我们将会计算π的数值,请稍候!\n");
for(i=1; i<=101; i++ ){
pai = pai * 4 * i * (i + 1) / (2 * i + 1) / (2 * i + 1);
// pai = pai * 2 * i * 2 * ( i + 1 );
// pai = pai / (2 * i + 1) /( 2 * i + 1 );
}
printf("π的计算数值为:%.7f\n", pai);
return 0;
}
<file_sep>/*************************************************************************
> File Name: MP.c
> Author:
> Mail:
> Created Time: 2018年08月22日 星期三 20时38分26秒
************************************************************************/
#include<stdio.h>
//int MP(int data[7]){
//
// int i;
// for(i=0;i<7;i++){
// int j;
// int b;
// //相邻的数组中的大数换到前面,小数换到后面
// for(j=i;j<7;j++){
// b=0;
// if(data[j+1]>data[j]){
//
// b=data[j];
// data[j]=data[j+1];
// data[j+1]=b;
// }
// }
// }
//
// return data[7];
//
//}
int main(){
int a[7];
printf("请输入7个随机整数:\n");
int i,j,b;
for(i=0;i<7;i++){
scanf("%d",&a[i]);
//printf("%d\n",a[i]);
}
for(i=0;i<7;i++){
//相邻的数组中大数到前面,小数换到后面
for(j=0;j<7;j++){
if(a[j]<a[j+1]){
b=a[j];
a[j]=a[j+1];
a[j+1]=b;
}
}
}
printf("冒泡法排序结果:\n");
for(i=0;i<7;i++){
printf("%d\n",a[i]);
}
return 0;
}
<file_sep>/*************************************************************************
> File Name: multiplication_9*9.c
> Author:
> Mail:
> Created Time: 2018年12月09日 星期日 10时05分51秒
************************************************************************/
#include<stdio.h>
int main(){
int m,n;//m控制行,n控制列
printf("九九乘法表如下:\n");
for(m=1; m<=9; m++){
for(n=1; n<=m; n++){
printf("%d*%d=%d\t",m,n,m*n);
}
printf("\n");
}
return 0;
}
<file_sep>/*************************************************************************
> File Name: count_letter_space_digit_others.c
> Author:
> Mail:
> Created Time: 2018年12月09日 星期日 08时26分34秒
************************************************************************/
#include<stdio.h>
int main(){
int c;
int space=0;
int letter=0;
int digit=0;
int other=0;
while((c=getchar())!='\n'){//循环判断
if(c>47&&c<58) digit++;
else if((c>96&&c<123)||(c>64&&c<91)) letter++;
else if(c==32) space++;
else
other++;
}
printf("统计结果显示:\n");
printf("字母有%d个,空格有%d个,数字%d个,其他字符有%d个,总计%d个\n",letter,space,digit,other,letter+space+digit+other);
return 0;
}
| ee0c84b6e521aa0d26d16080db3227056c8ee426 | [
"Markdown",
"C"
]
| 9 | Markdown | LeeCheer00/silver-bassoon | 456b201c800c4e58fb28ad7ade8eac8adfd7a5c7 | 5b6a9887a5b193cfc3277926ae92fc3ba1f9bea8 |
refs/heads/master | <repo_name>visor517/SHRI2020_1<file_sep>/build/script.js
window.onload = function() {
stubs();
document.body.addEventListener('click', clicker);
}
//вставляем заглушки
function stubs() {
var imgList = document.querySelectorAll('.image');
for (var i=0; i<imgList.length; i++) {
var theme = window.getComputedStyle(imgList[i]).backgroundColor; //вычисляем тему по цвету фона
if (theme == 'rgb(255, 255, 255)') {imgList[i].innerHTML ='<svg width="80px" height="64px" viewBox="0 0 80 64" version="1.1"><title>placeholder</title><desc>Created with Sketch.</desc><g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><g id="image-placeholder" transform="translate(-500.000000, -368.000000)" fill="#000000" fill-rule="nonzero"><g id="Group" transform="translate(500.000000, 368.000000)"><g id="placeholder"><path d="M32,16 L48,16 L48,8 L56,8 L56,16 L64,16 L64,24 L72,24 L72,32 L80,32 L80,48 L72,48 L72,40 L64,40 L64,48 L56,48 L56,56 L48,56 L48,48 L32,48 L32,56 L24,56 L24,48 L16,48 L16,40 L8,40 L8,48 L0,48 L0,32 L8,32 L8,24 L16,24 L16,16 L24,16 L24,8 L32,8 L32,16 Z M24,32 L32,32 L32,24 L24,24 L24,32 Z M16,0 L24,0 L24,8 L16,8 L16,0 Z M16,56 L24,56 L24,64 L16,64 L16,56 Z M56,32 L56,24 L48,24 L48,32 L56,32 Z M64,0 L64,8 L56,8 L56,0 L64,0 Z M64,56 L64,64 L56,64 L56,56 L64,56 Z" id="Shape"></path></g></g></g></g></svg>';}
else {imgList[i].innerHTML ='<svg width="80px" height="64px" viewBox="0 0 80 64" version="1.1"><title>placeholder</title><desc>Created with Sketch.</desc><g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><g id="image-placeholder" transform="translate(-620.000000, -368.000000)" fill="#FFFFFF" fill-rule="nonzero"><g id="Group" transform="translate(500.000000, 368.000000)"><g id="placeholder" transform="translate(120.000000, 0.000000)"><path d="M32,16 L48,16 L48,8 L56,8 L56,16 L64,16 L64,24 L72,24 L72,32 L80,32 L80,48 L72,48 L72,40 L64,40 L64,48 L56,48 L56,56 L48,56 L48,48 L32,48 L32,56 L24,56 L24,48 L16,48 L16,40 L8,40 L8,48 L0,48 L0,32 L8,32 L8,24 L16,24 L16,16 L24,16 L24,8 L32,8 L32,16 Z M24,32 L32,32 L32,24 L24,24 L24,32 Z M16,0 L24,0 L24,8 L16,8 L16,0 Z M16,56 L24,56 L24,64 L16,64 L16,56 Z M56,32 L56,24 L48,24 L48,32 L56,32 Z M64,0 L64,8 L56,8 L56,0 L64,0 Z M64,56 L64,64 L56,64 L56,56 L64,56 Z" id="Shape"></path></g></g></g></g></svg>';}
}
}
function clicker(event) {
//переключатель тем
if (event.target.classList.contains('onoffswitch__button')) {
var onoffswitch = event.target.parentNode;
onoffswitch.classList.toggle('onoffswitch_checked');
//смена тем
var themesDefault = document.querySelectorAll('.theme_color_project-default');
var themesInverse = document.querySelectorAll('.theme_color_project-inverse');
for (var i=0; i<themesDefault.length; i++) {
themesDefault[i].classList.remove('theme_color_project-default');
themesDefault[i].classList.add('theme_color_project-inverse');
}
for (var i=0; i<themesInverse.length; i++) {
themesInverse[i].classList.remove('theme_color_project-inverse');
themesInverse[i].classList.add('theme_color_project-default');
}
//меняем заглушки
stubs();
}
//аккордион
var item = event.target.closest('.history__transaction');
if (item != null) {
var item_more = item.querySelector('.e-accordion__more')
item_more.classList.toggle('history__hide');
}
} | a097e0cf20029f5ec2566ad4854a08f91c2dc2a2 | [
"JavaScript"
]
| 1 | JavaScript | visor517/SHRI2020_1 | 4e9c48830f8852c1a9ddf22b1617513fca34afc6 | 7fde3fc0c3045b7ce0c47ab55528ce8425f1d5d2 |
refs/heads/master | <repo_name>Moesif/Moesif-API-Java<file_sep>/README.md
MoesifAPILib
=================
[](https://jitpack.io/#Moesif/Moesif-API-Java)
How To Configure:
=================
The generated client class accepts the configuration parameters in its constructors.
The generated code uses a java library namely UniRest. The reference to this
library is already added as a maven dependency in the generated pom.xml
file. Therefore, you will need internet access to resolve this dependency.
How to Install:
===============
Step 1. Add the JitPack repository to your build file
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Step 2. Add the dependency
<dependency>
<groupId>com.github.Moesif</groupId>
<artifactId>Moesif-API-Java</artifactId>
<version>1.0.1</version>
</dependency>
How to Use:
===========
(See tests for usage examples)
MoesifAPIClient client = new MoesifAPIClient("my_application_id");
ApiController controller = getClient().getApi();
Synchronous Call to add Event:
controller.createEvent(myEventModel);
Asynchronous Call to add Event:
APICallBack<Object> callBack = new APICallBack<Object>() {
public void onSuccess(HttpContext context, Object response) {
assertEquals("Status is not 201",
201, context.getResponse().getStatusCode());
lock.countDown();
}
public void onFailure(HttpContext context, Throwable error) {
fail();
}
};
controller.createEventAsync(myEventModel, callBack);
How to build and install manually (Advanced users):
=============
1. Extract the zip file to a new folder named JavaSDK.
2. Open a command prompt and navigate to the JavaSDK/MoesifAPILib folder.
3. Execute "mvn install", this will install dependencies and also add the generated JAR in your local maven repository.
4. The invoked process will automatically run the JUnit tests and show the results in the console.
5.In your own maven application, add the following lines which will refer to newly installed SDK:
<dependency>
<groupId>MoesifAPILib</groupId>
<artifactId>MoesifAPILib</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
How to build via Eclipse:
=============
For build process do the following:
1. Open Eclipse and click on the "Import" option in "File" menu.
2. Select "General -> Existing Projects into Workspace" option from the tree list.
3. In "Select root directory", provide path to the unzipped archive for the generated code.
4. Click "Finish" and ensure that "Project -> Build Automatically" option is enabled in the menu.
How to Test via Eclipse:
===========
The generated code and the server can be tested using automatically generated test cases.
Junit is used as the testing framework and test runner.
For test process do the following:
1. Select the project MoesifAPILib from the package explorer.
2. Select "Run -> Run as -> Junit Test" or use "Alt + Shift + X" followed by "T" to run the Tests.
How to Export jar:
===========
Export the compiled classes as a java libray (jar). The exported jar can be used as library.
See the following links for more information on this topic.
Exporting JARs:
1. Click on the "Export" option in "File" menu.
2. Select "Java -> JAR file" and click on "Next".
3. Check the box beside "MoesifAPILib" and click on "Finish".
For further details on exporting JARs follow up on the following link.
http://help.eclipse.org/mars/topic/org.eclipse.jdt.doc.user/tasks/tasks-33.htm
Using JARs:
http://help.eclipse.org/juno/topic/org.eclipse.jst.j2ee.doc.user/topics/tjimpapp.html
<file_sep>/src/main/java/com/moesif/api/models/EventResponseBuilder.java
/*
* MoesifAPILib
*
*
*/
package com.moesif.api.models;
import java.util.*;
public class EventResponseBuilder {
//the instance to build
private EventResponseModel eventResponseModel;
/**
* Default constructor to initialize the instance
*/
public EventResponseBuilder() {
eventResponseModel = new EventResponseModel();
}
/**
* Time when response received
*/
public EventResponseBuilder time(Date time) {
eventResponseModel.setTime(time);
return this;
}
/**
* HTTP Status code such as 200
*/
public EventResponseBuilder status(int status) {
eventResponseModel.setStatus(status);
return this;
}
/**
* Key/Value map of response headers
*/
public EventResponseBuilder headers(Object headers) {
eventResponseModel.setHeaders(headers);
return this;
}
/**
* Response body
*/
public EventResponseBuilder body(Object body) {
eventResponseModel.setBody(body);
return this;
}
/**
* IP Address from the response, such as the server IP Address
*/
public EventResponseBuilder ipAddress(String ipAddress) {
eventResponseModel.setIpAddress(ipAddress);
return this;
}
/**
* Build the instance with the given values
*/
public EventResponseModel build() {
return eventResponseModel;
}
} | 5ba824e02dc100c38905a222c493fd7ccf2b11e6 | [
"Markdown",
"Java"
]
| 2 | Markdown | Moesif/Moesif-API-Java | 718aa8595a0281784c74c0d98caba2933f343520 | dd0e7db6821494d33c7f81a5c2696f71fa505b12 |
refs/heads/master | <file_sep>function params(url){
var str = url.split('?')[1];
var items = str.split('&');
var json = {};
for(var i = 0; i < items.length; i++){
var arr = items[i].split('=') ;
json[arr[0]]=arr[1];
}
return json;
}
var url='http://baidu.com?a=11&b=22&c=33';
console.log(params(url)); | 5f88df28bb1cb216cbe7f81f1302877115c0f3b1 | [
"JavaScript"
]
| 1 | JavaScript | xiamo12/String | 0eab1513e9ff429b17edbf83553348acf61d46c1 | b2e6b78447d1040e075edba9bce538038beee33c |
refs/heads/main | <file_sep>var days = ['Chủ Nhật', 'Thứ Hai', 'Thứ Ba', 'Thứa Tư', 'Thứ Năm', 'Thứ Sáu', 'Thứ Bảy'];
let DAY = new Date();
var year,
month,
date,
day,
second,
ms;
let ansDay;
function buildans(D) {
year = D.getFullYear(),
month = D.getMonth(),
date = D.getDate(),
day = D.getDay(),
second = D.getSeconds(),
ms = D.getTime();
let st = D.toISOString();
ansDay = "";
for (var i = 0; i < st.length; i++) {
if (st[i] == "T") break;
ansDay += st[i];
}
}
buildans(DAY);
let event1, event2, eventEnd;
let DAYevent = new Date(year, month, date, 19, 30);
var DAYms = DAYevent.setDate(DAYevent.getDate() + 6 - day);
if (DAYevent.getTime() < DAY.getTime()) {
event1 = new Date(DAYevent.setDate(DAYevent.getDate() + 7));
event2 = new Date(DAYevent.setDate(DAYevent.getDate() + 7));
} else {
event1 = new Date(DAYms);
event2 = new Date(DAYevent.setDate(DAYevent.getDate() + 7));
}
buildans(event1);
document.getElementById("event1Day").innerHTML =
ansDay;
document.getElementById("event1DayBot").innerHTML =
" (" + days[day] + ")";
document.getElementById("event1Start").innerHTML =
ansDay + " " + event1.toLocaleTimeString() + " UTC+" + event1.getTimezoneOffset() / -60;
document.getElementById("event1StartBot").innerHTML = " (" + event1.getTime() / 1000 + ")";
eventEnd = new Date(event1.getTime() + 10800000);
buildans(eventEnd);
document.getElementById("event1End").innerHTML =
ansDay + " " + eventEnd.toLocaleTimeString() + " UTC+" + eventEnd.getTimezoneOffset() / -60;
document.getElementById("event1EndBot").innerHTML = " (" + eventEnd.getTime() / 1000 + ")";
buildans(event2);
document.getElementById("event2Day").innerHTML =
ansDay;
document.getElementById("event2DayBot").innerHTML =
" (" + days[day] + ")";
document.getElementById("event2Start").innerHTML =
ansDay + " " + event2.toLocaleTimeString() + " UTC+" + event2.getTimezoneOffset() / -60;
document.getElementById("event2StartBot").innerHTML = " (" + event2.getTime() / 1000 + ")";
eventEnd = new Date(event2.getTime() + 10800000);
buildans(eventEnd);
document.getElementById("event2End").innerHTML =
ansDay + " " + eventEnd.toLocaleTimeString() + " UTC+" + eventEnd.getTimezoneOffset() / -60;
document.getElementById("event2EndBot").innerHTML = " (" + eventEnd.getTime() / 1000 + ")";
| 25ad0973ad6dbfbdb6b3ba0b423c81e9317a386e | [
"JavaScript"
]
| 1 | JavaScript | fctasta/fctasta.github.io | 30408e5fdfd76964df26fc89cb1b1f49269dda2b | b3c7e534cfac62dbd564b89848acc05ff2aa3cb1 |
refs/heads/master | <file_sep>require "DataFrame.rb"
require "UniSheet.rb"
require "csv"
<file_sep>data_frame
==========
Load and manipulate data into Ruby
==================================
[](http://dx.doi.org/10.5281/zenodo.10772)
##Contributing to data_frame
* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
* Fork the project.
* Start a feature/bugfix branch.
* Commit and push until you are happy with your contribution.
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
##Copyright
Copyright (c) 2014 <NAME>. See LICENSE.txt for
further details. Please contact me for a citation.
<file_sep>require 'data_frame'
require 'minitest'
require 'minitest/autorun'
describe HashHelpers do
it "Returns the length of equally-lengthed hashes" do
assert HashHelpers.equal_length({:a=>[1,2,3], :b=>["a", "v", "a"]}) == 3
assert HashHelpers.equal_length({:a=>[], :b=>[]}) == 0
end
it "Returns false for unequal length hashes" do
assert HashHelpers.equal_length({:a=>[1,2,3], :b=>["a", "a"]}) == false
end
end
describe DataFrame do
it "Initialises with a Hash" do
temp = DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]})
assert temp.data == {:a=>[1, 2, 3], :b=>["a", "v", "a"]}
assert temp.nrow == 3
assert temp.ncol == 2
assert_raises(RuntimeError) {DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a", "d"]})}
end
it "Appends rows from a DataFrame or Hash" do
first = DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]})
second = DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]})
first << second
assert first.data == {:a=>[1, 2, 3, 1, 2, 3], :b=>["a", "v", "a", "a", "v", "a"]}
assert first.nrow == 6
second << {:a=>[1,2,3], :b=>["a", "v", "a"]}
assert second.data == {:a=>[1, 2, 3, 1, 2, 3], :b=>["a", "v", "a", "a", "v", "a"]}
assert second.nrow == 6
end
it "Appends single elements from a DataFrame or Hash" do
first = DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]})
second = DataFrame.new({:a=>[4], :b=>["b"]})
first << second
assert first.data == {:a=>[1, 2, 3, 4], :b=>["a", "v", "a", "b"]}
assert first.nrow == 4
third = DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]})
fourth = {:a=>[4], :b=>["b"]}
third << fourth
assert first.data == third.data
end
it "Allows access to columns" do
first = DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]})
assert first[:a] == [1,2,3]
end
it "Iterates columns" do
columns = []; values = []
first = DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]})
first.each_column do |x,y|
y.each do |z|
columns << x
values << z
end
end
assert columns == [:a, :a, :a, :b, :b, :b]
assert values == [1, 2, 3, "a", "v", "a"]
end
it "Iterates rows" do
x = []; y = []
first = DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]})
first.each_row do |a,b|
x << a
y << b
end
assert x == [1, 2, 3]
assert y == ["a", "v", "a"]
merged = []
first.each_row {|x| merged << x}
assert merged == [[1, "a"], [2, "v"], [3, "a"]]
end
it "Checks for equality" do
assert DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]}) == DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]})
assert DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]}) != DataFrame.new({:a=>[1,2,3,4], :b=>["a", "v", "a", "b"]})
end
it "Adds columns" do
first = DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]})
first.insert :test
assert first.nrow == 3
assert first.ncol == 3
assert first[:test] == ['', '', '']
end
it "Delete columns" do
first = DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]})
first.delete :a
assert first.nrow == 3
assert first.ncol == 1
end
it "Has a copy constructor" do
first = DataFrame.new({:a=>[1,2,3], :b=>["a", "v", "a"]})
second = first.dup
second[:a][0] = "asd"
second.delete :a
second.col_names[1] = "derp"
assert first[:a][0] != "asd"
assert first.ncol == 2
end
end
<file_sep>#Allows loading and iterating over Excel (xls and xlsx) and CSV files
#without requiring the user to know what kind of file they're opening.
#Poorly tested, and doesn't attempt to handle exceptions thrown from
#underlying classes (e.g., file not found errors)
class UniSheet
#Getters
attr_reader :file_name, :file_type
#Load in a file
#@param [String] Location of file to be opened
#@param [String] Optional: file type to be loaded, one of 'csv', 'xls', or 'xlsx'
#@return UniSheet object
def initialize(file_name, file_type=nil)
#Detect filetype if not given
@file_name = file_name
if not file_type
if file_name[".csv"]
@file_type = "csv"
@csv = CSV.read @file_name
return @file_type
elsif file_name[".xlsx"]
@xlsx_book = RubyXL::Parser.parse file_name
@xlsx_sheet = @xlsx_book.worksheets[0].extract_data
@file_type = "xlsx"
#Do our best not to get extra folders popping up all over the place
#sleep 1
return @file_type
elsif file_name[".xls"]
@excel_book = Spreadsheet.open file_name
@excel_sheet = @excel_book.worksheet 0
@file_type = "xls"
return @file_type
else
raise RuntimeError, "File #{file_name} of undetectable or unsupported filetype"
end
end
@file_type = file_type
return @file_type
end
#Iterator
def each(&block)
case
when @file_type=="csv"
@csv.each(&block)
when @file_type=="xls"
@excel_sheet.each(&block)
when @file_type=="xlsx"
@xlsx_sheet.each(&block)
else
raise RuntimeError, "File #{@file_name} used in improperly defined UniSheet class"
end
end
#Pull out a row; returns an array so columns can also be called in this way
def [](index)
case
when @file_type=="csv"
return @csv[index]
when @file_type=="xls"
return @excel_sheet.row(index).to_a
when @file_type=="xlsx"
return @xlsx_sheet[index]
else
raise RuntimeError, "File #{@file_name} used in improperly defined UniSheet class"
end
end
#Change sheet if xls or xlsx file; give it a sheet number (starting at 0)
def set_sheet(sheet)
if @file_type == "xls"
@excel_sheet = @excel_book.worksheet sheet
elsif @file_type == "xlsx"
@xlsx_sheet = @xlsx_book.worksheets[sheet].extract_data
else
raise RuntimeError, "File #{@file_name} is not an xls or xlsx file, so cannot change sheet"
end
end
#Find number of sheets if xls or xlsx file
def n_sheets()
if @file_type == "xls"
return @excel_book.sheet_count
elsif @file_type == "xlsx"
return @xlsx_book.worksheets.size
else
raise RuntimeError, "File #{@file_name} is not an xls or xlsx file, so has only one sheet"
end
end
end
<file_sep>#Interal helpers to check all members of a Hash have the same length
module HashHelpers
#Check all items of a hash are of equal length
#@param hash hash to be checked for length
#@return return Either length of each item or false if not all equal
def self.equal_length(hash)
hash_length = []
hash.each {|key, value| hash_length << value.length}
if hash_length.uniq.length == 1
return hash_length[0]
else
return false
end
end
end
#Class to hold data
# @param [Hash] Hash to be converted to a DataFrame
# @return [DataFrame] DataFrame object
class DataFrame
include HashHelpers
#Getters
attr_reader :nrow, :ncol, :col_names, :data
#Create DataFrame with a hash
# @param [Hash] Hash to be converted to a DataFrame
# @return [DataFrame] DataFrame object
def initialize(input_hash)
#Assert that input object is compatible
unless input_hash.is_a? Hash then raise RuntimeError, "Must create a DataFrame with a Hash" end
unless HashHelpers.equal_length(input_hash) then raise RuntimeError, "Cannot add a hash with unequal element lengths to a data_base" end
#Setup parameters
@data = input_hash
@nrow = HashHelpers.equal_length(input_hash)
@ncol = @data.keys.length
@col_names = @data.keys
end
#Copy constructor
def initialize_copy(orig)
#Can't do this using .dup or you won't copy the arrays within the hash...
@data = Marshal::load(Marshal.dump(@data))
@nrow = @nrow
@ncol = @ncol
@col_names = @col_names.dup
end
#Access individual columns of data
def [](element)
return self.data[element]
end
#Insert a new, empty column
def insert(column)
if @col_names.include? column then raise RuntimeError, "Cannot add a column whose name is already taken in DataFrame" end
@data[column] = [''] * @nrow
@ncol += 1
@col_names.push column
return column
end
#Delete a column by name
def delete(column)
if !@col_names.include? column then raise RuntimeError, "Attempting to remove non-existant column from DataFrame" end
@data.delete(column)
@ncol -= 1
@col_names = @col_names - [column]
return column
end
#Append a DataFrame or Hash
def <<(binder)
if binder.is_a? DataFrame
unless self.data.keys.sort == binder.data.keys.sort then raise RuntimeError, "Cannot merge DataFrames with non-matching columns" end
binder.data.each do |key, value|
@data[key] << value
@data[key].flatten!
end
@nrow += HashHelpers.equal_length(binder.data)
elsif binder.is_a? Hash
unless self.data.keys.sort == binder.keys.sort then raise RuntimeError, "Cannot merge DataFrame and Hash with non-matching elements" end
unless HashHelpers.equal_length(binder) then raise RuntimeError, "Cannot merge DataFrame with non-equal-length Hash" end
binder.each do |key, value|
@data[key] << value
@data[key].flatten!
end
@nrow += HashHelpers.equal_length(binder)
else
raise RuntimeError, "Can only merge DataFrame with a DataFrame or Hash"
end
return @nrow
end
#Equality checking
def ==(comparison)
if comparison.is_a? DataFrame and self.data == comparison.data and self.nrow == comparison.nrow and self.ncol == comparison.ncol and self.col_names == comparison.col_names
return true
else
return false
end
end
#Iterator along each column
def each_column
@data.each do |column, value|
yield column, value
end
end
#Iterator along each row
def each_row
(0...@nrow).each do |i|
yield @data.keys.map {|x| @data[x][i]}
end
end
end
<file_sep>require 'data_frame'
require 'minitest'
require 'minitest/autorun'
require "spreadsheet"
require "csv"
require "rubyXL"
describe UniSheet do
before do
@csv_test = UniSheet.new "dataFrame.csv"
@xls_test = UniSheet.new "dataFrame.xls"
@xlsx_test = UniSheet.new "dataFrame.xlsx"
end
describe "When loading a CSV file" do
it "Will iterate correctly" do
temp = []
@csv_test.each {|line| temp << line[0]}
assert_equal ["Name", "<NAME>", "<NAME>"], temp
end
it "Will load a row correctly" do
@csv_test[0].must_equal ["Name", "Emailed?", "Confirmed?", "Emailed Re. Payment?","Paid?"]
end
it "Doesn't have sheets" do
proc {@csv_test.set_sheet(1)}.must_raise RuntimeError
end
end
describe "When loading an XLS file" do
it "Will iterate correctly" do
temp = []
@xls_test.each {|line| temp << line[0]}
assert_equal ["Name", "<NAME>", "<NAME>"], temp
end
it "Will load a row correctly" do
@xls_test[0].must_equal ["Name", "Emailed?", "Confirmed?", "Emailed Re. Payment?","Paid?"]
end
it "Handles multiple sheets" do
@xls_test.set_sheet 1
assert @xls_test[0] == ["Another sheet"]
end
end
describe "When loading an XLSX file" do
it "Will iterate correctly" do
temp = []
@xlsx_test.each {|line| temp << line[0]}
assert_equal ["Name", "<NAME>", "<NAME>"], temp
end
it "Will load a row correctly" do
@xlsx_test[0].must_equal ["Name", "Emailed?", "Confirmed?", "Emailed Re. Payment?","Paid?"]
end
it "Handles multiple sheets" do
@xlsx_test.set_sheet 1
assert @xlsx_test[0][0] == "Another sheet"
assert @xlsx_test.n_sheets == 2
assert @xls_test.n_sheets == 2
assert_raises(RuntimeError) {@csv_test.n_sheets}
end
end
describe "When loading files" do
it "Can ignore file endings if asked" do
@trick = UniSheet.new("test_files/dataFrameXLSTrick.csv", "xls")
temp = []
@xls_test.each {|line| temp << line[0]}
assert_equal ["Name", "<NAME>", "<NAME>"], temp
end
end
end
| 86a8339350e832d029f01af911ff29ac0a4d28c9 | [
"Markdown",
"Ruby"
]
| 6 | Ruby | willpearse/data_frame | 412212a34e1034ea0a19c36203c6f755f5e79668 | 0318dd260a35a3f4c5d3b59e24dd0b075d397e8b |
refs/heads/master | <repo_name>WilsonKinyua/shop-interview<file_sep>/store.php
<?php
include "config/config.php";
if($_POST["query"] != '') {
$search_array = explode(",", $_POST["query"]);
$store_owner = "'" . implode("', '", $search_array) . "'";
$query = "SELECT * FROM stock_mobile WHERE store_owner = " . $store_owner;
} else {
$query = "SELECT * FROM stock_mobile";
}
$data = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($data)) {
$date_create = date_create($row['date']);
$date = date_format($date_create, 'g:ia \o\n l jS F Y');
$id = $row['id'];
echo '<tr class="row100 body">';
echo "<td class='column1'>" . $id . "</td>";
echo "<td class='column2'>" . $row['store_owner'] . "</td>";
echo "<td class='column3'>" . $row['product'] . "</td>";
echo "<td class='column4'>" . $row['quantity_available'] . "</td>";
echo "<td class='column5'><a href='sold.php?sold=$id'>" . $row['sold'] . "</a></td>";
echo "<td class='column6'>" . $date . "</td>";
echo "<td class='column7'>" . $row['clear_status'] . "</td>";
echo "<td class='column8'><a class='btn btn-primary btn-sm' href='edit.php?edit=$id'>Edit</a></td>";
echo "<td class='column9'><a class='btn btn-danger btn-sm' href='delete.php?delete=$id'>Delete</a></td>";
echo "</tr>";
}
<file_sep>/delete.php
<?php
include "config/config.php";
if(isset($_GET['delete'])) {
$id = $_GET['delete'];
$query = "DELETE FROM stock_mobile WHERE id = " . $id;
$conn = mysqli_query($connection, $query);
$_SESSION['danger'] = "Delete Successfull!";
header('location: index.php');
}
?><file_sep>/sold.php
<?php
include "include/header.php";
include "config/config.php";
?>
<div class="container mt-5">
<form action="" method="POST">
<?php
if (isset($_GET['sold'])) {
$id = $_GET['sold'];
$query = "SELECT * FROM stock_mobile WHERE id = " . $id;
$select_items = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($select_items)) {
$store_owner = $row['store_owner'];
$product = $row['product'];
$quantity_available = $row['quantity_available'];
$sold = $row['sold'];
$date = $row['date'];
$clear_status = $row['clear_status'];
?>
<?php }
} ?>
<?php
if (isset($_POST['submit'])) {
$store_owner = $_POST['store_owner'];
$product = $_POST['product'];
$quantity_available = $_POST['quantity_available'];
$sold = $_POST['sold'];
$date = $_POST['date'];
$clear_status = $_POST['clear_status'];
$query = "UPDATE stock_mobile SET store_owner = '{$store_owner}', product = '{$product}', quantity_available = '{$quantity_available}' , sold = '{$sold}', date = '{$date}', clear_status = '{$clear_status}' WHERE id = {$id} ";
$update_query = mysqli_query($connection, $query);
$_SESSION['success'] = "Updated Successfully!";
header("Location: index.php");
if (!$update_query) {
die("QUERY FAILED" . mysqli_error($connection));
}
}
?>
<h3 class="m-5 text-uppercase">Edit Page for ONLY sold column</h3>
<div class="form-row">
<div class="form-group col-md-6">
<label for="store_owner">Store Owner(disabled)</label>
<input type="text" class="form-control" id="store_owner" name="store_owner" disabled value="<?php echo $store_owner; ?>">
</div>
<div class="form-group col-md-6">
<label for="product">Product(disabled)</label>
<input type="text" class="form-control" id="product" name="product" disabled value="<?php echo $product; ?>">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="quantity_available">Quantity Available(disabled)</label>
<input type="text" class="form-control" id="quantity_available" disabled name="quantity_available" value="<?php echo $quantity_available; ?>">
</div>
<div class="form-group col-md-6">
<label for="product">Sold</label>
<input type="text" class="form-control" id="sold" name="sold" value="<?php echo $sold; ?>">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="date">Date(disabled)</label>
<input type="date" class="form-control" id="timePicker" disabled name="date" placeholder="<?php echo $date; ?>">
</div>
<div class="form-group col-md-6">
<label for="cleat_status">Clear Status(disabled)</label>
<input type="text" class="form-control" id="clear_status" disabled name="clear_status" value="<?php echo $clear_status; ?>">
</div>
</div>
<div class="d-flex justify-content-center">
<button type="submit" name="submit" class="btn btn-secondary btn-lg">Update Item</button>
</div>
</form>
</div>
<?php include "include/footer.php" ?><file_sep>/edit.php
<?php
include "include/header.php";
include "config/config.php";
?>
<div class="container mt-5">
<form action="" method="POST">
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$query = "SELECT * FROM stock_mobile WHERE id = " . $id;
$select_items = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($select_items)) {
$store_owner = $row['store_owner'];
$product = $row['product'];
$quantity_available = $row['quantity_available'];
$sold = $row['sold'];
$date = $row['date'];
$clear_status = $row['clear_status'];
?>
<?php }
} ?>
<?php
if (isset($_POST['submit'])) {
$store_owner = $_POST['store_owner'];
$product = $_POST['product'];
$quantity_available = $_POST['quantity_available'];
$sold = $_POST['sold'];
$date = $_POST['date'];
$clear_status = $_POST['clear_status'];
$query = "UPDATE stock_mobile SET store_owner = '{$store_owner}', product = '{$product}', quantity_available = '{$quantity_available}' , sold = '{$sold}', date = '{$date}', clear_status = '{$clear_status}' WHERE id = {$id} ";
$update_query = mysqli_query($connection, $query);
$_SESSION['success'] = "Updated Successfully!";
header("Location: index.php");
if (!$update_query) {
die("QUERY FAILED" . mysqli_error($connection));
}
}
?>
<h3 class="m-5 text-uppercase">Edit Page for Store Owner : <?php echo $store_owner; ?></h3>
<div class="form-row">
<div class="form-group col-md-6">
<label for="store_owner">Store Owner</label>
<input type="text" class="form-control" id="store_owner" name="store_owner" value="<?php echo $store_owner; ?>">
</div>
<div class="form-group col-md-6">
<label for="product">Product</label>
<input type="text" class="form-control" id="product" name="product" value="<?php echo $product; ?>">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="quantity_available">Quantity Available</label>
<input type="text" class="form-control" id="quantity_available" name="quantity_available" value="<?php echo $quantity_available; ?>">
</div>
<div class="form-group col-md-6">
<label for="product">Sold</label>
<input type="text" class="form-control" id="sold" name="sold" value="<?php echo $sold; ?>">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="date">Date</label>
<input type="date" class="form-control" id="timePicker" name="date" value="<?php echo $date; ?>">
</div>
<div class="form-group col-md-6">
<label for="cleat_status">Clear Status</label>
<input type="text" class="form-control" id="clear_status" name="clear_status" value="<?php echo $clear_status; ?>">
</div>
</div>
<div class="d-flex justify-content-between">
<div>
<button type="submit" name="submit" class="btn btn-primary btn-lg">Update</button>
</div>
<div>
<a href="delete.php?delete=<?php echo $id; ?>'" type="submit" class="btn btn-danger btn-lg">Delete</a>
</div>
</div>
</form>
</div>
<?php include "include/footer.php" ?> | 312f80e2f346da4a2cf309e45b144d9d07287537 | [
"PHP"
]
| 4 | PHP | WilsonKinyua/shop-interview | f4c5c4b05651efe8e16d6162146fb8ded4b82799 | d37d8e6778d0e40d1e194b2cbc22df00b66a90ed |
refs/heads/Donald-Whitely | <file_sep>const Validator = require('validator');
const isEmpty = require('./isEmpty');
module.exports = function validateTaskInput(data) {
let errors = {};
data.username = !isEmpty(data.todo) ? data.todo : '';
if (Validator.isEmpty(data.todo)) {
errors.todo = 'A todo is required';
}
return {
errors,
isValid : isEmpty(errors),
};
};
<file_sep>const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const key = process.env.SECRET_KEY;
const passport = require('passport');
const TodoUser = require('../../models/User');
const validateRegisterInput = require('../../validation/register');
const validateLoginInput = require('../../validation/login');
const validateTaskInput = require('../../validation/task');
router.get('/test', (req, res) => res.json({ msg: 'Users working' }));
router.get('/tasks', passport.authenticate('jwt', { session: false }), (req, res) => {
TodoUser.findById({ _id: req.user.id }).then(user => res.json(user.tasks)).catch(err => console.log(err));
});
router.post('/register', (req, res) => {
const { errors, isValid } = validateRegisterInput(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
TodoUser.findOne({ username: req.body.username }).then(user => {
if (user) {
errors.username = 'Username already exists';
return res.status(400).json(errors);
}
});
const newUser = new TodoUser({
name : req.body.name,
username : req.body.username,
password : <PASSWORD>,
tasks : [],
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser.save().then(user => res.json(user)).catch(err => console.log(err));
});
});
});
router.post('/login', (req, res) => {
const { errors, isValid } = validateLoginInput(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
const username = req.body.username;
const password = req.body.password;
TodoUser.findOne({ username }).then(user => {
if (!user) {
errors.username = 'User not found';
return res.status(404).json(errors);
}
bcrypt.compare(password, user.password).then(isMatch => {
if (isMatch) {
const payload = {
id : user.id,
name : user.name,
username : user.username,
};
jwt.sign(payload, key, { expiresIn: 3600 }, (err, token) => {
res.json({
sucess : true,
token : `Bearer ${token}`,
});
});
} else {
errors.password = '<PASSWORD>';
return res.status(400).json(errors);
}
});
});
});
router.post('/add-task', passport.authenticate('jwt', { session: false }), (req, res) => {
const { errors, isValid } = validateTaskInput(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
TodoUser.findOne({ _id: req.user.id }).then(user => {
const newTask = {
todo : req.body.todo,
};
user.tasks = [ ...user.tasks, newTask ];
user.save().then(user => res.json(user));
});
});
router.put('/update-task/:taskId', passport.authenticate('jwt', { session: false }), (req, res) => {
const { errors, isValid } = validateTaskInput(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
let updatedUser = {};
updatedUser = req.user;
const updatedTasks = updatedUser.tasks.map(task => {
if (task._id.toString() === req.params.taskId) {
const updatedTask = {
_id : req.params.taskId,
todo : req.body.todo,
date : req.body.date,
completed : req.body.completed,
};
return updatedTask;
} else {
return task;
}
});
updatedUser.tasks = updatedTasks;
TodoUser.findOneAndUpdate({ _id: req.user.id }, { $set: updatedUser }, { new: true }).then(user => res.json(user));
});
router.put('/delete-task/:taskId', passport.authenticate('jwt', { session: false }), (req, res) => {
let updateUser = req.user;
const updatedTasks = updateUser.tasks.filter(task => task._id.toString() !== req.params.taskId);
updateUser.tasks = updatedTasks;
TodoUser.findOneAndUpdate({ _id: req.user.id }, { $set: updateUser }, { new: true }).then(user => res.json(user));
});
router.put('/delete-completed', passport.authenticate('jwt', { session: false }), (req, res) => {
let updateUser = req.user;
const updateTasks = updateUser.tasks.filter(task => !task.completed);
updateUser.tasks = updateTasks;
TodoUser.findOneAndUpdate({ _id: req.user.id }, { $set: updateUser }, { new: true }).then(user => res.json(user));
});
module.exports = router;
<file_sep>const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const passport = require('passport');
const validateTaskInput = require('../../validation/task');
const TodoUser = require('../../models/User');
router.post('/addtask', passport.authenticate('jwt', { session: false }), (req, res) => {
const { errors, isValid } = validateTaskInput(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
Task.findOne({ user: req.user.id }).then(task => {
const newTask = {
user : req.user.id,
todo : req.body.todo,
date : Date.now,
completed : false,
};
task.unshift(newTask);
task.save().then(task => res.json(task));
});
});
| b6371495e18281f1ced18d3e9facfe4cb4cccb4a | [
"JavaScript"
]
| 3 | JavaScript | dswhitely1/todoserver | b3e8e6442a375844439e4167db3cc0477e7c1486 | 554087066268b89f21f72fcf72f4fa6ca6d76761 |
refs/heads/master | <repo_name>deepakgorijala/team-manager<file_sep>/app/models/person.rb
class Person < ApplicationRecord
has_many :phone
has_and_belongs_to_many :addresses
end
<file_sep>/app/models/address.rb
class Address < ApplicationRecord
has_and_belongs_to_many :people
end
| a6f1ed2bf06303ba3cc59446843f4f938c9eb96e | [
"Ruby"
]
| 2 | Ruby | deepakgorijala/team-manager | b34eec8fc285ba1f785d83c343b1983ce1a5d8dc | e63edf0548548fcd1db96d8444560d1c568dfca7 |
refs/heads/master | <repo_name>zhoucaifu/ZCF<file_sep>/src/main/resources/static/js/queryAll.js
function(){
function queryAll(){
$.ajax({
type : "post",
url : "/queryAll",
data : "user:${list}",
dataType : map,
success : function(result) {
var result = eval('(' + result + ')');
$('#id').text(result.id);
$('#username').text(result.username);
$('#pwd').text(result.password);
}
}
}
}
<file_sep>/src/main/resources/static/js/Person.js
function Person(age,name){
this.sayHello = function(){
alert("说好")
}
}
function Student(score){
this.sayScore = function(){
alert("说成绩")
}
}
Student.prototype = new Person();
Student.prototype.bark = function () {
document.write("Student继承Person<br/>");
} | d4c80b28e35c606de8383d847b8b138578d78b1b | [
"JavaScript"
]
| 2 | JavaScript | zhoucaifu/ZCF | 1bf9877395ba7e4d09d6708f00f5ad1d42b28d06 | be59b359f954103ec0b442bc60a5c94647d9e725 |
refs/heads/master | <repo_name>sirlancelot/vim<file_sep>/readme.mkdn
# sirlancelot's dot vimrc
Keeping things minimal yet convenient. Find out how to
[install it](#installation), then learn the [key mappings](#key-mappings). If
you're on a Mac, get your [terminal settings right](#mac-terminal-settings).
Find out what [plugins](#plugins-used) I used. If you're feeling generous, you
can even [contribute](#contribute-pull-requests).
## installation
Install on Unix-based machines:
$ git clone --recursive https://github.com/sirlancelot/vim ~/.vim
$ ./extra/install.sh
You do not need to link `gvimrc.vim` as it is loaded at the bottom of `vimrc.vim`
Install on other platforms: just copy or link `vimrc.vim` to your
home directory and call it `.vimrc` or `_vimrc` on Windows.
## key mappings
Leader Key: `,` *(comma)*
- Use `<leader>ev` and `<leader>eg` to edit vimrc and gvimrc respectively.
They will be automatically reloaded when you save.
- Hit `<space>` on a fold to toggle open or close. `<s-space>` is recursive.
- `<tab>` will toggle `'list'` which will visualize tabs and trailing
whitespace.
- `<tab>` and `<s-tab>` with a selection will indent and unindent,
respectively.
- `<s-T>` in normal mode will strip all trailing whitespace.
## mac terminal settings
If the `<Home>` and `<End>` keys aren't working for you in Console Vim, you need to
add the following changes to your Terminal Preferences Keyboard Settings:
- Key: `Home`, Escape Sequence: `\033OH`
- Key: `End`, Escape Sequence: `\033OF`
Note: `\033` is typed by pressing `<Escape>` when the cursor is in the text box.
## plugins used
All plugins are placed in the `bundle/` subfolder and are git submodules. Each
bundle is loaded using [Pathogen][]. Rather than clutter up the `.vim` root
folder, my personal additions have been placed either in the `*vimrc.vim` or
`personal/`
- [Coffee-Script](https://github.com/kchmck/vim-coffee-script)
- [Ctrl-P](https://github.com/kien/ctrlp.vim)
- [Fugitive](https://github.com/tpope/vim-fugitive)
- [Git](https://github.com/tpope/vim-git) *updated runtime for Fugitive*
- [Indent Guides](https://github.com/nathanaelkane/vim-indent-guides)
- [Jekyll](https://github.com/csexton/jekyll.vim)
- [Markdown](https://github.com/tpope/vim-markdown.git)
- [Solarized](https://github.com/altercation/vim-colors-solarized)
- [Supertab](https://github.com/ervandew/supertab)
- [Surround](https://github.com/tpope/vim-surround)
- [TabMan](https://github.com/kien/tabman.vim)
- [ZenCoding](https://github.com/mattn/zencoding-vim)
[Pathogen]: https://github.com/tpope/vim-pathogen
## contribute pull requests
Pull Requests will only be merged if they are based off the tip of the
[develop][] branch. Please rebase (don't merge!) your changes if you are behind.
To learn about why rebase is better than merge, check out [The Case for Git
Rebase][rebase].
In short, to bring your Working Copy up to the tip of [develop][], you can use the
rebase feature: `git pull --rebase`. See [Pull with Rebase][pull] for details.
[develop]: /sirlancelot/vim/tree/develop
[rebase]: http://darwinweb.net/articles/the-case-for-git-rebase
[pull]: http://gitready.com/advanced/2009/02/11/pull-with-rebase.html
<file_sep>/extra/update-submodules.sh
#!/bin/sh
git submodule foreach "git checkout -q master && git pull --ff-only"
<file_sep>/extra/install.sh
#!/bin/bash
RCDIR=$HOME/.vim
NOW=$(date +%s)
cd "$HOME"
if [ -f .vimrc -a ! -h .vimrc ]; then
echo "Backing up old vimrc..."
mv .vimrc .vimrc-saved-$NOW
fi
echo "Linking new vimrc..."
ln -sf .vim/vimrc.vim .vimrc
cd "$RCDIR"
echo "(Re)Initializing submodules..."
git submodule update --init
if [ ! -f vimrc.local.vim ]; then
echo "Copying sample local vimrc..."
cp extra/vimrc.local.sample vimrc.local.vim
echo "You can now open and customize ~/.vim/vimrc.local.vim"
fi
<file_sep>/extra/bump-version.sh
#!/bin/sh
GITROOT=$(git rev-parse --show-toplevel)
usage() {
echo "usage: $0 <version>"
}
Version=$1
if [ -z $Version ]; then
usage
exit 1
fi
cd "$GITROOT"
git ls-files "*.vim" | while read File; do
if ! grep -Eq "^\" Version: v.+$" "$File"; then
continue
fi
echo "Bumping version number in $File..."
if ! sed "s/^\(\" Version: \)v.*$/\1v$Version/" "$File" > "$File~"; then
echo "Could not replace Version in $File." >&2
exit 2
fi
mv "$File~" "$File"
git add "$File"
done
echo "Now run: git commit -m \"Bumped version to v$Version\""
| 51cb7fc7bf943d5e5d84db2ce6aad7d0109f8b58 | [
"Markdown",
"Shell"
]
| 4 | Markdown | sirlancelot/vim | b2ee1bc7071c59ce9421d372e0c5725d3ed2c75f | bfe2300cd6b4765540afb68d59d09ee49592edd4 |
refs/heads/master | <file_sep>import React from "react";
import Mentioner from "./Mentioner";
function TopMentionersList({ topMentioners }) {
return (
<div className="col col-lg-4 d-none d-lg-block">
<div className="mentions-right-column">
<div className="prestigio-pane mb-3 prestigio-shadow">
<h4 className="px-2 pt-2">Top mentioners</h4>
<div className="mentions-mentioner-group">
{topMentioners.slice(0, 5).map((mentioner, index) => (
<Mentioner
mentioner={mentioner}
index={index}
key={mentioner.key}
/>
))}
</div>
</div>
</div>
</div>
);
}
export default TopMentionersList;
<file_sep>import React, { useState } from "react";
import Error from "./Error";
function SearchBox({ saveQuery, saveOrderField }) {
const [searchedTerm, saveSearchedTerm] = useState("");
// Handle select field
const [error, saveError] = useState(false);
const searchPost = e => {
e.preventDefault();
// Validate
if (searchedTerm === "") {
saveError(true);
return;
}
// Validate term to main component
saveError(false);
saveQuery(searchedTerm);
};
const requestData = e => {
if (e.key === "Enter") {
saveQuery(searchedTerm);
}
};
return (
<form onSubmit={searchPost} className="prestigio-responsive-central-pane">
<div className="form-row pr-close-row">
<div className="form-group col col-12 col-md-4 mb-2 mb-md-3">
<select
onKeyDown={e => requestData(e.target.value)}
onChange={e => saveOrderField(e.target.value)}
className="form-control prestigio-new-input w-100 pr-select">
<option value="post_created_at">Date</option>
<option value="usersid">Name</option>
</select>
</div>
<div className="form-group col col-12 col-md-auto ml-auto mb-3">
<div className="prestigio-search">
<input
type="search"
className="form-control prestigio-new-input w-100"
placeholder="Search..."
onKeyDown={e => requestData(e.target.value)}
onChange={e => saveSearchedTerm(e.target.value)}
/>
{/* TODO: review this, is it duplicated? */}
<button
type="button"
className="form-control prestigio-search-input-btn"
>
<i className="pr-icon-search"></i>
</button>
</div>
</div>
</div>
{error ? <Error message="Use a valid term to search!" /> : null}
</form>
);
}
export default SearchBox;
<file_sep>import React from "react";
const Mentioner = ({ mentioner, index }) => {
const { name, picture, length } = mentioner;
return (
<a
href="#"
className="no-style mentions-mentioner d-flex align-items-center"
>
<div className="mentions-mentioner-place">{index + 1}</div>
<div
className="prestigio-thumbnail mentions-mentioner-thumb mr-2"
style={{ backgroundImage: `url(${picture})` }}
></div>
<p className="small-text mb-0 ellipsis">{name}</p>
<p className="small-text op-67 mb-0 ml-auto mr-1">{length}</p>
</a>
);
};
export default Mentioner;
<file_sep>import React from "react";
const TaggedBrand = ({ brand }) => {
const { brand_logo_url, brand_name } = brand.brand[0];
// brand_url is required
return (
<a href="" className="no-style">
<div className="profile-timeline-tag mr-0 d-flex align-items-center prestigio-shadow">
<div
className="prestigio-thumbnail mr-2"
style={{ backgroundImage: `url(${brand_logo_url})` }}
></div>
<p className="mb-0 small-text ellipsis">{brand_name}</p>
</div>
</a>
);
};
export default TaggedBrand;
<file_sep>import React from "react";
import ReactHashtag from "react-hashtag";
import TaggedBrandList from "./TaggedBrandList";
const SocialPost = ({ post }) => {
const {
facebook,
instagram,
mentions,
post_content,
post_created_at,
post_metrics,
social
} = post;
const { name, url, picture } =
facebook.length > 0 ? facebook[0].accountinfo : instagram[0].accountinfo;
const { engagement, reach } =
facebook.length > 0
? facebook[0].accountmetrics
: instagram[0].accountmetrics;
const socialClass = `ptp-h-sn ${social}`;
const post_date = new Date(Date.parse(post_created_at));
return (
<div className="mention-row">
<div className="mention-body">
<div className="row pr-close-row">
<div className="col col-12 col-md-7 mb-2">
<a
href=""
className="no-style"
rel="noopener noreferrer"
target="_blank"
>
{/* TODO: post url is required */}
<div className="profile-timeline-post pb-2 mb-0 prestigio-shadow">
<div className="ptp-header mb-2 d-flex justify-content-between relative">
<div className="ptp-header-left d-flex">
<div
className="prestigio-thumbnail"
style={{ backgroundImage: `url(${picture})` }}
></div>
<div className="ptp-header-left-text ml-2 d-flex flex-column justify-content-between">
<div className="ptp-header-name">{name}</div>
<div className="ptp-header-info">
<span className={socialClass}>{social}</span>
<span className="ptp-h-sep"> . </span>
<span className="ptp-h-date">
{post_date.toLocaleString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "numeric",
hour12: false
})}
</span>
<span className="ptp-h-sep"> . </span>
<span className="ptp-h-prv">
<i className="pr-icon-world"></i>
</span>
</div>
</div>
</div>
</div>
<div className="ptp-content mb-2">
<div className="ptp-c-text">
<p className="mb-0">
{/* TODO: Get the hashtag url*/}
<ReactHashtag
renderHashtag={hashtagValue => (
<object type="prestigio/link">
<a href="/influencer/hashtag-results.html">
{hashtagValue}
</a>
</object>
)}
>
{post_content.text}
</ReactHashtag>
</p>
</div>
<div className="ptp-c-thumb">
<img src={post_content.picture} alt="" />
</div>
</div>
<div className="ptp-footer d-flex">
<div className="ptp-f-container d-flex align-items-center">
<div className="ptp-f-icon">
<i className="pr-icon-like"></i>
</div>
<div className="ptp-f-text">{post_metrics.likes_count}</div>
</div>
<div className="ptp-f-container d-flex align-items-center">
<div className="ptp-f-icon">
<i className="pr-icon-comment"></i>
</div>
<div className="ptp-f-text">
{post_metrics.comments_count}
</div>
</div>
<div className="ptp-f-container d-flex align-items-center">
<div className="ptp-f-icon">
<i className="pr-icon-share"></i>
</div>
<div className="ptp-f-text">
{post_metrics.shares_count}
</div>
</div>
</div>
</div>
</a>
</div>
<div className="col col-12 col-md-5">
<div className="prestigio-pane px-3 pt-3 mb-3 prestigio-shadow d-flex flex-column justify-content-center">
<a href={url} className="no-style d-none d-md-block">
<div className="d-flex align-items-center mb-3">
<div
className="prestigio-thumbnail mr-2"
style={{ backgroundImage: `url(${picture})` }}
></div>
<p className="small-text mb-0 ellipsis">{name}</p>
</div>
</a>
<div className="small-title-span p-0 mb-1">
<span>POST METRICS</span>
</div>
<div className="row pr-close-row">
<div className="col mb-3">
<span className="small-text op-67">
<strong>Reach</strong>
</span>
<h3 className="mb-0">{reach}</h3>
</div>
<div className="col mb-3">
<span className="small-text op-67">
<strong>Engagement</strong>
</span>
<h3 className="mb-0">{engagement}</h3>
</div>
</div>
<div className="small-title-span p-0 mb-2">
<span>TAGGED BRANDS</span>
</div>
<TaggedBrandList mentions={mentions} />
</div>
<div className="text-right">
<button
type="button"
className="prestigio-btn prestigio-blue-white prestigio-shadow"
data-toggle="modal"
data-target="#shareModal"
onClick={() => (window.location.href = url)}
>
<i className="pr-icon-share"></i> SHARE
</button>
</div>
</div>
</div>
</div>
<div className="row pr-close-row">
<div className="col col-8 offset-2 offset-lg-3">
<hr />
</div>
</div>
</div>
);
};
export default SocialPost;
<file_sep>import React, { useState, useEffect } from "react";
import SearchBox from "./components/SearchBox";
import FilterBox from "./components/FiltersBox";
import MentionedSocialPostList from "./components/MentionedSocialPostList";
import TopMentionersList from "./components/TopMentionersList";
import Error from "./components/Error";
import { sortBy } from "lodash";
function App() {
const [query, saveQuery] = useState("");
const [orderField, saveOrderField] = useState("post_created_at");
const [fetchOrderField, saveFetchOrderField] = useState("post_created_at");
const [option, saveOption] = useState("all");
const [mentionedSocialPost, saveMentionedSocialPost] = useState([]);
const [topMentioners, saveTopMentioners] = useState([]);
const [currentPage, saveCurrentPage] = useState(1);
const [totalPost, setTotalPost] = useState(0);
const [error, saveError] = useState(false);
useEffect(() => {
saveTopMentioners([]);
saveMentionedSocialPost([]);
saveCurrentPage(1);
queryAPI();
}, [query]);
useEffect(() => {
if (currentPage > 1) {
queryAPI();
}
}, [currentPage]);
useEffect(() => {
sortData();
}, [orderField]);
const sortData = () => {
if (orderField !== fetchOrderField) {
switch (orderField) {
case "post_created_at":
saveMentionedSocialPost(
sortBy(mentionedSocialPost, [o => o.post_created_at])
);
break;
case "usersid":
saveMentionedSocialPost(
sortBy(mentionedSocialPost, [o => o.user[0].userinfo.displayname])
);
default:
break;
}
}
};
const queryAPI = async () => {
let brand = "";
const postPerPage = 4;
const includes = `user,social,mentions.brand`;
const sorting = `sortField=${orderField}&sortOrder=asc`;
const baseURL = `https://adcaller.com/`;
const brandURL = `${baseURL}brands`;
// const userBaseURL = `${baseURL}users`
const sidBrandURL = `${brandURL}?qField=brand_name&qValue=${encodeURIComponent(
query
)}`;
//https://adcaller.com/brands?qField=brand_name&qValue=me
saveFetchOrderField(orderField);
if (query === "") return;
else if (query === "me") brand = "Z2EfoOUFQJVs39lg";
else {
// Getting the sidbrand in order to get the brand
// TODO: Improve the brand searching method. but it depends on the API.
const searchBrand = await fetch(sidBrandURL);
const searchBrandResult = await searchBrand.json();
if (searchBrandResult.data.attributes[0])
brand = searchBrandResult.data.attributes[0].sidbrand;
else {
saveError(true);
return;
}
// if it cannot get the result, raise an error
}
const url = `${brandURL}/${brand}/mentioned_social_posts?&${sorting}&includes=${encodeURIComponent(
includes
)}`;
const urlPerPage = `${url}&page=${currentPage}&limit=${postPerPage}`;
/* https://adcaller.com/brands/Z2EfoOUFQJVs39lg/mentioned_social_posts?sortField=userid&sortOrder=asc&page=2&limit=4&includes=social%2Cmentions.brand&*/
const answer = await fetch(url);
const answerPerPage = await fetch(urlPerPage);
const result = await answer.json();
const resultPerPage = await answerPerPage.json();
setTotalPost(resultPerPage.meta.totalResults);
// Note: this must to be an API's endpoint
let topMentionerList = result.data.attributes.reduce((r, a) => {
r[a.usersid] = [...(r[a.usersid] || []), a];
r[a.usersid]["name"] = a.user[0].userinfo.displayname;
r[a.usersid]["key"] = a.usersid;
r[a.usersid]["picture"] = a.user[0].userinfo.avatar_url;
// TODO: just add increase a counter and add the name and photo url
return r;
}, {});
saveError(false);
saveMentionedSocialPost(m => [...m, ...resultPerPage.data.attributes]);
saveTopMentioners(
Object.values(topMentionerList).sort((a, b) => b.length - a.length)
);
};
const filteredPosts = () => {
if (option === "all") {
return mentionedSocialPost;
}
return mentionedSocialPost.filter(post => post.social === option);
};
return (
<div className="App brand-prestigio">
<div className="container-fluid prestigio-brand-background">
<div className="row pr-close-row">
<div className="col col-lg-6 offset-lg-3">
<div className="row no-gutters">
<div className="col col-10 col-lg-10 col-md-8 col-sm-8 offset-1 offset-lg-1 offset-md-2 offset-sm-2 prestigio-white-stripe prestigio-shadow">
<SearchBox
saveQuery={saveQuery}
saveOrderField={saveOrderField}
/>
<FilterBox saveOption={saveOption} option={option} />
<div
className="prestigio-tab-pane"
style={{ display: `block` }}
id="brand-pane"
data-tabs="mentions"
>
<div className="prestigio-offset-pane-big">
<div className="row pr-responsive-row">
<MentionedSocialPostList
mentionedSocialPost={filteredPosts()}
saveCurrentPage={saveCurrentPage}
currentPage={currentPage}
totalPost={totalPost}
/>
<TopMentionersList topMentioners={topMentioners} />
</div>
</div>
</div>
{error ? (
<Error message="No brand was matched with your query!" />
) : null}
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default App; | 593fe9817f77f69ee326095671703ccdb444f6d0 | [
"JavaScript"
]
| 6 | JavaScript | SalahAdDin/frontend-test | f1d95acff122548251e8bcc68dd77afbc8b6ed14 | 506e82b269504d81bf0095ee2561bf76a89d20c4 |
refs/heads/readBDTNtuple | <repo_name>zhangzc11/WVZLooper<file_sep>/scripts/bdt_looper/xgboost/python/plot_wwz_vs_zz_features.py
#!/usr/bin/env python
# coding: utf-8
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
import ROOT as root
import os
import shlex
import uproot
####################option A:##################
##train a single BDT to discriminate signal with zz backgrounds
##use emu events for training
##with zz backgrounds included
##############################################
root.gROOT.SetBatch(True)
#for channel in ["emu", "OffZ"]:
for channel in ["emu"]:
test_name = channel+'_wwz_vs_zz'
plotDir = "/home/users/zhicaiz/public_html/WWZ/BDT/"
pwd = os.getcwd()
dataDir = pwd.replace("python", "data/All/"+channel+"HighTTZBDT/")
os.system("mkdir -p "+plotDir)
os.system("mkdir -p "+plotDir+"variables_compare")
##Define variables to be used
variables = ['eventweight', 'met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis']
variables_names = ['eventweight', 'met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','Mll34', 'pt_zeta', 'pt_zeta_vis']
print(len(variables))
##Getting ROOT files into pandas
df_wwz_HighZZBDT = uproot.open(dataDir+"wwz_HighZZBDT.root")['t'].pandas.df(variables, flatten=False)
df_wwz_LowZZBDT = uproot.open(dataDir+"wwz_LowZZBDT.root")['t'].pandas.df(variables, flatten=False)
df_zz_HighZZBDT = uproot.open(dataDir+"zz_HighZZBDT.root")['t'].pandas.df(variables, flatten=False)
df_zz_LowZZBDT = uproot.open(dataDir+"zz_LowZZBDT.root")['t'].pandas.df(variables, flatten=False)
####Plot input variables######
for idx in range(1, len(variables)):
plt.figure()
y_wwz_HighZZBDT, x_wwz_HighZZBDT, _ = plt.hist(df_wwz_HighZZBDT[df_wwz_HighZZBDT[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="wwz "+channel+" - ZZ BDT > 0.9", color='b')
y_wwz_LowZZBDT, x_wwz_LowZZBDT, _ = plt.hist(df_wwz_LowZZBDT[df_wwz_LowZZBDT[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="wwz "+channel+" - ZZ BDT < 0.9", color='y')
y_zz_HighZZBDT, x_zz_HighZZBDT, _ = plt.hist(df_zz_HighZZBDT[df_zz_HighZZBDT[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="zz "+channel+" - ZZ BDT > 0.9", color='g')
y_zz_LowZZBDT, x_zz_LowZZBDT, _ = plt.hist(df_zz_LowZZBDT[df_zz_LowZZBDT[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="zz "+channel+" - ZZ BDT < 0.9", color='r')
y_max1 = max([max(y_wwz_HighZZBDT), max(y_wwz_LowZZBDT), max(y_zz_HighZZBDT), max(y_zz_LowZZBDT)])
y_max2 = max([max(y_zz_HighZZBDT), max(y_zz_LowZZBDT)])
plt.legend(loc="upper center", fontsize = 30)
plt.xlabel(variables[idx], fontsize=50)
plt.ylabel('Events', fontsize=30)
plt.xticks(fontsize=35)
plt.yticks(fontsize=30)
if "MT" in variables[idx]:
plt.xlim([0.0, 500.0])
if "Pt" in variables[idx]:
plt.xlim([0.0, 500.0])
if "met_pt" in variables[idx]:
plt.xlim([0.0, 500.0])
if "MllN" in variables[idx]:
plt.xlim([0.0, 500.0])
if "pt_zeta" in variables[idx]:
plt.xlim([-100.0, 500.0])
if "dZ" in variables[idx]:
plt.xlim([-0.05, 0.05])
plt.ylim([0.0*y_max1, 2.0*y_max1])
#plt.ylim([0.00001*y_max, 200.0*y_max])
#plt.yscale("log")
fig = plt.gcf()
fig.set_size_inches(16, 12)
plt.draw()
plt.savefig(plotDir+'variables_compare/'+test_name + '_' + variables[idx]+'.png')
plt.figure()
os.system("chmod 755 "+plotDir+"variables_compare/*")
<file_sep>/scripts/bdt_looper/xgboost/python/others/train_wwz_vs_zz_OffZ.py
#!/usr/bin/env python
# coding: utf-8
import matplotlib.pyplot as plt
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_curve, roc_auc_score
import numpy as np
import pandas as pd
import math
import pickle as pickle
import ROOT as root
import os
import shlex
import uproot
####################option A:##################
##train a single BDT to discriminate signal with zz backgrounds
##use OffZ events for training
##with zz backgrounds included
##############################################
doAppend = False
root.gROOT.SetBatch(True)
test_name = 'xgb_wwz_vs_zz_OffZ'
lumi_sf_sig = 1.0 # scale lumi from 2018 sample to full run2
lumi_sf_bkg = 1.0
plotDir = "/home/users/zhicaiz/public_html/WWZ/BDT/"
pwd = os.getcwd()
dataDir = pwd.replace("python", "data/All/OffZ/")
os.system("mkdir -p "+plotDir)
os.system("mkdir -p "+plotDir+"training")
os.system("mkdir -p "+plotDir+"results")
os.system("mkdir -p "+plotDir+"scores")
os.system("mkdir -p "+plotDir+"variables")
#signal
signalFileName = dataDir + 'wwz.root'
signalFile = root.TFile(signalFileName)
signalTree = signalFile.Get('t')
signalTree.Draw('met_pt>>tmp1', 'eventweight')
signalHisto = root.gDirectory.Get('tmp1')
signalEvents = lumi_sf_sig*signalHisto.Integral()
#bkg
bkgFileName = dataDir + 'zz.root'
bkgFile = root.TFile(bkgFileName)
bkgTree = bkgFile.Get('t')
bkgTree.Draw('met_pt>>tmp2', 'eventweight')
bkgHisto = root.gDirectory.Get('tmp2')
bkgEvents = lumi_sf_bkg*bkgHisto.Integral()
print('[INFO]: S =' + str(signalEvents) + '; B =' + str(bkgEvents) +"; S/sqrt(B) = " + str(signalEvents/math.sqrt(bkgEvents)))
##Define variables to be used
variables = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis']
variables_names = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','Mll34', 'pt_zeta', 'pt_zeta_vis']
print(len(variables))
##Getting ROOT files into pandas
df_signal = uproot.open(signalFileName)['t'].pandas.df(variables, flatten=False)
df_bkg = uproot.open(bkgFileName)['t'].pandas.df(variables, flatten=False)
##Getting Sample weights
weights_signal = uproot.open(signalFileName)['t'].pandas.df('eventweight', flatten=False)
weights_bkg = uproot.open(bkgFileName)['t'].pandas.df('eventweight', flatten=False)
## We care about the sign of the sample only, we don't care about the xsec weight
#weights_sign_signal = np.sign(weights_signal)
#weights_sign_bkg = np.sign(weights_bkg)
weights_sign_signal = weights_signal
weights_sign_bkg = weights_bkg
##Getting a numpy array out of two pandas data frame
sample_weights = np.concatenate([weights_sign_bkg.values, weights_sign_signal.values])
#print sample_weights
#getting a numpy array from two pandas data frames
x = np.concatenate([df_bkg.values,df_signal.values])
#creating numpy array for target variables
y = np.concatenate([np.zeros(len(df_bkg)),
np.ones(len(df_signal))])
####Plot input variables######
for idx in range(len(variables)):
plt.figure()
plt.hist(df_signal[df_signal[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=4, label="WWZ")
plt.hist(df_bkg[df_bkg[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=4, label="ZZ")
plt.legend(loc="upper center", fontsize = 50)
plt.xlabel(variables[idx], fontsize=50)
plt.ylabel('Events', fontsize=30)
plt.xticks(fontsize=35)
plt.yticks(fontsize=30)
fig = plt.gcf()
fig.set_size_inches(16, 12)
plt.draw()
plt.savefig(plotDir+'variables/'+test_name + '_' + variables[idx]+'.png')
os.system("chmod 755 "+plotDir+"variables/*")
# split data into train and test sets
seed = 7
test_size = 0.4
sample_size = 1.0
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size = sample_size*(1-test_size), test_size=sample_size*test_size, random_state=seed)
# fit model no training data
#model = xgb.XGBClassifier(max_depth=8, n_estimators=1000, gamma=1, learning_rate = .99)
#model = xgb.XGBClassifier(max_depth=4, learning_rate=0.05, n_estimators=400, verbosity=2, n_jobs=4, reg_lambda=0.5, booster='gblinear')
model = xgb.XGBClassifier(max_depth=6, learning_rate=0.1, n_estimators=100, verbosity=2, n_jobs=4, reg_lambda=1.0)
#model = xgb.XGBClassifier(max_depth=8, learning_rate=0.1, n_estimators=1000, verbosity=2, n_jobs=4, booster='gblinear')
#model = xgb.XGBClassifier(max_depth=3, learning_rate=0.1, n_estimators=100, verbosity=2, n_jobs=4)
#model.fit(x_train, y_train, sample_weight=sample_weights)
model.fit(x_train, y_train, sample_weight=sample_weights)
#model.fit(x_train, y_train)
#print( dir(model) )
#print(model)
# make predictions for test data
y_pred = model.predict_proba(x_test)[:, 1]
y_pred_train = model.predict_proba(x_train)[:, 1]
y_pred_bkg = model.predict_proba(df_bkg.values)[:, 1]
predictions = [round(value) for value in y_pred]
# evaluate predictions
accuracy = accuracy_score(y_test, predictions)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
print("AUC: "+str(roc_auc_score(y_test, y_pred)))
#get roc curve
#roc = roc_curve(y_test, y_pred)
fpr, tpr, thr = roc_curve(y_test, y_pred)
significance = []
effSignal = []
effBkg = []
thresholds = []
ctr = 0
for i in range(len(fpr)):
if fpr[i] > 1e-5 and tpr[i] > 1e-5:
#print fpr[i], tpr[i]
#significance.append(math.sqrt(lumi)*4.8742592356*0.006431528796*tpr[i]/math.sqrt(fpr[i]*0.9935684712))
significance.append(signalEvents*tpr[i]/math.sqrt(fpr[i]*bkgEvents))
effSignal.append(tpr[i])
effBkg.append(fpr[i])
thresholds.append(thr[i])
#print significance[ctr], ' ' , fpr[ctr], ' ', tpr[ctr]
ctr = ctr + 1
max_significance = max(significance)
idx_max_significance = np.argmax(np.array(significance))
best_threshold = thresholds[idx_max_significance]
best_effSignal = effSignal[idx_max_significance]
best_effBkg = effBkg[idx_max_significance]
print("max_significance: "+str(max_significance))
print("best_threshold: "+str(best_threshold))
print("best_effSignal: "+str(best_effSignal))
print("best_effBkg: "+str(best_effBkg))
idx_WP90 = 0
minD0p9 = 999.0
for idx in range(len(effSignal)):
if abs(effSignal[idx] - 0.90) < minD0p9:
idx_WP90 = idx
minD0p9 = abs(effSignal[idx] - 0.90)
WP90_significance = significance[idx_WP90]
WP90_threshold = thresholds[idx_WP90]
WP90_effSignal = effSignal[idx_WP90]
WP90_effBkg = effBkg[idx_WP90]
print("WP90_significance: "+str(WP90_significance))
print("WP90_threshold: "+str(WP90_threshold))
print("WP90_effSignal: "+str(WP90_effSignal))
print("WP90_effBkg: "+str(WP90_effBkg))
##########################################################
# make histogram of discriminator value for signal and bkg
##########################################################
#pd.DataFrame({'truth':y_test, 'disc':y_pred}).hist(column='disc', by='truth', bins=50)
y_frame = pd.DataFrame({'truth':y_test, 'disc':y_pred})
y_frame_train = pd.DataFrame({'truth':y_train, 'disc':y_pred_train})
disc_bkg = y_frame[y_frame['truth'] == 0]['disc'].values
disc_bkg_train = y_frame_train[y_frame_train['truth'] == 0]['disc'].values
disc_signal = y_frame[y_frame['truth'] == 1]['disc'].values
disc_signal_train = y_frame_train[y_frame_train['truth'] == 1]['disc'].values
plt.figure()
plt.hist(disc_signal, density=True, bins=100, alpha=1.0, histtype="step", lw=2, label="WWZ - test")
plt.hist(disc_signal_train, density=True, bins=100, alpha=1.0, histtype="step", lw=2, label="WWZ - train")
plt.hist(disc_bkg, density=True, bins=100, alpha=1.0, histtype="step", lw=2, label="ZZ - test")
plt.hist(disc_bkg_train, density=True, bins=100, alpha=1.0, histtype="step", lw=2, label="ZZ - train")
plt.yscale("log")
plt.xlim([0.0, 1.0])
plt.ylim([0.001, 100.0])
plt.legend(loc="upper center")
plt.xlabel('BDT response')
plt.ylabel('Events')
plt.axvline(x=WP90_threshold, color="black", linestyle='--')
plt.text(0.5,0.7,'WP90: disc > %.3f'%WP90_threshold, fontsize=12, horizontalalignment='center', verticalalignment='center', transform=plt.gca().transAxes)
plt.savefig(plotDir+'training/mydiscriminator_' + test_name +'_logY.png')
plt.figure()
plt.hist(disc_signal, density=True, bins=100, alpha=1.0, histtype="step", lw=2, label="WWZ - test")
plt.hist(disc_signal_train, density=True, bins=100, alpha=1.0, histtype="step", lw=2, label="WWZ - train")
plt.hist(disc_bkg, density=True, bins=100, alpha=1.0, histtype="step", lw=2, label="ZZ - test")
plt.hist(disc_bkg_train, density=True, bins=100, alpha=1.0, histtype="step", lw=2, label="ZZ - train")
plt.yscale("linear")
plt.xlim([0.0, 1.0])
#plt.ylim([0.001, 100.0])
plt.legend(loc="upper center")
plt.xlabel('BDT response')
plt.ylabel('Events')
plt.axvline(x=WP90_threshold, color="black", linestyle='--')
plt.text(0.5,0.7,'WP90: disc > %.3f'%WP90_threshold, fontsize=12, horizontalalignment='center', verticalalignment='center', transform=plt.gca().transAxes)
plt.savefig(plotDir+'training/mydiscriminator_' + test_name +'_linY.png')
os.system("chmod 755 "+plotDir+"training/*")
#plot roc curve
plt.figure()
lw = 2
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label='ROC curve')
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('Signal Efficiency')
plt.ylabel('Background Efficiency')
plt.axhline(y=0.9, color="black", linestyle='--')
plt.text(0.5,0.2,'WP90: bkg eff = %.2f'%WP90_effBkg, fontsize=12)
plt.text(0.5,0.3,'WP90: S/sqrt(B) = %.2f'%WP90_significance, fontsize=12)
#plt.title('Receiver operating characteristic example')
#plt.legend(loc="lower right")
#plt.show()
plt.savefig(plotDir+'training/myroc_' + test_name + '.png')
os.system("chmod 755 "+plotDir+"training/*")
#print "signal Eff: ", effSignal
#print "significance:", significance
plt.figure()
plt.plot(effSignal, significance,
lw=lw, label='s/sqrt(B) vs. sig eff')
plt.plot(effBkg, significance,
lw=lw, label='s/sqrt(B) vs. bkg eff')
#plt.xlim([0.0, 1.0])
#plt.ylim([0.0, 5.01])
plt.xlabel('efficiency')
plt.ylabel('s/sqrt(B)')
#plt.title('significance')
plt.legend(loc="lower center")
#plt.show()
plt.savefig(plotDir+'training/significance_vs_eff_' + test_name + '.png')
os.system("chmod 755 "+plotDir+"training/*")
plt.figure()
plt.plot(thresholds, significance, color='darkorange',
lw=lw, label='S/sqrt(B)')
plt.axvline(x=best_threshold, color="black")
plt.axvline(x=WP90_threshold, color="black", linestyle='--')
plt.text(0.1,8.0,'thr @ max S/sqrt(B) = %.3f'%best_threshold + " [S/sqrt(B) = %.1f"%max_significance+"]", fontsize=12)
plt.text(0.1,7.0,'thr @ WP90 = %.3f'%WP90_threshold + "[S/sqrt(B) = %.1f"%WP90_significance+"]", fontsize=12)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 10.0])
plt.xlabel('thresholds')
plt.ylabel('S/sqrt(B)')
plt.title('significance')
#plt.legend(loc="lower center")
#plt.show()
plt.savefig(plotDir+'training/significance_vs_thr_' + test_name + '.png')
os.system("chmod 755 "+plotDir+"training/*")
# Pickle dictionary using protocol 0.
output = open('../models/model_'+test_name+'.pkl', 'wb')
pickle.dump(model, output)
output.close()
model.get_booster().dump_model('../models/model_'+test_name+'.txt')
model.get_booster().save_model('../models/model_'+test_name+'.xgb')
print("example input and prediction....")
print("bkg sample 1st event input:")
print(df_bkg.values[0])
print("y_pred_bkg first 20 events")
print(y_pred_bkg[:20])
#plot feature importances
model.get_booster().feature_names = variables_names
xgb.plot_importance(model, max_num_features=len(variables), xlabel="F score (weight)")
plt.savefig(plotDir+'training/myImportances_Fscore_' + test_name + '.png')
os.system("chmod 755 "+plotDir+"training/*")
#xgb.plot_tree( model.get_booster() )
xgb.plot_tree( model )
fig = plt.gcf()
fig.set_size_inches(500, 50)
plt.draw()
plt.savefig(plotDir+'training/myTree_' + test_name + '.png')
plt.savefig(plotDir+'myTree_' + test_name + '.svg')
os.system("chmod 755 "+plotDir+"training/*")
<file_sep>/scripts/bdt_looper/xgboost/python/optimize_cut_minDR.py
#!/usr/bin/env python
# coding: utf-8
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
import pickle as pickle
import ROOT as root
import os
import shlex
import uproot
####################option B:##################
##train two BDTs/: ZZ and ttZ
##use emu events for ZZ BDT training
##use events without bVeto for ttZ BDT training
##############################################
root.gROOT.SetBatch(True)
test_name = 'significance_vs_minDR'
lumi_sf_sig = 1.0 # scale lumi from 2018 sample to full run2
lumi_sf_bkg = 1.0
plotDir = "/home/users/zhicaiz/public_html/WWZ/BDT/"
pwd = os.getcwd()
os.system("mkdir -p "+plotDir)
os.system("mkdir -p "+plotDir+"cuts_scan")
yield_emuHighMT_all = [10.27, 3.2, 2.67, 1.19, 1.14, 0.8, 0.5]
yield_OffZHighMET_all = [4.95, 4.29, 1.58, 0.58, 0.5, 0.47, 0.0]
for channel in ["emuHighMT", "OffZHighMET"]:
print("optimize channel: "+channel)
dataDir = pwd.replace("python", "data/All/"+channel+"/")
yield_all = np.array(yield_emuHighMT_all)
if "OffZHighMET" in channel:
yield_all = np.array(yield_OffZHighMET_all)
N_all = np.zeros(len(yield_all))
fileName_all = ["wwz", "zz", "ttz", "twz", "wz", "higgs", "othernoh"]
tree_all = {}
for idx in range(len(N_all)):
tree_all[idx] = root.TChain("t")
tree_all[idx].AddFile(dataDir + fileName_all[idx]+".root")
root.SetOwnership(tree_all[idx], True)
file_this = root.TFile(dataDir + fileName_all[idx]+".root")
tree_this = file_this.Get('t')
#tree_all.append(tree_this)
N_all[idx] = tree_this.GetEntries()
#print("N_all:")
#print(N_all)
minDRJetToLep3_cuts = np.arange(0.0, 2.0, 0.1)
minDRJetToLep4_cuts = np.arange(0.0, 2.0, 0.1)
L_cuts = np.zeros((len(minDRJetToLep3_cuts), len(minDRJetToLep4_cuts)))
for idx1 in range(len(minDRJetToLep3_cuts)):
for idx2 in range(len(minDRJetToLep4_cuts)):
cut_this = "(minDRJetToLep3>"+str(minDRJetToLep3_cuts[idx1])+" || minDRJetToLep3 < 0) && (minDRJetToLep4>"+str(minDRJetToLep4_cuts[idx2])+" || minDRJetToLep4 < 0)"
#print(cut_this)
yield_this = np.zeros(len(yield_all))
for idx in range(len(N_all)):
N_this = tree_all[idx].GetEntries(cut_this)
yield_this[idx] = yield_all[idx]*N_this*1.0/N_all[idx]
s = yield_this[0]
b = 0.0
for idx in range(1, len(N_all)):
b = b + yield_this[idx]
L = math.sqrt(2.0*((s+b)*math.log(1+s/b) - s))
print(str(minDRJetToLep3_cuts[idx1])+", "+str(minDRJetToLep4_cuts[idx2]) + ", "+ str(s) +", "+str(b)+ ", "+ str(L))
L_cuts[idx1][idx2] = L
print(L_cuts)
print("max L: "+str(np.amax(L_cuts)))
<file_sep>/scripts/bdt_looper/xgboost/python/others/plot_prune.py
import numpy as np
import matplotlib.pyplot as plt
import os
test_name = 'xgb_wwz_vs_ttz_nbAll_full'
plotDir = "/home/users/zhicaiz/public_html/WWZ/BDT/"
name = []
AUC = []
with open("result_prune_ttZ.txt") as f:
lines = f.readlines()
for line in lines:
line_items = line.strip('\n').split()
name.append(line_items[0])
AUC.append(float(line_items[1]))
plt.figure()
plt.plot(name, AUC, lw=2)
plt.xticks(rotation=90)
plt.xlabel('cumulative removed features (left to right)')
plt.ylabel('AUC after removal')
plt.savefig(plotDir+'training/AUC_vs_removed_features_'+test_name+'.png', bbox_inches='tight')
os.system("chmod 755 "+plotDir+"training/*")
<file_sep>/scripts/bdt_looper/xgboost/python/others/train_wwz_vs_multi_emu.py
#!/usr/bin/env python
# coding: utf-8
import matplotlib.pyplot as plt
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_curve, roc_auc_score
import numpy as np
import pandas as pd
import math
import pickle as pickle
import ROOT as root
import os
import shlex
import uproot
####################option C:##################
##train a multi-class BDT to discriminate signal with all backgrounds
##use emu events for training
##with all backgrounds included
##############################################
doAppend = False
root.gROOT.SetBatch(True)
test_name = 'xgb_wwz_vs_multi_emu'
lumi_sf_sig = 1.0 # scale lumi from 2018 sample to full run2
lumi_sf_bkg = 1.0
plotDir = "/home/users/zhicaiz/public_html/WWZ/BDT/"
pwd = os.getcwd()
dataDir = pwd.replace("python", "data/All/emu/")
os.system("mkdir -p "+plotDir)
os.system("mkdir -p "+plotDir+"training")
os.system("mkdir -p "+plotDir+"results")
os.system("mkdir -p "+plotDir+"scores")
os.system("mkdir -p "+plotDir+"variables")
#signal
signalFileName = dataDir + 'wwz_skim.root'
signalFile = root.TFile(signalFileName)
signalTree = signalFile.Get('t')
signalTree.Draw('met_pt>>tmp1', 'eventweight')
signalHisto = root.gDirectory.Get('tmp1')
signalEvents = lumi_sf_sig*signalHisto.Integral()
#bkg
bkgFileName = dataDir + 'all_bkg_skim.root'
bkgFile = root.TFile(bkgFileName)
bkgTree = bkgFile.Get('t')
bkgTree.Draw('met_pt>>tmp2', 'eventweight')
bkgHisto = root.gDirectory.Get('tmp2')
bkgEvents = lumi_sf_bkg*bkgHisto.Integral()
zzFileName = dataDir + 'zz_skim.root'
ttzFileName = dataDir + 'ttz_skim.root'
wzFileName = dataDir + 'wz_skim.root'
twzFileName = dataDir + 'twz_skim.root'
otherFileName = dataDir + 'other_skim.root'
num_class = 6
print('[INFO]: S =' + str(signalEvents) + '; B =' + str(bkgEvents) +"; S/sqrt(B) = " + str(signalEvents/math.sqrt(bkgEvents)))
##Define variables to be used
variables = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis', "nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore']
variables_names = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','Mll34', 'pt_zeta', 'pt_zeta_vis', "nj", 'minDRJToL3','minDRJToL4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1Btag', 'jet2Btag', 'jet3Btag', 'jet4Btag']
print(len(variables))
##Getting ROOT files into pandas
df_signal = uproot.open(signalFileName)['t'].pandas.df(variables, flatten=False)
df_zz = uproot.open(zzFileName)['t'].pandas.df(variables, flatten=False)
df_ttz = uproot.open(ttzFileName)['t'].pandas.df(variables, flatten=False)
df_wz = uproot.open(wzFileName)['t'].pandas.df(variables, flatten=False)
df_twz = uproot.open(twzFileName)['t'].pandas.df(variables, flatten=False)
df_other = uproot.open(otherFileName)['t'].pandas.df(variables, flatten=False)
##Getting Sample weights
weights_signal = uproot.open(signalFileName)['t'].pandas.df('eventweight', flatten=False)
weights_zz = uproot.open(zzFileName)['t'].pandas.df('eventweight', flatten=False)
weights_ttz = uproot.open(ttzFileName)['t'].pandas.df('eventweight', flatten=False)
weights_wz = uproot.open(wzFileName)['t'].pandas.df('eventweight', flatten=False)
weights_twz = uproot.open(twzFileName)['t'].pandas.df('eventweight', flatten=False)
weights_other = uproot.open(otherFileName)['t'].pandas.df('eventweight', flatten=False)
##Getting a numpy array out of two pandas data frame
sample_weights = np.concatenate([weights_signal.values, weights_zz.values[:100000], weights_ttz.values, weights_wz.values, weights_twz.values, weights_other.values])
#print sample_weights
#getting a numpy array from two pandas data frames
x = np.concatenate([df_signal.values, df_zz.values[:100000], df_ttz.values, df_wz.values, df_twz.values, df_other.values])
#creating numpy array for target variables
y = np.concatenate([0*np.ones(len(df_signal.values)), 1*np.ones(len(df_zz.values[:100000])), 2*np.ones(len(df_ttz.values)), 3*np.ones(len(df_wz.values)), 4*np.ones(len(df_twz.values)), 5*np.ones(len(df_other.values))])
####Plot input variables######
for idx in range(len(variables)):
plt.figure()
plt.hist(df_signal[df_signal[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="WWZ")
plt.hist(df_zz[df_zz[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="zz")
plt.hist(df_ttz[df_ttz[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="ttz")
plt.hist(df_wz[df_wz[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="wz")
plt.hist(df_twz[df_twz[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="twz")
plt.hist(df_other[df_other[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="other")
plt.legend(loc="upper center")
plt.xlabel(variables[idx])
plt.ylabel('Events')
plt.savefig(plotDir+'variables/'+test_name + '_' + variables[idx]+'.png')
os.system("chmod 755 "+plotDir+"variables/*")
# split data into train and test sets
seed = 7
test_size = 0.4
sample_size = 1.0
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size = sample_size*(1-test_size), test_size=sample_size*test_size, random_state=seed)
d_train = xgb.DMatrix(x_train, label=y_train)
d_test = xgb.DMatrix(x_test, label=y_test)
# fit model no training data
watchlist = [(d_train, 'train'), (d_test, 'test')]
params = {'max_depth':7, 'learning_rate':0.1, 'n_estimators':1000, 'n_jobs':4, 'objective':'multi:softmax', 'num_class':num_class}
model = xgb.train(params, d_train)#, evals_result=watchlist)
pred_label = model.predict(d_test)
pred_label_train = model.predict(d_train)
error_rate = np.sum(pred_label != y_test) / y_test.shape[0]
print('Test error using softmax = {}'.format(error_rate))
#params['objective'] = 'multi:softprob'
#model = xgb.train(params, d_train)#, evals_result=watchlist)
#pred_prob = model.predict(d_test).reshape(y_test.shape[0], num_class)
#pred_prob_train = model.predict(d_train).reshape(y_train.shape[0], num_class)
#pred_label = np.argmax(pred_prob, axis=1)
#pred_label_train = np.argmax(pred_prob_train, axis=1)
#error_rate = np.sum(pred_label != y_test) / y_test.shape[0]
#print('Test error using softprob = {}'.format(error_rate))
##########################################################
# make histogram of discriminator value for signal and bkg
##########################################################
#pd.DataFrame({'truth':y_test, 'disc':y_pred}).hist(column='disc', by='truth', bins=50)
y_frame = pd.DataFrame({'truth':y_test, 'disc':pred_label})
y_frame_train = pd.DataFrame({'truth':y_train, 'disc':pred_label_train})
disc_zz = y_frame[y_frame['truth'] == 1]['disc'].values
disc_zz_train = y_frame_train[y_frame_train['truth'] == 1]['disc'].values
disc_ttz = y_frame[y_frame['truth'] == 2]['disc'].values
disc_ttz_train = y_frame_train[y_frame_train['truth'] == 2]['disc'].values
disc_wz = y_frame[y_frame['truth'] == 3]['disc'].values
disc_wz_train = y_frame_train[y_frame_train['truth'] == 3]['disc'].values
disc_twz = y_frame[y_frame['truth'] == 4]['disc'].values
disc_twz_train = y_frame_train[y_frame_train['truth'] == 4]['disc'].values
disc_other = y_frame[y_frame['truth'] == 5]['disc'].values
disc_other_train = y_frame_train[y_frame_train['truth'] == 5]['disc'].values
disc_signal = y_frame[y_frame['truth'] == 0]['disc'].values
disc_signal_train = y_frame_train[y_frame_train['truth'] == 0]['disc'].values
plt.figure()
bins_label=[-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5]
plt.hist(disc_signal, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="WWZ - test", color='b')
plt.hist(disc_signal_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="WWZ - train", linestyle='--', color='b')
plt.hist(disc_zz, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="zz - test", color='y')
plt.hist(disc_zz_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="zz - train", linestyle='--', color='y')
plt.hist(disc_ttz, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="ttz - test", color='g')
plt.hist(disc_ttz_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="ttz - train", linestyle='--', color='g')
plt.hist(disc_wz, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="wz - test", color='r')
plt.hist(disc_wz_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="wz - train", linestyle='--', color='r')
plt.hist(disc_twz, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="twz - test", color='m')
plt.hist(disc_twz_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="twz - train", linestyle='--', color='m')
plt.hist(disc_other, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="other - test", color='c')
plt.hist(disc_other_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="other - train", linestyle='--', color='c')
#plt.hist(disc_signal_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="WWZ - train")
plt.yscale("log")
plt.xlim([-0.5, 5.5])
#plt.ylim([0.001, 100.0])
plt.legend(loc="upper right")
plt.xlabel('BDT response (label)')
plt.ylabel('Events')
plt.savefig(plotDir+'training/mydiscriminator_' + test_name +'_logY.png')
plt.figure()
plt.hist(disc_signal, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="WWZ - test", color='b')
plt.hist(disc_signal_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="WWZ - train", linestyle='--', color='b')
plt.hist(disc_zz, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="zz - test", color='y')
plt.hist(disc_zz_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="zz - train", linestyle='--', color='y')
plt.hist(disc_ttz, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="ttz - test", color='g')
plt.hist(disc_ttz_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="ttz - train", linestyle='--', color='g')
plt.hist(disc_wz, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="wz - test", color='r')
plt.hist(disc_wz_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="wz - train", linestyle='--', color='r')
plt.hist(disc_twz, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="twz - test", color='m')
plt.hist(disc_twz_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="twz - train", linestyle='--', color='m')
plt.hist(disc_other, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="other - test", color='c')
plt.hist(disc_other_train, density=True, bins=bins_label, alpha=1.0, histtype="step", lw=2, label="other - train", linestyle='--', color='c')
plt.yscale("linear")
plt.xlim([-0.5, 5.5])
#plt.ylim([0.001, 100.0])
plt.legend(loc="upper right")
plt.xlabel('BDT response')
plt.ylabel('Events')
plt.savefig(plotDir+'training/mydiscriminator_' + test_name +'_linY.png')
os.system("chmod 755 "+plotDir+"training/*")
# Pickle dictionary using protocol 0.
output = open('../models/model_'+test_name+'.pkl', 'wb')
pickle.dump(model, output)
output.close()
model.dump_model('../models/model_'+test_name+'.txt')
model.save_model('../models/model_'+test_name+'.xgb')
print("example input and prediction....")
print("zz sample 1st event input:")
print(df_zz.values[0])
print("y_pred_bkg first 20 events")
print(pred_label[:20])
#plot feature importances
model.feature_names = variables_names
xgb.plot_importance(model, max_num_features=len(variables), xlabel="F score (weight)")
plt.savefig(plotDir+'training/myImportances_Fscore_' + test_name + '.png')
os.system("chmod 755 "+plotDir+"training/*")
xgb.plot_tree( model )
fig = plt.gcf()
fig.set_size_inches(500, 50)
plt.draw()
plt.savefig(plotDir+'training/myTree_' + test_name + '.png')
plt.savefig(plotDir+'training/myTree_' + test_name + '.svg')
os.system("chmod 755 "+plotDir+"training/*")
<file_sep>/scripts/bdt_looper/xgboost/python/plot_wwz_vs_ttz_features.py
#!/usr/bin/env python
# coding: utf-8
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
import ROOT as root
import os
import shlex
import uproot
####################option A:##################
##train a single BDT to discriminate signal with ttz backgrounds
##use emu events for training
##with ttz backgrounds included
##############################################
root.gROOT.SetBatch(True)
for channel in ["emu", "OffZ"]:
test_name = channel+'_wwz_vs_ttz'
plotDir = "/home/users/zhicaiz/public_html/WWZ/BDT/"
pwd = os.getcwd()
dataDir = pwd.replace("python", "data/All/compare/")
os.system("mkdir -p "+plotDir)
os.system("mkdir -p "+plotDir+"variables_compare")
##Define variables to be used
variables = ["eventweight","nb","nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore', "MllN", "lep3MT", "lep4MT", "lep34MT", "ZPt"]
variables_names = ["eventweight","nb","nj", 'minDRJToL3','minDRJToL4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1Btag', 'jet2Btag', 'jet3Btag', 'jet4Btag', "Mll34", "lep3MT", "lep4MT", "lep34MT", "ZPt"]
print(len(variables))
##Getting ROOT files into pandas
df_wwz_PassTTZBDTAndbVeto = uproot.open(dataDir+"wwz_"+channel+"_PassTTZBDTAndbVeto.root")['t'].pandas.df(variables, flatten=False)
df_wwz_PassTTZBDTFailbVeto = uproot.open(dataDir+"wwz_"+channel+"_PassTTZBDTFailbVeto.root")['t'].pandas.df(variables, flatten=False)
df_wwz_PassbVetoFailTTZBDT = uproot.open(dataDir+"wwz_"+channel+"_PassbVetoFailTTZBDT.root")['t'].pandas.df(variables, flatten=False)
df_ttz_PassTTZBDTAndbVeto = uproot.open(dataDir+"ttz_"+channel+"_PassTTZBDTAndbVeto.root")['t'].pandas.df(variables, flatten=False)
df_ttz_PassTTZBDTFailbVeto = uproot.open(dataDir+"ttz_"+channel+"_PassTTZBDTFailbVeto.root")['t'].pandas.df(variables, flatten=False)
df_ttz_PassbVetoFailTTZBDT = uproot.open(dataDir+"ttz_"+channel+"_PassbVetoFailTTZBDT.root")['t'].pandas.df(variables, flatten=False)
####Plot input variables######
for idx in range(1, len(variables)):
plt.figure()
#y_wwz_PassTTZBDTAndbVeto, x_wwz_PassTTZBDTAndbVeto, _ = plt.hist(df_wwz_PassTTZBDTAndbVeto[df_wwz_PassTTZBDTAndbVeto[variables[idx]] > -999][variables[idx]], weights=df_wwz_PassTTZBDTAndbVeto[df_wwz_PassTTZBDTAndbVeto[variables[idx]] > -999][variables[0]], density=False, bins=50, alpha=1.0, histtype="step", lw=2, label="wwz "+channel+" - pass BDT and bVeto")
y_wwz_PassTTZBDTAndbVeto, x_wwz_PassTTZBDTAndbVeto, _ = plt.hist(df_wwz_PassTTZBDTAndbVeto[df_wwz_PassTTZBDTAndbVeto[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="wwz "+channel+" - pass BDT and bVeto", color='b')
y_wwz_PassTTZBDTFailbVeto, x_wwz_PassTTZBDTFailbVeto, _ = plt.hist(df_wwz_PassTTZBDTFailbVeto[df_wwz_PassTTZBDTFailbVeto[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="wwz "+channel+" - pass BDT fail bVeto", color='y')
y_wwz_PassbVetoFailTTZBDT, x_wwz_PassbVetoFailTTZBDT, _ = plt.hist(df_wwz_PassbVetoFailTTZBDT[df_wwz_PassbVetoFailTTZBDT[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="wwz "+channel+" - pass bVeto fail BDT", color='g')
y_ttz_PassTTZBDTAndbVeto, x_ttz_PassTTZBDTAndbVeto, _ = plt.hist(df_ttz_PassTTZBDTAndbVeto[df_ttz_PassTTZBDTAndbVeto[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="ttz "+channel+" - pass BDT and bVeto", color='r')
y_ttz_PassTTZBDTFailbVeto, x_ttz_PassTTZBDTFailbVeto, _ = plt.hist(df_ttz_PassTTZBDTFailbVeto[df_ttz_PassTTZBDTFailbVeto[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="ttz "+channel+" - pass BDT fail bVeto", color='m')
y_ttz_PassbVetoFailTTZBDT, x_ttz_PassbVetoFailTTZBDT, _ = plt.hist(df_ttz_PassbVetoFailTTZBDT[df_ttz_PassbVetoFailTTZBDT[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="ttz "+channel+" - pass bVeto fail BDT", color='c')
y_max1 = max([max(y_wwz_PassTTZBDTAndbVeto), max(y_wwz_PassTTZBDTFailbVeto), max(y_wwz_PassbVetoFailTTZBDT), max(y_ttz_PassTTZBDTAndbVeto), max(y_ttz_PassTTZBDTFailbVeto), max(y_ttz_PassbVetoFailTTZBDT)])
y_max2 = max([max(y_wwz_PassTTZBDTAndbVeto), max(y_ttz_PassTTZBDTAndbVeto), max(y_ttz_PassTTZBDTFailbVeto), max(y_ttz_PassbVetoFailTTZBDT)])
plt.legend(loc="upper center", fontsize = 30)
plt.xlabel(variables[idx], fontsize=50)
plt.ylabel('Events', fontsize=30)
plt.xticks(fontsize=35)
plt.yticks(fontsize=30)
if "MT" in variables[idx]:
plt.xlim([0.0, 500.0])
plt.ylim([0.0*y_max1, 2.0*y_max1])
#plt.ylim([0.00001*y_max, 200.0*y_max])
#plt.yscale("log")
fig = plt.gcf()
fig.set_size_inches(16, 12)
plt.draw()
plt.savefig(plotDir+'variables_compare/'+test_name + '_' + variables[idx]+'_all.png')
plt.figure()
y_wwz_PassTTZBDTAndbVeto, x_wwz_PassTTZBDTAndbVeto, _ = plt.hist(df_wwz_PassTTZBDTAndbVeto[df_wwz_PassTTZBDTAndbVeto[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="wwz "+channel+" - pass BDT and bVeto", color='b')
y_ttz_PassTTZBDTAndbVeto, x_ttz_PassTTZBDTAndbVeto, _ = plt.hist(df_ttz_PassTTZBDTAndbVeto[df_ttz_PassTTZBDTAndbVeto[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="ttz "+channel+" - pass BDT and bVeto", color='r')
y_ttz_PassTTZBDTFailbVeto, x_ttz_PassTTZBDTFailbVeto, _ = plt.hist(df_ttz_PassTTZBDTFailbVeto[df_ttz_PassTTZBDTFailbVeto[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="ttz "+channel+" - pass BDT fail bVeto", color='m')
y_ttz_PassbVetoFailTTZBDT, x_ttz_PassbVetoFailTTZBDT, _ = plt.hist(df_ttz_PassbVetoFailTTZBDT[df_ttz_PassbVetoFailTTZBDT[variables[idx]] > -999][variables[idx]], density=True, bins=50, alpha=1.0, histtype="step", lw=2, label="ttz "+channel+" - pass bVeto fail BDT", color='c')
y_max2 = max([max(y_wwz_PassTTZBDTAndbVeto), max(y_ttz_PassTTZBDTAndbVeto), max(y_ttz_PassTTZBDTFailbVeto), max(y_ttz_PassbVetoFailTTZBDT)])
plt.legend(loc="upper center", fontsize = 30)
plt.xlabel(variables[idx], fontsize=50)
plt.ylabel('Events', fontsize=30)
plt.xticks(fontsize=35)
plt.yticks(fontsize=30)
if "MT" in variables[idx]:
plt.xlim([0.0, 500.0])
plt.ylim([0.0*y_max2, 1.5*y_max2])
fig = plt.gcf()
fig.set_size_inches(16, 12)
plt.draw()
plt.savefig(plotDir+'variables_compare/'+test_name + '_' + variables[idx]+'_onewwz.png')
os.system("chmod 755 "+plotDir+"variables_compare/*")
<file_sep>/scripts/bdt_looper/xgboost/README.md
### package installation for xgboost training
first, go to a directory where you want to install anaconda - it takes about 7G space...
install anaconda - you only need to do this once!
```
cp /nfs-7/userdata/zhicaiz/Anaconda3-2019.03-Linux-x86_64.sh ./
./Anaconda3-2019.03-Linux-x86_64.sh
```
now you need to remove all the stuff in ~/.bashrc about conda: starting from >>> conda initialize >>> to the end
and then when you want to use conda, do:
```
source YOUR_DIR_TO_CONDA/etc/profile.d/conda.sh; conda activate
```
(don't source setup.sh in the main looper before you do this)
whne you want to get out of conda, do :
```
conda deactivate
```
then install the following packages...
install root for python3:
```
conda uninstall cfitsio
conda uninstall curl
conda uninstall krb5
conda install -c conda-forge krb5=1.16.3
conda install -c conda-forge curl=7.64.1
conda install -c conda-forge cfitsio=3.470
conda install -c conda-forge root=6.18.00
```
install other packages
```
pip install root_pandas
conda install -c conda-forge xgboost
pip install matplotlib
pip install uproot
conda install -c conda-forge tensorflow
conda install -c conda-forge keras
```
### To convert xgboost models into c++ header file, do
```
cd python
source convert_to_c.sh
```
this will generate the corresponding c++ header files that can be directly used to evaluate BDT on the fly in the looper, for example:
```
#include "wwz_vs_zz_emuHighTTZBDT.h"
// other code....
std::vector<float> test_sample_ZZ{bdt.met_pt(),bdt.lep3Pt(),bdt.lep4Pt(),bdt.ZPt(),bdt.lep3dZ(),bdt.lep4dZ(),bdt.lep3MT(),bdt.lep4MT(),bdt.lep34MT(),bdt.phi0(),bdt.theta0(),bdt.phi(),bdt.theta1(),bdt.theta2(),bdt.MllN(),bdt.pt_zeta(),bdt.pt_zeta_vis()};
float BDT_zz_emuHighTTZBDT = wwz_vs_zz_emuHighTTZBDT(test_sample_ZZ, true)[0]; // true means get probability, which is what we use to get BDT, false means to get weight
```
all the header files of the existing model can be found in models/cpp/ , with the corresponding input variables in python/train_*.py
<file_sep>/scripts/bdt_looper/xgboost/python/cmd_append.sh
#!/bin/bash
INPUTDIR=$1 #/nfs-7/userdata/zhicaiz/babies/
version=$2
for year in 2018 2016 2017
do
rm cmd_${year}.sh
THISINPUTDIR=${INPUTDIR}WVZ${year}_${version}
for i in $(ls ${THISINPUTDIR}); do
if [ $year == '2018' ]; then
echo python append_xgboost_discriminator_to_tree.py ${THISINPUTDIR} $i yes >> cmd_${year}.sh
else
echo python append_xgboost_discriminator_to_tree.py ${THISINPUTDIR} $i no >> cmd_${year}.sh
fi
done
done
##then do the following:
#source cmd_2016.sh
#source cmd_2017.sh
#source cmd_2018.sh
<file_sep>/scripts/bdt_looper/xgboost/python/convert_to_c.sh
for model in \
wwz_vs_ttz_nbAll \
wwz_vs_zz_emuHighTTZBDT \
wwz_vs_zz_OffZHighTTZBDT
#wwz_vs_zz_OffZ \
#wwz_vs_zz_emu \
#wwz_vs_ttzzz_emu \
#wwz_vs_ttzzz_bVeto \
#wwz_vs_ttzzz_OffZ \
#wwz_vs_ttz_nbAll \
#wwz_vs_ttz_emu \
#wwz_vs_ttz_bVeto \
#wwz_vs_ttz_OffZ
do
python raw_to_cpp.py --xgb_dump=../models/model_xgb_${model}.txt --num_classes=1 --func_name=${model}
mv ${model}.h ../models/cpp/
done
<file_sep>/scripts/bdt_looper/xgboost/python/append_xgboost_discriminator_to_tree.py
#!/usr/bin/env python
import matplotlib.pyplot as plt
import xgboost as xgb
import numpy as np
import pandas as pd
import math
import pickle as pickle
import ROOT as root
import uproot
import sys, os
#################
##Preliminaries
#################
root.gROOT.Reset()
if __name__ == "__main__":
#plotDir = "/home/users/zhicaiz/public_html/WWZ/BDT/"
plotDir = "../plots/"
os.system("mkdir -p "+plotDir)
fileDir = sys.argv[1]
sample = sys.argv[2]
filterBDTvariables = "yes"
mkplot = "yes"
if len(sys.argv) > 3:
mkplot = sys.argv[3]
if len(sys.argv) > 4:
filterBDTvariables = sys.argv[4]
FileName = fileDir + "/" + sample
os.system("mkdir -p "+fileDir+".BDT")
File = root.TFile(FileName)
Tree = File.Get('t')
if Tree.GetEntries() < 1:
os.system("cp "+FileName+" "+fileDir+".BDT/"+sample)
sys.exit(0)
Nevents = File.Get('h_neventsinfile')
##Define variables to be used
variables_ttzzz_bVeto = ['met_pt','lep3Id','lep4Id','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis', "nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore']
variables_ttzzz_emu = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis', "nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore']
variables_ttzzz_OffZ = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis', "nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore']
variables_zz_emu = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis']
variables_zz_emuHighTTZBDT = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis']
variables_zz_OffZ = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis']
variables_zz_OffZHighTTZBDT = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis']
variables_ttz_nbAll = ["nb","nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore', "MllN", "lep3MT", "lep4MT", "lep34MT", "ZPt"]
variables_ttz_bVeto = ["nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore', "MllN", "lep3MT", "lep4MT", "lep34MT", "ZPt"]
variables_ttz_emu = ["nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore', "MllN", "lep3MT", "lep4MT", "lep34MT", "ZPt"]
variables_ttz_OffZ = ["nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore', "MllN", "lep3MT", "lep4MT", "lep34MT", "ZPt"]
variables_multi_nbAll = ['met_pt','lep3Id','lep4Id','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis', "nj", "nb", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore']
variables_multi_emuHighTTZBDT = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis', "nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore']
variables_multi_emu = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis', "nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore']
variables_multi_OffZHighTTZBDT = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis', "nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore']
variables_multi_OffZ = ['met_pt','lep3Pt','lep4Pt','ZPt','lep3dZ', 'lep4dZ','lep3MT','lep4MT','lep34MT','phi0','theta0','phi','theta1','theta2','MllN', 'pt_zeta', 'pt_zeta_vis', "nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore']
##Getting ROOT files into pandas
df_ttzzz_bVeto = uproot.open(FileName)['t'].pandas.df(variables_ttzzz_bVeto, flatten=False)
df_ttzzz_emu = uproot.open(FileName)['t'].pandas.df(variables_ttzzz_emu, flatten=False)
df_ttzzz_OffZ = uproot.open(FileName)['t'].pandas.df(variables_ttzzz_OffZ, flatten=False)
df_zz_emu = uproot.open(FileName)['t'].pandas.df(variables_zz_emu, flatten=False)
df_zz_emuHighTTZBDT = uproot.open(FileName)['t'].pandas.df(variables_zz_emuHighTTZBDT, flatten=False)
df_zz_OffZ = uproot.open(FileName)['t'].pandas.df(variables_zz_OffZ, flatten=False)
df_zz_OffZHighTTZBDT = uproot.open(FileName)['t'].pandas.df(variables_zz_OffZHighTTZBDT, flatten=False)
df_ttz_nbAll = uproot.open(FileName)['t'].pandas.df(variables_ttz_nbAll, flatten=False)
df_ttz_bVeto = uproot.open(FileName)['t'].pandas.df(variables_ttz_bVeto, flatten=False)
df_ttz_emu = uproot.open(FileName)['t'].pandas.df(variables_ttz_emu, flatten=False)
df_ttz_OffZ = uproot.open(FileName)['t'].pandas.df(variables_ttz_OffZ, flatten=False)
df_multi_nbAll = uproot.open(FileName)['t'].pandas.df(variables_multi_nbAll, flatten=False)
df_multi_emuHighTTZBDT = uproot.open(FileName)['t'].pandas.df(variables_multi_emuHighTTZBDT, flatten=False)
df_multi_emu = uproot.open(FileName)['t'].pandas.df(variables_multi_emu, flatten=False)
df_multi_OffZHighTTZBDT = uproot.open(FileName)['t'].pandas.df(variables_multi_OffZHighTTZBDT, flatten=False)
df_multi_OffZ = uproot.open(FileName)['t'].pandas.df(variables_multi_OffZ, flatten=False)
x_test_ttzzz_bVeto = df_ttzzz_bVeto.values
y_test_ttzzz_bVeto = np.zeros(len(df_ttzzz_bVeto))
x_test_ttzzz_emu = df_ttzzz_emu.values
y_test_ttzzz_emu = np.zeros(len(df_ttzzz_emu))
x_test_ttzzz_OffZ = df_ttzzz_OffZ.values
y_test_ttzzz_OffZ = np.zeros(len(df_ttzzz_OffZ))
x_test_zz_emu = df_zz_emu.values
y_test_zz_emu = np.zeros(len(df_zz_emu))
x_test_zz_emuHighTTZBDT = df_zz_emuHighTTZBDT.values
y_test_zz_emuHighTTZBDT = np.zeros(len(df_zz_emuHighTTZBDT))
x_test_zz_OffZ = df_zz_OffZ.values
y_test_zz_OffZ = np.zeros(len(df_zz_OffZ))
x_test_zz_OffZHighTTZBDT = df_zz_OffZHighTTZBDT.values
y_test_zz_OffZHighTTZBDT = np.zeros(len(df_zz_OffZHighTTZBDT))
x_test_ttz_nbAll = df_ttz_nbAll.values
y_test_ttz_nbAll = np.zeros(len(df_ttz_nbAll))
x_test_ttz_bVeto = df_ttz_bVeto.values
y_test_ttz_bVeto = np.zeros(len(df_ttz_bVeto))
x_test_ttz_emu = df_ttz_emu.values
y_test_ttz_emu = np.zeros(len(df_ttz_emu))
x_test_ttz_OffZ = df_ttz_OffZ.values
y_test_ttz_OffZ = np.zeros(len(df_ttz_OffZ))
x_test_multi_nbAll = df_multi_nbAll.values
y_test_multi_nbAll = np.zeros(len(df_multi_nbAll))
x_test_multi_emuHighTTZBDT = df_multi_emuHighTTZBDT.values
y_test_multi_emuHighTTZBDT = np.zeros(len(df_multi_emuHighTTZBDT))
x_test_multi_emu = df_multi_emu.values
y_test_multi_emu = np.zeros(len(df_multi_emu))
x_test_multi_OffZHighTTZBDT = df_multi_OffZHighTTZBDT.values
y_test_multi_OffZHighTTZBDT = np.zeros(len(df_multi_OffZHighTTZBDT))
x_test_multi_OffZ = df_multi_OffZ.values
y_test_multi_OffZ = np.zeros(len(df_multi_OffZ))
############################
# get model from file
############################
model_ttzzz_bVeto = pickle.load(open('../models/model_xgb_wwz_vs_ttzzz_bVeto.pkl','rb'))
model_ttzzz_emu = pickle.load(open('../models/model_xgb_wwz_vs_ttzzz_emu.pkl','rb'))
model_ttzzz_OffZ = pickle.load(open('../models/model_xgb_wwz_vs_ttzzz_OffZ.pkl','rb'))
model_zz_emu = pickle.load(open('../models/model_xgb_wwz_vs_zz_emu.pkl','rb'))
model_zz_emuHighTTZBDT = pickle.load(open('../models/model_xgb_wwz_vs_zz_emuHighTTZBDT.pkl','rb'))
model_zz_OffZ = pickle.load(open('../models/model_xgb_wwz_vs_zz_OffZ.pkl','rb'))
model_zz_OffZHighTTZBDT = pickle.load(open('../models/model_xgb_wwz_vs_zz_OffZHighTTZBDT.pkl','rb'))
model_ttz_nbAll = pickle.load(open('../models/model_xgb_wwz_vs_ttz_nbAll.pkl','rb'))
model_ttz_bVeto = pickle.load(open('../models/model_xgb_wwz_vs_ttz_bVeto.pkl','rb'))
model_ttz_emu = pickle.load(open('../models/model_xgb_wwz_vs_ttz_emu.pkl','rb'))
model_ttz_OffZ = pickle.load(open('../models/model_xgb_wwz_vs_ttz_OffZ.pkl','rb'))
model_multi_nbAll = pickle.load(open('../models/model_xgb_wwz_vs_multi_nbAll.pkl','rb'))
model_multi_emuHighTTZBDT = pickle.load(open('../models/model_xgb_wwz_vs_multi_emuHighTTZBDT.pkl','rb'))
model_multi_emu = pickle.load(open('../models/model_xgb_wwz_vs_multi_emu.pkl','rb'))
model_multi_OffZHighTTZBDT = pickle.load(open('../models/model_xgb_wwz_vs_multi_OffZHighTTZBDT.pkl','rb'))
model_multi_OffZ = pickle.load(open('../models/model_xgb_wwz_vs_multi_OffZ.pkl','rb'))
# make predictions for test data
y_pred_ttzzz_bVeto = model_ttzzz_bVeto.predict_proba(x_test_ttzzz_bVeto)[:, 1]
y_pred_ttzzz_emu = model_ttzzz_emu.predict_proba(x_test_ttzzz_emu)[:, 1]
y_pred_ttzzz_OffZ = model_ttzzz_OffZ.predict_proba(x_test_ttzzz_OffZ)[:, 1]
y_pred_zz_emu = model_zz_emu.predict_proba(x_test_zz_emu)[:, 1]
y_pred_zz_emuHighTTZBDT = model_zz_emuHighTTZBDT.predict_proba(x_test_zz_emuHighTTZBDT)[:, 1]
y_pred_zz_OffZ = model_zz_OffZ.predict_proba(x_test_zz_OffZ)[:, 1]
y_pred_zz_OffZHighTTZBDT = model_zz_OffZHighTTZBDT.predict_proba(x_test_zz_OffZHighTTZBDT)[:, 1]
y_pred_ttz_nbAll = model_ttz_nbAll.predict_proba(x_test_ttz_nbAll)[:, 1]
y_pred_ttz_bVeto = model_ttz_bVeto.predict_proba(x_test_ttz_bVeto)[:, 1]
y_pred_ttz_emu = model_ttz_emu.predict_proba(x_test_ttz_emu)[:, 1]
y_pred_ttz_OffZ = model_ttz_OffZ.predict_proba(x_test_ttz_OffZ)[:, 1]
d_test_multi_nbAll = xgb.DMatrix(x_test_multi_nbAll, label=y_test_multi_nbAll)
y_pred_multi_nbAll = model_multi_nbAll.predict(d_test_multi_nbAll)
d_test_multi_emuHighTTZBDT = xgb.DMatrix(x_test_multi_emuHighTTZBDT, label=y_test_multi_emuHighTTZBDT)
y_pred_multi_emuHighTTZBDT = model_multi_emuHighTTZBDT.predict(d_test_multi_emuHighTTZBDT)
d_test_multi_emu = xgb.DMatrix(x_test_multi_emu, label=y_test_multi_emu)
y_pred_multi_emu = model_multi_emu.predict(d_test_multi_emu)
d_test_multi_OffZHighTTZBDT = xgb.DMatrix(x_test_multi_OffZHighTTZBDT, label=y_test_multi_OffZHighTTZBDT)
y_pred_multi_OffZHighTTZBDT = model_multi_OffZHighTTZBDT.predict(d_test_multi_OffZHighTTZBDT)
d_test_multi_OffZ = xgb.DMatrix(x_test_multi_OffZ, label=y_test_multi_OffZ)
y_pred_multi_OffZ = model_multi_OffZ.predict(d_test_multi_OffZ)
#print y_pred
##########################################################
# make histogram of discriminator value for signal and bkg
##########################################################
y_frame_ttzzz_bVeto = pd.DataFrame({'truth':y_test_ttzzz_bVeto, 'disc':y_pred_ttzzz_bVeto})
y_frame_ttzzz_emu = pd.DataFrame({'truth':y_test_ttzzz_emu, 'disc':y_pred_ttzzz_emu})
y_frame_ttzzz_OffZ = pd.DataFrame({'truth':y_test_ttzzz_OffZ, 'disc':y_pred_ttzzz_OffZ})
y_frame_zz_emu = pd.DataFrame({'truth':y_test_zz_emu, 'disc':y_pred_zz_emu})
y_frame_zz_emuHighTTZBDT = pd.DataFrame({'truth':y_test_zz_emuHighTTZBDT, 'disc':y_pred_zz_emuHighTTZBDT})
y_frame_zz_OffZ = pd.DataFrame({'truth':y_test_zz_OffZ, 'disc':y_pred_zz_OffZ})
y_frame_zz_OffZHighTTZBDT = pd.DataFrame({'truth':y_test_zz_OffZHighTTZBDT, 'disc':y_pred_zz_OffZHighTTZBDT})
y_frame_ttz_nbAll = pd.DataFrame({'truth':y_test_ttz_nbAll, 'disc':y_pred_ttz_nbAll})
y_frame_ttz_bVeto = pd.DataFrame({'truth':y_test_ttz_bVeto, 'disc':y_pred_ttz_bVeto})
y_frame_ttz_emu = pd.DataFrame({'truth':y_test_ttz_emu, 'disc':y_pred_ttz_emu})
y_frame_ttz_OffZ = pd.DataFrame({'truth':y_test_ttz_OffZ, 'disc':y_pred_ttz_OffZ})
y_frame_multi_nbAll = pd.DataFrame({'truth':y_test_multi_nbAll, 'disc':y_pred_multi_nbAll})
y_frame_multi_emuHighTTZBDT = pd.DataFrame({'truth':y_test_multi_emuHighTTZBDT, 'disc':y_pred_multi_emuHighTTZBDT})
y_frame_multi_emu = pd.DataFrame({'truth':y_test_multi_emu, 'disc':y_pred_multi_emu})
y_frame_multi_OffZHighTTZBDT = pd.DataFrame({'truth':y_test_multi_OffZHighTTZBDT, 'disc':y_pred_multi_OffZHighTTZBDT})
y_frame_multi_OffZ = pd.DataFrame({'truth':y_test_multi_OffZ, 'disc':y_pred_multi_OffZ})
disc_ttzzz_bVeto = y_frame_ttzzz_bVeto[y_frame_ttzzz_bVeto['truth'] == 0]['disc'].values
disc_ttzzz_emu = y_frame_ttzzz_emu[y_frame_ttzzz_emu['truth'] == 0]['disc'].values
disc_ttzzz_OffZ = y_frame_ttzzz_OffZ[y_frame_ttzzz_OffZ['truth'] == 0]['disc'].values
disc_zz_emu = y_frame_zz_emu[y_frame_zz_emu['truth'] == 0]['disc'].values
disc_zz_emuHighTTZBDT = y_frame_zz_emuHighTTZBDT[y_frame_zz_emuHighTTZBDT['truth'] == 0]['disc'].values
disc_zz_OffZ = y_frame_zz_OffZ[y_frame_zz_OffZ['truth'] == 0]['disc'].values
disc_zz_OffZHighTTZBDT = y_frame_zz_OffZHighTTZBDT[y_frame_zz_OffZHighTTZBDT['truth'] == 0]['disc'].values
disc_ttz_nbAll = y_frame_ttz_nbAll[y_frame_ttz_nbAll['truth'] == 0]['disc'].values
disc_ttz_bVeto = y_frame_ttz_bVeto[y_frame_ttz_bVeto['truth'] == 0]['disc'].values
disc_ttz_emu = y_frame_ttz_emu[y_frame_ttz_emu['truth'] == 0]['disc'].values
disc_ttz_OffZ = y_frame_ttz_OffZ[y_frame_ttz_OffZ['truth'] == 0]['disc'].values
disc_multi_nbAll = y_frame_multi_nbAll[y_frame_multi_nbAll['truth'] == 0]['disc'].values
disc_multi_emuHighTTZBDT = y_frame_multi_emuHighTTZBDT[y_frame_multi_emuHighTTZBDT['truth'] == 0]['disc'].values
disc_multi_emu = y_frame_multi_emu[y_frame_multi_emu['truth'] == 0]['disc'].values
disc_multi_OffZHighTTZBDT = y_frame_multi_OffZHighTTZBDT[y_frame_multi_OffZHighTTZBDT['truth'] == 0]['disc'].values
disc_multi_OffZ = y_frame_multi_OffZ[y_frame_multi_OffZ['truth'] == 0]['disc'].values
if mkplot == "yes":
plt.figure()
plt.hist(disc_ttzzz_bVeto, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_ttzzz_bVeto_' + sample + '.png')
plt.figure()
plt.hist(disc_ttzzz_emu, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_ttzzz_emu_' + sample + '.png')
plt.figure()
plt.hist(disc_ttzzz_OffZ, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_ttzzz_OffZ_' + sample + '.png')
plt.figure()
plt.hist(disc_zz_emu, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_zz_emu_' + sample + '.png')
plt.figure()
plt.hist(disc_zz_emuHighTTZBDT, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_zz_emuHighTTZBDT_' + sample + '.png')
plt.figure()
plt.hist(disc_zz_OffZ, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_zz_OffZ_' + sample + '.png')
plt.figure()
plt.hist(disc_zz_OffZHighTTZBDT, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_zz_OffZHighTTZBDT_' + sample + '.png')
plt.figure()
plt.hist(disc_ttz_nbAll, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_ttz_nbAll_' + sample + '.png')
plt.figure()
plt.hist(disc_ttz_bVeto, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_ttz_bVeto_' + sample + '.png')
plt.figure()
plt.hist(disc_ttz_emu, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_ttz_emu_' + sample + '.png')
plt.figure()
plt.hist(disc_ttz_OffZ, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_ttz_OffZ_' + sample + '.png')
plt.figure()
plt.figure()
plt.hist(disc_multi_nbAll, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_multi_nbAll_' + sample + '.png')
plt.figure()
plt.hist(disc_multi_emuHighTTZBDT, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_multi_emuHighTTZBDT_' + sample + '.png')
plt.figure()
plt.hist(disc_multi_emu, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_multi_emu_' + sample + '.png')
plt.figure()
plt.hist(disc_multi_OffZHighTTZBDT, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_multi_OffZHighTTZBDT_' + sample + '.png')
os.system("chmod 755 "+plotDir+"scores/*")
plt.figure()
plt.hist(disc_multi_OffZ, density=True, bins=50, alpha=0.3)
plt.yscale("log")
plt.savefig(plotDir+'scores/BDTscore_multi_OffZ_' + sample + '.png')
os.system("chmod 755 "+plotDir+"scores/*")
#############################################
##Creating a new TTree with the discriminator
#############################################
ch = root.TChain("t")
ch.Add(FileName)
if filterBDTvariables == "yes":
ch.SetBranchStatus("lep_Z_idx0",0)
ch.SetBranchStatus("lep_Z_idx1",0)
ch.SetBranchStatus("lep_N_idx0",0)
ch.SetBranchStatus("lep_N_idx1",0)
ch.SetBranchStatus("eventweight",0)
ch.SetBranchStatus("lepsf",0)
ch.SetBranchStatus("MllN",0)
ch.SetBranchStatus("MllZ",0)
ch.SetBranchStatus("ZPt",0)
ch.SetBranchStatus("lep1Pt",0)
ch.SetBranchStatus("lep2Pt",0)
ch.SetBranchStatus("lep3Pt",0)
ch.SetBranchStatus("lep4Pt",0)
ch.SetBranchStatus("lep3Id",0)
ch.SetBranchStatus("lep4Id",0)
ch.SetBranchStatus("lep3MT",0)
ch.SetBranchStatus("lep4MT",0)
ch.SetBranchStatus("lep34MT",0)
ch.SetBranchStatus("lep1dZ",0)
ch.SetBranchStatus("lep2dZ",0)
ch.SetBranchStatus("lep3dZ",0)
ch.SetBranchStatus("lep4dZ",0)
ch.SetBranchStatus("pt_zeta",0)
ch.SetBranchStatus("pt_zeta_vis",0)
ch.SetBranchStatus("phi0",0)
ch.SetBranchStatus("phi",0)
ch.SetBranchStatus("phiH",0)
ch.SetBranchStatus("theta0",0)
ch.SetBranchStatus("theta1",0)
ch.SetBranchStatus("theta2",0)
ch.SetBranchStatus("minDRJetToLep3",0)
ch.SetBranchStatus("minDRJetToLep4",0)
ch.SetBranchStatus("jet1Pt",0)
ch.SetBranchStatus("jet2Pt",0)
ch.SetBranchStatus("jet3Pt",0)
ch.SetBranchStatus("jet4Pt",0)
ch.SetBranchStatus("jet1BtagScore",0)
ch.SetBranchStatus("jet2BtagScore",0)
ch.SetBranchStatus("jet3BtagScore",0)
ch.SetBranchStatus("jet4BtagScore",0)
nEntries = ch.GetEntries()
print("nEntries = "+str(nEntries))
outFile = fileDir+".BDT/"+sample
newFile = root.TFile(outFile,"RECREATE")
ch_new = ch.CloneTree(0)
root.gROOT.ProcessLine("struct MyStruct_ttzzz_bVeto{float disc_ttzzz_bVeto;};")
root.gROOT.ProcessLine("struct MyStruct_ttzzz_emu{float disc_ttzzz_emu;};")
root.gROOT.ProcessLine("struct MyStruct_ttzzz_OffZ{float disc_ttzzz_OffZ;};")
root.gROOT.ProcessLine("struct MyStruct_zz_emu{float disc_zz_emu;};")
root.gROOT.ProcessLine("struct MyStruct_zz_emuHighTTZBDT{float disc_zz_emuHighTTZBDT;};")
root.gROOT.ProcessLine("struct MyStruct_zz_OffZ{float disc_zz_OffZ;};")
root.gROOT.ProcessLine("struct MyStruct_zz_OffZHighTTZBDT{float disc_zz_OffZHighTTZBDT;};")
root.gROOT.ProcessLine("struct MyStruct_ttz_nbAll{float disc_ttz_nbAll;};")
root.gROOT.ProcessLine("struct MyStruct_ttz_bVeto{float disc_ttz_bVeto;};")
root.gROOT.ProcessLine("struct MyStruct_ttz_emu{float disc_ttz_emu;};")
root.gROOT.ProcessLine("struct MyStruct_ttz_OffZ{float disc_ttz_OffZ;};")
root.gROOT.ProcessLine("struct MyStruct_multi_nbAll{float disc_multi_nbAll;};")
root.gROOT.ProcessLine("struct MyStruct_multi_emuHighTTZBDT{float disc_multi_emuHighTTZBDT;};")
root.gROOT.ProcessLine("struct MyStruct_multi_emu{float disc_multi_emu;};")
root.gROOT.ProcessLine("struct MyStruct_multi_OffZHighTTZBDT{float disc_multi_OffZHighTTZBDT;};")
root.gROOT.ProcessLine("struct MyStruct_multi_OffZ{float disc_multi_OffZ;};")
from ROOT import MyStruct_ttzzz_bVeto
from ROOT import MyStruct_ttzzz_emu
from ROOT import MyStruct_ttzzz_OffZ
from ROOT import MyStruct_zz_emu
from ROOT import MyStruct_zz_emuHighTTZBDT
from ROOT import MyStruct_zz_OffZ
from ROOT import MyStruct_zz_OffZHighTTZBDT
from ROOT import MyStruct_ttz_nbAll
from ROOT import MyStruct_ttz_bVeto
from ROOT import MyStruct_ttz_emu
from ROOT import MyStruct_ttz_OffZ
from ROOT import MyStruct_multi_nbAll
from ROOT import MyStruct_multi_emuHighTTZBDT
from ROOT import MyStruct_multi_emu
from ROOT import MyStruct_multi_OffZHighTTZBDT
from ROOT import MyStruct_multi_OffZ
# Create branches in the tree
s_ttzzz_bVeto = MyStruct_ttzzz_bVeto()
s_ttzzz_emu = MyStruct_ttzzz_emu()
s_ttzzz_OffZ = MyStruct_ttzzz_OffZ()
s_zz_emu = MyStruct_zz_emu()
s_zz_emuHighTTZBDT = MyStruct_zz_emuHighTTZBDT()
s_zz_OffZ = MyStruct_zz_OffZ()
s_zz_OffZHighTTZBDT = MyStruct_zz_OffZHighTTZBDT()
s_ttz_nbAll = MyStruct_ttz_nbAll()
s_ttz_bVeto = MyStruct_ttz_bVeto()
s_ttz_emu = MyStruct_ttz_emu()
s_ttz_OffZ = MyStruct_ttz_OffZ()
s_multi_nbAll = MyStruct_multi_nbAll()
s_multi_emuHighTTZBDT = MyStruct_multi_emuHighTTZBDT()
s_multi_emu = MyStruct_multi_emu()
s_multi_OffZHighTTZBDT = MyStruct_multi_OffZHighTTZBDT()
s_multi_OffZ = MyStruct_multi_OffZ()
bpt_ttzzz_bVeto = ch_new.Branch('disc_ttzzz_bVeto',root.AddressOf(s_ttzzz_bVeto,'disc_ttzzz_bVeto'),'disc_ttzzz_bVeto/F');
bpt_ttzzz_emu = ch_new.Branch('disc_ttzzz_emu',root.AddressOf(s_ttzzz_emu,'disc_ttzzz_emu'),'disc_ttzzz_emu/F');
bpt_ttzzz_OffZ = ch_new.Branch('disc_ttzzz_OffZ',root.AddressOf(s_ttzzz_OffZ,'disc_ttzzz_OffZ'),'disc_ttzzz_OffZ/F');
bpt_zz_emu = ch_new.Branch('disc_zz_emu',root.AddressOf(s_zz_emu,'disc_zz_emu'),'disc_zz_emu/F');
bpt_zz_emuHighTTZBDT = ch_new.Branch('disc_zz_emuHighTTZBDT',root.AddressOf(s_zz_emuHighTTZBDT,'disc_zz_emuHighTTZBDT'),'disc_zz_emuHighTTZBDT/F');
bpt_zz_OffZ = ch_new.Branch('disc_zz_OffZ',root.AddressOf(s_zz_OffZ,'disc_zz_OffZ'),'disc_zz_OffZ/F');
bpt_zz_OffZHighTTZBDT = ch_new.Branch('disc_zz_OffZHighTTZBDT',root.AddressOf(s_zz_OffZHighTTZBDT,'disc_zz_OffZHighTTZBDT'),'disc_zz_OffZHighTTZBDT/F');
bpt_ttz_nbAll = ch_new.Branch('disc_ttz_nbAll',root.AddressOf(s_ttz_nbAll,'disc_ttz_nbAll'),'disc_ttz_nbAll/F');
bpt_ttz_bVeto = ch_new.Branch('disc_ttz_bVeto',root.AddressOf(s_ttz_bVeto,'disc_ttz_bVeto'),'disc_ttz_bVeto/F');
bpt_ttz_emu = ch_new.Branch('disc_ttz_emu',root.AddressOf(s_ttz_emu,'disc_ttz_emu'),'disc_ttz_emu/F');
bpt_ttz_OffZ = ch_new.Branch('disc_ttz_OffZ',root.AddressOf(s_ttz_OffZ,'disc_ttz_OffZ'),'disc_ttz_OffZ/F');
bpt_multi_nbAll = ch_new.Branch('disc_multi_nbAll',root.AddressOf(s_multi_nbAll,'disc_multi_nbAll'),'disc_multi_nbAll/F');
bpt_multi_emuHighTTZBDT = ch_new.Branch('disc_multi_emuHighTTZBDT',root.AddressOf(s_multi_emuHighTTZBDT,'disc_multi_emuHighTTZBDT'),'disc_multi_emuHighTTZBDT/F');
bpt_multi_emu = ch_new.Branch('disc_multi_emu',root.AddressOf(s_multi_emu,'disc_multi_emu'),'disc_multi_emu/F');
bpt_multi_OffZHighTTZBDT = ch_new.Branch('disc_multi_OffZHighTTZBDT',root.AddressOf(s_multi_OffZHighTTZBDT,'disc_multi_OffZHighTTZBDT'),'disc_multi_OffZHighTTZBDT/F');
bpt_multi_OffZ = ch_new.Branch('disc_multi_OffZ',root.AddressOf(s_multi_OffZ,'disc_multi_OffZ'),'disc_multi_OffZ/F');
for i in range(nEntries):
ch.GetEntry(i)
if i%10000==0:
print("Processing event nr. "+str(i)+" of " + str(nEntries))
s_ttzzz_bVeto.disc_ttzzz_bVeto = disc_ttzzz_bVeto[i]
s_ttzzz_emu.disc_ttzzz_emu = disc_ttzzz_emu[i]
s_ttzzz_OffZ.disc_ttzzz_OffZ = disc_ttzzz_OffZ[i]
s_zz_emu.disc_zz_emu = disc_zz_emu[i]
s_zz_emuHighTTZBDT.disc_zz_emuHighTTZBDT = disc_zz_emuHighTTZBDT[i]
s_zz_OffZHighTTZBDT.disc_zz_OffZHighTTZBDT = disc_zz_OffZHighTTZBDT[i]
s_ttz_nbAll.disc_ttz_nbAll = disc_ttz_nbAll[i]
s_ttz_bVeto.disc_ttz_bVeto = disc_ttz_bVeto[i]
s_ttz_emu.disc_ttz_emu = disc_ttz_emu[i]
s_ttz_OffZ.disc_ttz_OffZ = disc_ttz_OffZ[i]
s_multi_nbAll.disc_multi_nbAll = disc_multi_nbAll[i]
s_multi_emuHighTTZBDT.disc_multi_emuHighTTZBDT = disc_multi_emuHighTTZBDT[i]
s_multi_emu.disc_multi_emu = disc_multi_emu[i]
s_multi_OffZHighTTZBDT.disc_multi_OffZHighTTZBDT = disc_multi_OffZHighTTZBDT[i]
s_multi_OffZ.disc_multi_OffZ = disc_multi_OffZ[i]
ch_new.Fill()
ch_new.GetCurrentFile().Write()
Nevents.Write()
ch_new.GetCurrentFile().Close()
<file_sep>/scripts/bdt_looper/xgboost/python/prune_wwz_vs_ttz_nbAll_full.py
#!/usr/bin/env python
# coding: utf-8
import matplotlib.pyplot as plt
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_curve, roc_auc_score
import numpy as np
import pandas as pd
import math
import pickle as pickle
import ROOT as root
import os
import shlex
import uproot
####################option A:##################
##train a single BDT to discriminate signal with ttz backgrounds
##use emu events for training
##with ttz backgrounds included
##############################################
doAppend = False
root.gROOT.SetBatch(True)
test_name = 'xgb_wwz_vs_ttz_nbAll_full'
lumi_sf_sig = 1.0 # scale lumi from 2018 sample to full run2
lumi_sf_bkg = 1.0
plotDir = "/home/users/zhicaiz/public_html/WWZ/BDT/"
pwd = os.getcwd()
dataDir = pwd.replace("python", "data/All/nbAll/")
os.system("mkdir -p "+plotDir)
os.system("mkdir -p "+plotDir+"training")
os.system("mkdir -p "+plotDir+"results")
os.system("mkdir -p "+plotDir+"scores")
os.system("mkdir -p "+plotDir+"variables")
os.system("mkdir -p "+plotDir+"variables_compare")
os.system("mkdir -p "+plotDir+"cuts_scan")
#signal
signalFileName = dataDir + 'wwz.root'
signalFile = root.TFile(signalFileName)
signalTree = signalFile.Get('t')
signalTree.Draw('met_pt>>tmp1')
signalHisto = root.gDirectory.Get('tmp1')
signalEvents = lumi_sf_sig*signalHisto.Integral()
#bkg
bkgFileName = dataDir + 'ttz.root'
bkgFile = root.TFile(bkgFileName)
bkgTree = bkgFile.Get('t')
bkgTree.Draw('met_pt>>tmp2')
bkgHisto = root.gDirectory.Get('tmp2')
bkgEvents = lumi_sf_bkg*bkgHisto.Integral()
print('[INFO]: S =' + str(signalEvents) + '; B =' + str(bkgEvents) +"; S/sqrt(B) = " + str(signalEvents/math.sqrt(bkgEvents)))
##Define variables to be used
variables = ["nb","nj", 'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore', "MllN", "lep3MT", "lep4MT", "lep34MT", "ZPt", "M4l", "Pt4l"]
variables_names = ["nb","nj", 'minDRJToL3','minDRJToL4', 'jet1Pt', 'jet2Pt', 'jet3Pt', 'jet4Pt', 'jet1Btag', 'jet2Btag', 'jet3Btag', 'jet4Btag', "Mll34", "lep3MT", "lep4MT", "lep34MT", "ZPt", "M4l", "Pt4l"]
#variables = ["nb",'minDRJetToLep3','minDRJetToLep4', 'jet1Pt', 'jet1BtagScore', 'jet2BtagScore', 'jet3BtagScore', 'jet4BtagScore', "MllN", "ZPt", "M4l", "Pt4l"]
#variables_names = ["nb",'minDRJToL3','minDRJToL4', 'jet1Pt', 'jet1Btag', 'jet2Btag', 'jet3Btag', 'jet4Btag', "Mll34", "ZPt", "M4l", "Pt4l"]
print(len(variables))
##Getting ROOT files into pandas
df_signal = uproot.open(signalFileName)['t'].pandas.df(variables, flatten=False)
df_bkg = uproot.open(bkgFileName)['t'].pandas.df(variables, flatten=False)
#getting a numpy array from two pandas data frames
x = np.concatenate([df_bkg.values,df_signal.values])
#creating numpy array for target variables
y = np.concatenate([np.zeros(len(df_bkg)),
np.ones(len(df_signal))])
# split data into train and test sets
seed = 7
test_size = 0.4
sample_size = 1.0
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size = sample_size*(1-test_size), test_size=sample_size*test_size, random_state=seed)
model = xgb.XGBClassifier(max_depth=3, learning_rate=0.1, n_estimators=400, verbosity=2, reg_lambda=0.1)
model.fit(x_train, y_train)
y_pred = model.predict_proba(x_test)[:, 1]
predictions = [round(value) for value in y_pred]
accuracy = accuracy_score(y_test, predictions)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
AUC=roc_auc_score(y_test, y_pred)
print("AUC: "+str(AUC))
fpr, tpr, thr = roc_curve(y_test, y_pred)
index_remove = []
AUC_after_remove = []
fpr_remove = []
tpr_remove = []
variables_left = variables.copy()
x_train_left = np.copy(x_train)
x_test_left = np.copy(x_test)
for num_remove in range(len(variables)-1):
plt.figure()
plt.plot(fpr, tpr, lw=2, label='all variables, AUC = %.4f'%AUC)
print("trying to remove "+str(num_remove+1)+" variable...")
AUC_all = np.zeros(len(variables))
AUC_maximum = 0.0
fpr_remove_this = None
tpr_remove_this = None
for idx in range(len(variables)):
if idx in index_remove:
continue
idx_in_left = variables_left.index(variables[idx])
print("removing input variable: "+variables[idx])
x_train_prune = np.delete(x_train_left, idx_in_left, 1)
x_test_prune = np.delete(x_test_left, idx_in_left, 1)
model = xgb.XGBClassifier(max_depth=3, learning_rate=0.1, n_estimators=400, verbosity=2, reg_lambda=0.1)
model.fit(x_train_prune, y_train)
y_pred = model.predict_proba(x_test_prune)[:, 1]
predictions = [round(value) for value in y_pred]
accuracy = accuracy_score(y_test, predictions)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
AUC_this=roc_auc_score(y_test, y_pred)
print("AUC: "+str(AUC_this))
fpr_this, tpr_this, thr_this = roc_curve(y_test, y_pred)
plt.plot(fpr_this, tpr_this, lw=2, label='w/o '+variables_names[idx]+", AUC = %.4f"%AUC_this)
AUC_all[idx] = AUC_this
if AUC_this > AUC_maximum:
AUC_maximum = AUC_this
fpr_remove_this = np.copy(fpr_this)
tpr_remove_this = np.copy(tpr_this)
fpr_remove.append(fpr_remove_this)
tpr_remove.append(tpr_remove_this)
print("least important variable:")
idx_remove = np.argmax(AUC_all)
print("var"+str(idx_remove)+", "+variables[idx_remove]+", AUC = %.4f"%AUC_all[idx_remove])
#plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 0.4])
plt.ylim([0.6, 1.05])
plt.ylabel('Signal Efficiency')
plt.xlabel('Background Efficiency')
#plt.axhline(y=0.9, color="black", linestyle='--')
#plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
#plt.show()
plt.savefig(plotDir+'training/myroc_prune_' + test_name + '_remove'+str(num_remove+1)+'.png')
os.system("chmod 755 "+plotDir+"training/*")
idx_remove_in_left = variables_left.index(variables[idx_remove])
variables_left.remove(variables[idx_remove])
x_train_left = np.delete(x_train_left, idx_remove_in_left, 1)
x_test_left = np.delete(x_test_left, idx_remove_in_left, 1)
index_remove.append(idx_remove)
AUC_after_remove.append(AUC_all[idx_remove])
print("order of variables to be removed, and AUC after removing it")
names_removal = []
AUCs_removal = []
for idx in range(len(index_remove)):
print(variables[index_remove[idx]]+" %.4f"%AUC_after_remove[idx])
names_removal.append(variables_names[index_remove[idx]])
AUCs_removal.append(AUC_after_remove[idx])
##plot AUC vs feature names plot:
plt.figure()
plt.plot(names_removal, AUCs_removal, lw=2)
plt.xticks(rotation=90)
plt.xlabel('cumulative removed features (left to right)')
plt.ylabel('AUC after removal')
plt.savefig(plotDir+'training/AUC_vs_removed_features_'+test_name+'.png', bbox_inches='tight')
os.system("chmod 755 "+plotDir+"training/*")
##plot roc curve in steps of removal
plt.figure()
plt.plot(fpr, tpr, lw=2, label='all variables, AUC = %.4f'%AUC)
for idx in range(len(index_remove)):
plt.plot(fpr_remove[idx], tpr_remove[idx], lw=2, label='-'+variables_names[index_remove[idx]]+", AUC = %.4f"%AUC_after_remove[idx])
plt.xlim([0.0, 0.4])
plt.ylim([0.6, 1.05])
plt.ylabel('Signal Efficiency')
plt.xlabel('Background Efficiency')
#plt.axhline(y=0.9, color="black", linestyle='--')
#plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
#plt.show()
plt.savefig(plotDir+'training/myroc_prune_' + test_name + '_cumulative.png')
plt.yscale("log")
#plt.xscale("log")
plt.savefig(plotDir+'training/myroc_prune_' + test_name + '_cumulative_logY.png',bbox_inches='tight')
plt.yscale("log")
os.system("chmod 755 "+plotDir+"training/*")
<file_sep>/scripts/bdt_looper/xgboost/python/optimize_cut_ttZBDT.py
#!/usr/bin/env python
# coding: utf-8
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
import pickle as pickle
import ROOT as root
import os
import shlex
import uproot
####################option B:##################
##train two BDTs/: ZZ and ttZ
##use emu events for ZZ BDT training
##use events without bVeto for ttZ BDT training
##############################################
root.gROOT.SetBatch(True)
test_name = 'significance_vs_ttZBDT'
lumi_sf_sig = 1.0 # scale lumi from 2018 sample to full run2
lumi_sf_bkg = 1.0
plotDir = "/home/users/zhicaiz/public_html/WWZ/BDT/"
pwd = os.getcwd()
os.system("mkdir -p "+plotDir)
os.system("mkdir -p "+plotDir+"cuts_scan")
yield_emu_all = [13.67, 1.44, 45.39, 7.29, 1.7, 1.62, 1.49]
yield_OffZHighMET_all = [3.74, 0.73, 15.0, 2.38, 0.48, 0.46, 0.26]
for channel in ["emu", "OffZHighMET"]:
print("optimize channel: "+channel)
dataDir = pwd.replace("python", "data/All/"+channel+"NobVetoHighZZBDT/")
yield_all = np.array(yield_emu_all)
if "OffZHighMET" in channel:
yield_all = np.array(yield_OffZHighMET_all)
N_all = np.zeros(len(yield_all))
fileName_all = ["wwz", "zz", "ttz", "twz", "wz", "higgs", "othernoh"]
tree_all = {}
for idx in range(len(N_all)):
tree_all[idx] = root.TChain("t")
tree_all[idx].AddFile(dataDir + fileName_all[idx]+".root")
root.SetOwnership(tree_all[idx], True)
file_this = root.TFile(dataDir + fileName_all[idx]+".root")
tree_this = file_this.Get('t')
#tree_all.append(tree_this)
tree_this.Draw("met_pt>>temp","eventweight")
hist_this = root.gDirectory.Get('temp')
#N_all[idx] = tree_this.GetEntries()
N_all[idx] = hist_this.Integral()
#print("N_all:")
#print(N_all)
BDT_cuts = np.arange(0.8,0.996, 0.001)
L_cuts = np.zeros(len(BDT_cuts))
S_cuts = np.zeros(len(BDT_cuts))
B_cuts = np.zeros(len(BDT_cuts))
for idx1 in range(len(BDT_cuts)):
cut_this = "disc_ttz_nbAll > "+str(BDT_cuts[idx1])
#print(cut_this)
yield_this = np.zeros(len(yield_all))
for idx in range(len(N_all)):
#N_this = tree_all[idx].GetEntries(cut_this)
tree_all[idx].Draw("met_pt>>temp2","eventweight * ("+cut_this+")")
hist_this = root.gDirectory.Get('temp2')
N_this = hist_this.Integral()
yield_this[idx] = yield_all[idx]*N_this*1.0/N_all[idx]
s = yield_this[0]
b = 0.0
for idx in range(1, len(N_all)):
b = b + yield_this[idx]
L = math.sqrt(2.0*((s+b)*math.log(1+s/b) - s))
print(str(idx1)+" "+str(BDT_cuts[idx1])+", "+str(s) +", "+str(b)+ ", "+ str(L))
#print(yield_this)
L_cuts[idx1] = L
S_cuts[idx1] = s
B_cuts[idx1] = b
print(L_cuts)
print("max L: "+str(np.amax(L_cuts)))
best_cut = BDT_cuts[np.argmax(L_cuts)]
significanceWP90 = L_cuts[np.where(abs(BDT_cuts - 0.960) < 0.000001) [0]] [0]
#plt.figure()
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
ax1.plot(BDT_cuts, S_cuts, color='b', lw=2, label="sig vs threshold")
ax1.plot(BDT_cuts, B_cuts, color='r', lw=2, label="bkg vs threshold")
ax1.xaxis.grid()
ax1.yaxis.grid()
ax1.set_ylabel("Events")
ax1.legend()
ax1.set_title(channel+" - ZZ BDT > 0.9333")
ax2.plot(BDT_cuts, L_cuts, color='darkorange',
lw=2, label='significance vs threshold')
ax2.axvline(x=0.960, color="black", linestyle='--', label="WP90: th = 0.960, L = %.2f"%(significanceWP90))
ax2.axvline(x=best_cut, color="black", label="optimal cut: th = %.3f"%best_cut+", L = %.2f"%(np.amax(L_cuts)))
#plt.xlim([0.0, 1.0])
#plt.ylim([0.0, 10.0])
ax2.set_ylabel('significance')
ax2.set_xlabel('ttZ BDT cut')
ax2.legend(loc="upper left")
#plt.show()
plt.savefig(plotDir+'cuts_scan/' + test_name + '_'+channel+'.png')
os.system("chmod 755 "+plotDir+"cuts_scan/*")
| 165478aa697ba81d7adc1dc3b081fc97ffafb723 | [
"Markdown",
"Python",
"Shell"
]
| 12 | Python | zhangzc11/WVZLooper | 4b2eb46392c228672d5a2db30539b49aeb58cd1c | d55c24127a65a36bd4a0ac25a8c53c007b5a71a1 |
refs/heads/master | <repo_name>nadavye/SeaGull-Test<file_sep>/file1.js
console.log('hello nadav!');
console.log('have a very nice day!');
console.log('I am a new line, added by Nadav');
| ac1b589b33e38ffad36f2cb8cd4af68cdb6cb1ce | [
"JavaScript"
]
| 1 | JavaScript | nadavye/SeaGull-Test | 70523bca54a7d198c7d24a23db23811205c24ad7 | 82c3a278c36a57c02c9aaff65389fe0d5b42d9df |
refs/heads/main | <repo_name>analuizaporto/exercicios-python-mundo-2<file_sep>/README.md
# Exercicios Python Mundo 2
Exercícios do curso de Python 3 - Mundo 2 (40 horas) do [site](https://www.cursoemvideo.com/course/python-3-mundo-2/) e canal no [Youtube](https://www.youtube.com/watch?v=nJkVHusJp6E&list=PLHz_AreHm4dk_nZHmxxf_J0WRAqy5Czye): Curso em Vídeo - Professor <NAME>.
### Assuntos estudados:<h3>
**Estruturas de controle:**
* Condições aninhadas.
* Estruturas de repetição for.
* Estruturas de repetição while.
* Interrompendo repetições while.
<file_sep>/ex01.py
# Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa.
# O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar.
# Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário ou então o empréstimo será negado.
casa = float(input('Qual é o valor da casa? R$'))
salario = float(input('Qual é o seu salário? R$'))
anos = int(input('Em quantos anos você vai pagar a casa ?'))
prestacao = casa / (anos * 12)
if prestacao <= 0.3 * salario:
print('Empréstimo aprovado! A prestação é até 30% do seu salário. o valor da prestação é R${:.2f}.'.format(prestacao))
else:
print('Empréstimo negado, pois a prestação é maior do que 30% do seu salário!')
<file_sep>/ex03.py
# Crie um programa que leia duas notas de um aluno e calcule sua média mostrando uma mensagem final de acordo com a média atingida:
# Média abaixo de 5 → Reprovado
# Média entre 5 e 6.9 → Recuperação
# Média 7 ou superior → Aprovado
print('Vamos calcular a média das suas notas na sua prova de Matemática e saberemos se você foi aprovado!')
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
media = (nota1 + nota2) / 2
if media >= 7:
print('Parabéns! Sua média é {:.1f} e você está APROVADO!'.format(media))
elif 5< media <6.9:
print('Sua média é {:.1f} e você está de Recuperação! '.format(media))
else:
print('Sua média é {:.1f} e você está Reprovado. '.format(media))
| 9c2150792730d20a44efaaee9afda3f33b0a87bc | [
"Markdown",
"Python"
]
| 3 | Markdown | analuizaporto/exercicios-python-mundo-2 | c913dd2e313790bf5d88b7886b5c77f0ced3b2bb | fd476d650ce9fdb8a673564aa8ea838c2de80252 |
refs/heads/master | <repo_name>Jlegolas/pythonBasic<file_sep>/python/preservedCode.py
'''
1. all preserved key code are low
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
'''
'''
2. variable
stored in cpu memory
implemented only when it has real value
like:
numbers -- can't change. so if you change it, will allocate a new variable
int long float complex
string
list -- like array
Tuple -- read only list
Dictionary -- use key to visit the element
'''
'''
3. operators
arithmetic operator
+ - * / % **(like ^) //(like int(a/b))
comparison operators
== != <> > < >= <=
assigning operators
= += -= *= /= %= **= //=
logical operators
& | ^ ~ << >>
bitwise operators
and or not
member access operators
in not in
identity operators
is is not
operator precedence
**
~
* / % //
+ -
&
^ |
<= < > >=
<> == !=
= %= /= //= -= += *= **=
is is not
in not in
not or and
'''
'''
4. condition
if :
elif :
else:
'''
'''
5. circle
break continue pass
while for
example of while
cnt = 0
while (cnt < 9) :
cnt += 1
for can be used to traverse any list like string or others
example of for
for var in 'python' :
print(vav)
# maybe i will not be willing to use belowing code pragram.
while :
else :
for :
else :
'''<file_sep>/python/basicFunction.py
'''
1. function format
def functionname(parameters):
function_suite
return [expression]
2. function parameters
all are quote type
necessary parameter
key parameter
default parameter
uncertain length parameter
def functionname([format_args,] *var_args_tuple):
function_suite
return [expression]
3. anonymity function
lambda only a expression, not a code module
lambda [arg1 [,arg2,...argn]] : expression
'''
def printName (string):
print(string)
return
sum1 = lambda arg1, arg2: arg1 + arg2
printName("hello" + str(sum1(10,20)))
'''
a strange usage, maybe not use
'''
b = lambda x : lambda y : x + y
a=b(3)
print(a(2))
<file_sep>/economics/README.md
# report
reference technology book: http://blog.jobbole.com/106093/
中国科学院:
http://www.csdb.cn/
中国植物物种:
http://db.kib.ac.cn/eflora/default.aspx
<file_sep>/paddle/trainer_config.py
# -*- coding:utf-8 -*-
# trainer_config.py
from paddle.trainer_config_helpers import *
# 1. 定义数据来源,调用上面的process函数获得观测数据
data_file = 'empty.list'
with open(data_file, 'w') as f: f.writelines(' ')
define_py_data_sources2(train_list=data_file, test_list=None,
module='dataprovider', obj='process',args={})
# 2. 学习算法。控制如何改变模型参数 w 和 b
settings(batch_size=12, learning_rate=1e-3, learning_method=MomentumOptimizer())
# 3. 神经网络配置
x = data_layer(name='x', size=1)
y = data_layer(name='y', size=1)
# 线性计算单元: y_predict = wx + b
y_predict = fc_layer(input=x, param_attr=ParamAttr(name='w'), size=1, act=LinearActivation(), bias_attr=ParamAttr(name='b'))
# 损失计算,度量 y_predict 和真实 y 之间的差距
cost = regression_cost(input=y_predict, label=y)
outputs(cost)
<file_sep>/python/basicTimeFunc.py
'''
author: sping
'''
'''
1. time module
import time
functions:
time
localtime
strftime
mktime
%y
%Y
%m
%d
%H
%M
%l
%M
%S
%a
%A
%b
%B
%c
%j
%p
%U
%w
.....
2. calendar module
functions:
month
.....
3. datetime module
4. pytz module
5. dateutil module
'''
import time
import calendar
ticks = time.time()
localtime = time.localtime(ticks)
cal = calendar.month(2016, 1)
print(localtime)
print(cal)<file_sep>/python/basicLibFuncsForVari.py
'''
1. process number type variable
like:
int()
hex()
abs()
random()
sin()
pi
e
'''
'''
2. process string type variable
+
*
[]
[:]
in
not in
r/R
% -- print("My name is %s and weight is %d" % ('sping',60)
%c %s %d %u %o %x %X %f %e %E %g %G %p
* - + <sp> # 0 % (var) m.n
errHTML = '/'/'/
<HTML><HEAD><TITLE>
.......
'/'/'/
Unicode
u"Hello World"
string.capitalize()
string.center(width)
string.counter(str, beg = 0, end= len(string))
....
'''<file_sep>/README.md
# learning project
1. python
  learning basic python program
  WinPython-32bit-3.5.2.1Qt5
  https://www.python.org/
2. c & c++
3. paddle
4. economics
5. openstack guide https://www.cnblogs.com/fbwfbi/p/3508500.html
<file_sep>/paddle/dataprovider.py
# -*- coding:utf-8 -*-
# dataprovider.py
from paddle.trainer.PyDataProvider2 import *
import random
# 定义输入数据的类型: 2个浮点数
@provider(input_types=[dense_vector(1), dense_vector(1)],use_seq=False)
def process(settings, input_file):
for i in xrange(2000):
x = random.random()
yield [x], [2*x+0.3]
<file_sep>/python/basicLibFuncForContainer.py
'''
1. for list
+ *
[]
[:]
del
len()
cmp()
max()
min()
append()
count()
index()
insert()
reverse()
sort()
'''
'''
2. for tuple
del()
len()
tuple()
...
'''
'''
3. for dictionary
radiansdict.clear()
radiansdict.copy()
...
'''<file_sep>/las/las.py
from
if '__main__' == __name__:
print("Hi, world. I'm born in 5.8. My name is las.")<file_sep>/python/basicPyModule.py
'''
author: sping
module is a file to store functions, classes, variables
import moduleName
from moduleName import subName or *
interpreter use following sequence to find module
1. current path
2. shell's PYTHONPATH
3. default path. /usr/local/lib/python/ of UNIX
if a function want to set value to global variabel,
you must use "global" keyword.like:
global varName
dir()
list all elements of a module.like:
import math
dir(math)
globals()
locals()
reload(moduleName)
package
'''
<file_sep>/python/sping.py
'''
1. next to know
1) CGI programming
2) next as interest. change to c++
'''
'''
2. learning method:
1) basic grammer
2) application scenario
'''
<file_sep>/python/basicObject.py
'''
author: sping
'''
'''
make class
class className:
classSuit
help info msg can get from className.__doc__
classSuit include:
1. class element
2. method
3. data
'''
class Employee :
def __init__(self, age):
self.age = age
emp = Employee(1)
'''
access operator .
'''
'''
class basic properties
__dict__
__doc__
__name__
__module__
__bases__
'''
'''
python object destroy mechanism
need to study
'''
'''
class inherrit
class SubclassName (ParaentClass1 [, ParentClass2] [,...]):
classSuit
'''
'''
class property and method
private: -- only can be accessed in class
__method
__property
'''<file_sep>/python/basicException.py
'''
author: sping
'''
'''
two very important ways to process exceptions and errors occured during running.
1. exception process
2. assertions
BaseException
SystemExit
KeyboardInterrupt
Exception
StopIteration
GeneratorExit
StandardError
ArithmeticError
FloatingPointError
OverflowError
ZeroDivisionError
AssertionError
AttributeError
EOFError
EnvironmentError
IOError
OSError
WindowsError
ImportError
LookupError
IndexError
KeyError
MemoryError
NameError
UnboundLocalError
ReferenceError
RuntimeError
NotImplementedError
SyntaxError
IndentationError
TabError
SystemError
TypeError
ValueError
UnicodeError
UnicodeDecodeError
UnicodeEncodeError
UnicodeTranslateError
Warning
DeprecationWarning
FutureWarning
OverflowWarning
PendingDeprecationWarning
RuntimeWarning
SyntaxWarning
UserWarning
'''
'''
what is exception.
exception is a event. this event will interrupt procedure normal running.
how to solve this problem.
try :
suite
except <name> :
suite
except <name>,<data> :
suite
else :
suite
'''
try :
fo = open("testfile", "w")
fo.write("sping")
except IOError :
print("Error: no such file")
else :
print("write file successfully.")
fo.close()
'''
three type of try/except
1.
try :
except errName :
else :
2.
try :
except :
else :
3.
try:
except (Exception1 [,Exception2] [,...]) :
else :
'''
'''
try - finally
try :
finally :
'''
try :
print(1)
except :
print(2)
else :
print(3)
finally:
print(4)
'''
try can nest
'''
'''
exception parametes
'''
def temp_convert(var):
try :
return int(var)
except ValueError as Argument:
print(Argument)
temp_convert("xx")
'''
raise keyword , to produce a exception
'''
def raiseFunc(level):
if level < 1 :
raise Exception("Invalid level!", level)
try :
raiseFunc(0)
except :#"Invalid level!":
print(1)
else :
print(2)
'''
user defined exception class
'''
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
try :
raise Networkerror("Bad hostname.")
except Networkerror as e:
print(e.args)
#print(2)<file_sep>/paddle/readOp.py
import numpy as np
import os
def load(file_name):
with open(file_name, 'rb') as f:
f.read(16)
return np.fromfile(f, dtype=np.float32)
i = 0
while(i<=29):
s_index=str(i)
if i <= 9:s_index = '0' + s_index
print 'w=%.6f, b=%.6f' % (load('output/pass-000%s/w' % s_index), load('output/pass-000%s/b' % s_index))
i += 1
<file_sep>/las/modules/interest/compand_interest.py
import numpy as np
def calc_period(result, rate, base):
return np.log((result / base)) / np.log(rate)
def calc_result(rate, period, base):
factor = 1 + rate
return base * np.exp(period * np.log(factor))
if '__main__' == __name__ :
print('Begin' + '\n')
print(calc_period(84487, 1.203, 19))
print(calc_result(0.15, 40, 40))
print('\n' + 'End.')<file_sep>/python/basicIO.py
'''
author: sping
'''
'''
print
raw_input
input
file object = open(file_name [, access_mode] [,buffering])
accessMode
r
rb
r+
rb+
w
wb
w+
wb+
a
ab
a+
ab+
file.closed
file.mode
file.name
file.softspace
close()
write()
read()
tell()
seek()
os.rename()
os.remove()
mkdir()
chdir()
rmdir()
file . os object
'''
| e6892a6b90e3c75ed509386f5ad86bdd12a707f9 | [
"Markdown",
"Python"
]
| 17 | Python | Jlegolas/pythonBasic | 832e313a61cb7e72c2bb8d65385369e87f67eb8c | b87841c5e17304759383446cb8b15a96fca04a14 |
refs/heads/master | <repo_name>parkjimin0/take-home-assessment<file_sep>/front/js/app.js
/**
* @file App main entry point.
*/
import '@babel/polyfill';
// Include the main scss file for webpack processing.
import '../css/app.scss';
import { renderApp, renderTime } from './components';
import getLogger from './utils/logger';
const log = getLogger('App');
const init = () => {
log.info('init() :: App starts booting...');
renderTime('#time')
renderApp('#app')
};
// init app
init();
<file_sep>/front/js/components/index.js
/**
* `components/index.js` exists simply as a 'central export' for rendering components back to Rails.
*/
export { default as renderApp } from './App'
export { default as renderTime } from './Timestamp'<file_sep>/app/controllers/home_controller.rb
class HomeController < ApplicationController
def index
end
def timestamp
render json: {timestamp: Time.now.to_i}
end
def time
render 'time'
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
# get 'jimin/index'
get 'jimin' => 'jimin#index'
get 'home' => 'home#index'
get 'home/timestamp'
get 'time' => 'home#time'
root 'home#index'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
| 7d570dfb7dca269eedb3463e969316553d5966fd | [
"JavaScript",
"Ruby"
]
| 4 | JavaScript | parkjimin0/take-home-assessment | bdd3e516b388be0e3d09359f33c572a9f907543f | 7c88f9d06406991ae1d2a2cffe41cf17ae9d298d |
refs/heads/main | <repo_name>lerryjay/grey-sender<file_sep>/v2/resource/functions.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require './PHPMailer/src/Exception.php';
require './PHPMailer/src/PHPMailer.php';
require './PHPMailer/src/SMTP.php';
function getPost($key)
{
return $_POST[$key];
}
function extractfilecontents($key)
{
return file_get_contents($_FILES[$key]['tmp_name']);
}
function sendMail($recipient,$smtp,$replyTo)
{
global $message,$subject,$fromEmail,$fromName;
$mail = new PHPMailer();
$output = [];
try {
$error;
$mail->SMTPDebug = 3; // Enable verbose debug output
// $mail->Debugoutput = function($str, $level) { echo $error = "debug level $level; message: $str";};
$mail->isSMTP(); // Send using SMTP
$mail->Host = $smtp['host'];//$line[3]; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = $smtp['username']; // SMTP username
$mail->Password = $smtp['<PASSWORD>'];
$mail->Port = (int)$smtp['port'];
$mail->setFrom($smtp['username'],$fromName);
//Recipient
$mail->addAddress($recipient); // Name is optional
$mail->ClearReplyTos();
foreach ($replyTo as $key => $value) {
$mail->addReplyTo($value['email'],$value['name']);
}
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
// var_dump($mail->getError());
return $mail->send();
}catch (phpmailerException $e) {
var_dump('i am here ');
// echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
var_dump('i am there ');
// echo $e->getMessage(); //Boring error messages from anything else!
$failed++;
}
}
?>
<file_sep>/v2/resource/index.php
<?php
set_time_limit(0);
include_once './functions.php';
$sent = false;
$success = 0;
$failed = 0;
$smtps = [];
$recipients = [];
if (isset($_POST['submit'])) {
if(getPost('recipients') == 'email'){
$recipients = strlen($_POST['recipientemail']) > 0 ? array($_POST['recipientemail']) : [];
}
if(getPost('recipients') == 'combotext'){
$recipients = explode("\n", $_POST['combotext']);
}
if(getPost('recipients') == 'mailtext'){
$recipients = explode("\n", $_POST['mailtext']);
}
if(getPost('recipients') == 'combofile'){
$recipients = explode("\n", extractfilecontents('combofile'));
for ($i=0; $i < count($recipients) ; $i++) {
$recipients[$i] = explode(':',$recipients[$i])[0];
}
}
if(getPost('recipients') == 'mailfile'){
$recipients = explode("\n", extractfilecontents('mailfile'));
}
$total = count($recipients);
if(getPost('smtp') == 'file'){
$smtps = explode("\n", extractfilecontents('smtpcombofile'));
for ($i=0; $i < count($smtps) ; $i++) {
$smtp = explode(':',$smtps[$i]);
$smtps[$i] = ['host'=>$smtp[0], 'ip'=>$smtp[1],'port'=>$smtp[2],'username'=>$smtp[3], 'password'=>$smtp[4]];
}
}
if(getPost('smtp') == 'textarea'){
$smtps = explode("\n",getPost('smtpconfigtext'));
for ($i=0; $i < count($smtps) ; $i++) {
$smtp = explode(':',$smtps[$i]);
$smtps[$i] = ['host'=>$smtp[0], 'ip'=>$smtp[1],'port'=>$smtp[2],'username'=>$smtp[3], 'password'=>$smtp[4]];
}
}
if(getPost('smtp') == 'configuration'){
$smtps[] = ['host'=>getPost('smtphost'),'ip'=>getPost('smtpip'),'port'=>getPost('smtpport'),'username'=>getPost('smtpuser'),'password'=>getPost('<PASSWORD>') ];
}
$subject = $_POST['subject'];
$message = $_POST['message'];
$fromEmail = $_POST['senderemail'];
$fromName = $_POST['sendername'];
$i = 0;
while (count($recipients) > $i && count($smtps) > 0) {
$smtpIndex = rand(0,count($smtps) - 1);
$res = sendMail($recipients[$i],$smtps[$smtpIndex]);
if(!$res){
$failed++;
array_splice($smtps,$smtpIndex);
}else{
$i++;
$success++;
}
// array_splice($recipients,$i,1);
}
exit;
header("Location: ../index.php?success=$success&failed=$failed&total=$total");
}
?>
<file_sep>/v2/assets/js/main.js
const recipients = document.querySelector("#recipients");
const smtp = document.querySelector("#smtp");
const handleOptionSwitch = (input,value,list)=>{
list.forEach(item => !document.querySelector(`#${input+"-"+item+"-input"}`).classList.contains("d-none") && document.querySelector(`#${input+"-"+item+"-input"}`).classList.add('d-none'));
document.querySelector(`#${input+"-"+value+"-input"}`).classList.contains("d-none") && document.querySelector(`#${input+"-"+value+"-input"}`).classList.remove('d-none');
}
const handleRecipientChange = ({ target })=>{
const value = target.value;
const list = ['email','mailfile','combofile','combotext','mailtext'];
handleOptionSwitch('recipients',value,list);
}
const handleSMTPInputChange = ({ target })=>{
const value = target.value;
const list = ['file','textarea','configuration'];
handleOptionSwitch('smtp',value,list);
}
recipients.addEventListener('change',handleRecipientChange);
smtp.addEventListener('change',handleSMTPInputChange);
document.onload = ()=>{
handleRecipientChange(recipients);
handleSMTPInputChange(smtp);
}<file_sep>/v2/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="assets/css/bootstrap.min.css" />
<link rel="stylesheet" href="assets/css/style.css" />
<title>Document</title>
</head>
<body class="text-white px-0">
<header>
<!-- As a heading -->
<nav class="navbar navbar-m bg-dark py-3 px-5">
<span class="navbar-brand mb-0 text-light h1 font-weight-bold">GREY Mailer</span>
</nav>
</header>
<form method="POST" enctype="multipart/form-data" action="http://localhost/mailer/v2/resource/index.php" >
<div class="container-fluid">
<div class="row px-md-5 pt-md-5">
<div class="col-md-6">
<div class="form-group">
<label for="recipients">Recipients:</label>
<select class="form-control" name="recipients" id="recipients">
<option value="email">Email</option>
<option value="mailfile">File (mails;.txt)</option>
<option value="combofile">File (combos;.txt)</option>
<option value="mailtext">Mail Text</option>
<option value="combotext">Combo Text</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="smtp">SMTP Configuartions:</label>
<select class="form-control" name="smtp" id="smtp">
<option value="file">File</option>
<option value="textarea">Textarea</option>
<option value="configuration" selected>Configuration</option>
</select>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row bg-dark-purple mid-area px-md-5 pt-md-4 my-md-5">
<div class="col-md-6">
<div class="form-group d-none" id="recipients-combofile-input">
<label for="combo-text">Combo File:</label>
<input class="form-control" type="file" type="combofile" name="combofile" />
</div>
<div class="form-group d-none" id="recipients-combotext-input">
<label for="combo-text">Combo Text:</label>
<textarea class="form-control" name="combo-text" id="combotext" rows="3" placeholder="email:password"></textarea>
</div>
<div class="form-group" id="recipients-email-input">
<label for="combo-text">Email:</label>
<input class="form-control" type="text" name="recipientemail" />
</div>
<div class="form-group d-none" id="recipients-mailfile-input">
<label for="combo-text">Mail File:</label>
<input class="form-control" type="file" type="mailfile" name="mailfile" />
</div>
<div class="form-group d-none" id="recipients-mailtext-input">
<label for="combo-text">Mail Text:</label>
<textarea class="form-control" name="mailtext" id="mailtext" rows="3" placeholder="email"></textarea>
</div>
</div>
<div class="col-md-6">
<div class="row" id="smtp-configuration-input">
<div class="col">
<label>Host:</label>
<input type="text" class="form-control" id="" name="smtphost" placeholder="">
</div>
<div class="col">
<label>Username:</label>
<input type="text" class="form-control" id="" name="smtpuser" placeholder="">
</div>
<div class="col">
<label>Password:</label>
<input type="text" class="form-control" id="" name="smtppass" placeholder="">
</div>
<div class="col">
<label>Port:</label>
<input type="text" class="form-control" id="" name="smtpport" placeholder="">
</div>
<div class="col">
<label>IP:</label>
<input type="text" class="form-control" id="" name="smtpip" placeholder="">
</div>
</div>
<div class="row">
<div class="col-md-12 d-none" id="smtp-textarea-input">
<div class="form-group">
<label for="">Configurations:</label>
<textarea class="form-control" name="smtpconfigtext" id="smtpconfigtext" placeholder="host:ip:port:username:password" rows="3"></textarea>
</div>
</div>
<div class="col-md-12 d-none" id="smtp-file-input">
<div class="form-group">
<label for="combo-text">Combo:</label>
<input class="form-control" name="smtpcombofile" type="file" id="smtpcombofile" rows="3" placeholder="email:password"/>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row px-5">
<div class="col-md-12">
<div class="form-group">
<label for="">Subject:</label>
<input type="text" class="form-control" name="subject" id="subject" >
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="message">Reply To:</label>
<textarea class="form-control" rows="1" name="message" id="message" rows="3"></textarea>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="sendername">Sender Name:</label>
<input type="text" class="form-control" name="sendername" id="sendername" placeholder="">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" name="message" id="message" rows="3"></textarea>
</div>
</div>
</div>
<div class="row px-5">
<div class="col-md-12">
<?php if (isset($_GET['total'])) { ?>
<h5>Total: <?php echo $_GET['total']; ?> Success: <?php echo $_GET['success']; ?> Failed:<?php echo $_GET['failed']; ?> </h5>
<?php } ?>
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-success px-5 p rounded-0" value="submit" name="submit">Submit</button>
</div>
</div>
</div>
</form>
</body>
<script src="./assets/js/main.js"></script>
</html>
| 0d3abebd50327ea85d0b136b70a360ea385aa6cb | [
"JavaScript",
"PHP"
]
| 4 | PHP | lerryjay/grey-sender | 5043b3a84fa1ad0a028cd1a6c5d163852ccdfa89 | b6c97ffbc377d7bbb897cd344e701f10c5b18671 |
refs/heads/master | <repo_name>andrewlstanley/dreamlister<file_sep>/DreamLister/ItemCell.swift
//
// ItemCell.swift
// DreamLister
//
// Created by <NAME> on 9/6/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class ItemCell: UITableViewCell {
@IBOutlet weak var thumb: UIImageView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var price: UILabel!
@IBOutlet weak var itemDescription: UILabel!
func configureCell(item: Item) {
title.text = item.title
price.text = "$\(item.price)"
itemDescription.text = item.details
thumb.image = item.toImage?.image as? UIImage
}
}
| 03f5d3d4a0b8dc08da584facb8bd90f3f8db9dfa | [
"Swift"
]
| 1 | Swift | andrewlstanley/dreamlister | a948e83820d9c63465b730c112ececec65a14b7a | c132b4a364ce26561ea9339b6fa61b85215d5757 |
refs/heads/master | <file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// yamy.cpp
#include <windows.h>
#include <tchar.h>
#include "stringtool.h"
#include "mayurc.h"
/// main
int WINAPI _tWinMain(HINSTANCE i_hInstance, HINSTANCE /* i_hPrevInstance */,
LPTSTR /* i_lpszCmdLine */, int /* i_nCmdShow */)
{
typedef BOOL (WINAPI* ISWOW64PROCESS)(HANDLE hProcess, PBOOL Wow64Process);
BOOL isWow64;
ISWOW64PROCESS pIsWow64Process;
STARTUPINFO si;
PROCESS_INFORMATION pi;
BOOL result;
tstring yamyPath;
_TCHAR exePath[GANA_MAX_PATH];
_TCHAR exeDrive[GANA_MAX_PATH];
_TCHAR exeDir[GANA_MAX_PATH];
GetModuleFileName(NULL, exePath, GANA_MAX_PATH);
_tsplitpath_s(exePath, exeDrive, GANA_MAX_PATH, exeDir, GANA_MAX_PATH, NULL, 0, NULL, 0);
yamyPath = exeDrive;
yamyPath += exeDir;
pIsWow64Process =
(ISWOW64PROCESS)::GetProcAddress(::GetModuleHandle(_T("kernel32.dll")),
"IsWow64Process");
ZeroMemory(&pi,sizeof(pi));
ZeroMemory(&si,sizeof(si));
si.cb=sizeof(si);
if (pIsWow64Process) {
result = pIsWow64Process(::GetCurrentProcess(), &isWow64);
if (result != FALSE && isWow64 == TRUE) {
yamyPath += _T("yamy64");
} else {
yamyPath += _T("yamy32");
}
} else {
yamyPath += _T("yamy32");
}
result = CreateProcess(yamyPath.c_str(), NULL, NULL, NULL, FALSE,
NORMAL_PRIORITY_CLASS, 0, NULL, &si, &pi);
if (result == FALSE) {
TCHAR buf[1024];
TCHAR text[1024];
TCHAR title[1024];
LoadString(i_hInstance, IDS_cannotInvoke,
text, sizeof(text)/sizeof(text[0]));
LoadString(i_hInstance, IDS_mayu,
title, sizeof(title)/sizeof(title[0]));
_stprintf_s(buf, sizeof(buf)/sizeof(buf[0]),
text, yamyPath, GetLastError());
MessageBox((HWND)NULL, buf, title, MB_OK | MB_ICONSTOP);
} else {
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
return 0;
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// setting.cpp
#include "keymap.h"
#include "errormessage.h"
#include "stringtool.h"
#include "setting.h"
#include <algorithm>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Action
//
tostream &operator<<(tostream &i_ost, const Action &i_action)
{
return i_action.output(i_ost);
}
//
ActionKey::ActionKey(const ModifiedKey &i_mk)
: m_modifiedKey(i_mk)
{
}
//
Action::Type ActionKey::getType() const
{
return Type_key;
}
// create clone
Action *ActionKey::clone() const
{
return new ActionKey(m_modifiedKey);
}
// stream output
tostream &ActionKey::output(tostream &i_ost) const
{
return i_ost << m_modifiedKey;
}
//
ActionKeySeq::ActionKeySeq(KeySeq *i_keySeq)
: m_keySeq(i_keySeq)
{
}
//
Action::Type ActionKeySeq::getType() const
{
return Type_keySeq;
}
// create clone
Action *ActionKeySeq::clone() const
{
return new ActionKeySeq(m_keySeq);
}
// stream output
tostream &ActionKeySeq::output(tostream &i_ost) const
{
return i_ost << _T("$") << m_keySeq->getName();
}
//
ActionFunction::ActionFunction(FunctionData *i_functionData,
Modifier i_modifier)
: m_functionData(i_functionData),
m_modifier(i_modifier)
{
}
//
ActionFunction::~ActionFunction()
{
delete m_functionData;
}
//
Action::Type ActionFunction::getType() const
{
return Type_function;
}
// create clone
Action *ActionFunction::clone() const
{
return new ActionFunction(m_functionData->clone(), m_modifier);
}
// stream output
tostream &ActionFunction::output(tostream &i_ost) const
{
return i_ost << m_modifier << m_functionData;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// KeySeq
void KeySeq::copy()
{
for (Actions::iterator i = m_actions.begin(); i != m_actions.end(); ++ i)
(*i) = (*i)->clone();
}
void KeySeq::clear()
{
for (Actions::iterator i = m_actions.begin(); i != m_actions.end(); ++ i)
delete (*i);
}
KeySeq::KeySeq(const tstringi &i_name)
: m_name(i_name),
m_mode(Modifier::Type_KEYSEQ)
{
}
KeySeq::KeySeq(const KeySeq &i_ks)
: m_actions(i_ks.m_actions),
m_name(i_ks.m_name),
m_mode(i_ks.m_mode)
{
copy();
}
KeySeq::~KeySeq()
{
clear();
}
KeySeq &KeySeq::operator=(const KeySeq &i_ks)
{
if (this != &i_ks) {
clear();
m_actions = i_ks.m_actions;
m_mode = i_ks.m_mode;
copy();
}
return *this;
}
KeySeq &KeySeq::add(const Action &i_action)
{
m_actions.push_back(i_action.clone());
return *this;
}
/// get the first modified key of this key sequence
ModifiedKey KeySeq::getFirstModifiedKey() const
{
if (0 < m_actions.size()) {
const Action *a = m_actions.front();
switch (a->getType()) {
case Action::Type_key:
return reinterpret_cast<const ActionKey *>(a)->m_modifiedKey;
case Action::Type_keySeq:
return reinterpret_cast<const ActionKeySeq *>(a)->
m_keySeq->getFirstModifiedKey();
default:
break;
}
}
return ModifiedKey(); // failed
}
// stream output
tostream &operator<<(tostream &i_ost, const KeySeq &i_ks)
{
for (KeySeq::Actions::const_iterator
i = i_ks.m_actions.begin(); i != i_ks.m_actions.end(); ++ i)
i_ost << **i << _T(" ");
return i_ost;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Keymap
Keymap::KeyAssignments &Keymap::getKeyAssignments(const ModifiedKey &i_mk)
{
ASSERT(1 <= i_mk.m_key->getScanCodesSize());
return m_hashedKeyAssignments[i_mk.m_key->getScanCodes()->m_scan %
HASHED_KEY_ASSIGNMENT_SIZE];
}
const Keymap::KeyAssignments &
Keymap::getKeyAssignments(const ModifiedKey &i_mk) const
{
ASSERT(1 <= i_mk.m_key->getScanCodesSize());
return m_hashedKeyAssignments[i_mk.m_key->getScanCodes()->m_scan %
HASHED_KEY_ASSIGNMENT_SIZE];
}
Keymap::Keymap(Type i_type,
const tstringi &i_name,
const tstringi &i_windowClass,
const tstringi &i_windowTitle,
KeySeq *i_defaultKeySeq,
Keymap *i_parentKeymap)
: m_type(i_type),
m_name(i_name),
m_defaultKeySeq(i_defaultKeySeq),
m_parentKeymap(i_parentKeymap),
m_windowClass(_T(".*")),
m_windowTitle(_T(".*"))
{
if (i_type == Type_windowAnd || i_type == Type_windowOr)
try {
tregex::flag_type f = (tregex::normal |
tregex::icase);
if (!i_windowClass.empty())
m_windowClass.assign(i_windowClass, f);
if (!i_windowTitle.empty())
m_windowTitle.assign(i_windowTitle, f);
} catch (boost::bad_expression &i_e) {
throw ErrorMessage() << i_e.what();
}
}
// add a key assignment;
void Keymap::addAssignment(const ModifiedKey &i_mk, KeySeq *i_keySeq)
{
KeyAssignments &ka = getKeyAssignments(i_mk);
for (KeyAssignments::iterator i = ka.begin(); i != ka.end(); ++ i)
if ((*i).m_modifiedKey == i_mk) {
(*i).m_keySeq = i_keySeq;
return;
}
ka.push_front(KeyAssignment(i_mk, i_keySeq));
}
// add modifier
void Keymap::addModifier(Modifier::Type i_mt, AssignOperator i_ao,
AssignMode i_am, Key *i_key)
{
if (i_ao == AO_new)
m_modAssignments[i_mt].clear();
else {
for (ModAssignments::iterator i = m_modAssignments[i_mt].begin();
i != m_modAssignments[i_mt].end(); ++ i)
if ((*i).m_key == i_key) {
(*i).m_assignOperator = i_ao;
(*i).m_assignMode = i_am;
return;
}
}
ModAssignment ma;
ma.m_assignOperator = i_ao;
ma.m_assignMode = i_am;
ma.m_key = i_key;
m_modAssignments[i_mt].push_back(ma);
}
// search
const Keymap::KeyAssignment *
Keymap::searchAssignment(const ModifiedKey &i_mk) const
{
const KeyAssignments &ka = getKeyAssignments(i_mk);
for (KeyAssignments::const_iterator i = ka.begin(); i != ka.end(); ++ i)
if ((*i).m_modifiedKey.m_key == i_mk.m_key &&
(*i).m_modifiedKey.m_modifier.doesMatch(i_mk.m_modifier))
return &(*i);
return NULL;
}
// does same window
bool Keymap::doesSameWindow(const tstringi i_className,
const tstringi &i_titleName)
{
if (m_type == Type_keymap)
return false;
tsmatch what;
if (boost::regex_search(i_className, what, m_windowClass)) {
if (m_type == Type_windowAnd)
return boost::regex_search(i_titleName, what, m_windowTitle);
else // type == Type_windowOr
return true;
} else {
if (m_type == Type_windowAnd)
return false;
else // type == Type_windowOr
return boost::regex_search(i_titleName, what, m_windowTitle);
}
}
// adjust modifier
void Keymap::adjustModifier(Keyboard &i_keyboard)
{
for (size_t i = 0; i < NUMBER_OF(m_modAssignments); ++ i) {
ModAssignments mos;
if (m_parentKeymap)
mos = m_parentKeymap->m_modAssignments[i];
else {
// set default modifiers
if (i < Modifier::Type_BASIC) {
Keyboard::Mods mods =
i_keyboard.getModifiers(static_cast<Modifier::Type>(i));
for (Keyboard::Mods::iterator j = mods.begin(); j != mods.end(); ++ j) {
ModAssignment ma;
ma.m_assignOperator = AO_add;
ma.m_assignMode = AM_normal;
ma.m_key = *j;
mos.push_back(ma);
}
}
}
// mod adjust
for (ModAssignments::iterator mai = m_modAssignments[i].begin();
mai != m_modAssignments[i].end(); ++ mai) {
ModAssignment ma = *mai;
ma.m_assignOperator = AO_new;
switch ((*mai).m_assignOperator) {
case AO_new: {
mos.clear();
mos.push_back(ma);
break;
}
case AO_add: {
mos.push_back(ma);
break;
}
case AO_sub: {
for (ModAssignments::iterator j = mos.begin();
j != mos.end(); ++ j)
if ((*j).m_key == ma.m_key) {
mos.erase(j);
break;
}
break;
}
case AO_overwrite: {
for (ModAssignments::iterator j = mos.begin();
j != mos.end(); ++ j)
(*j).m_assignMode = (*mai).m_assignMode;
break;
}
}
}
// erase redundant modifiers
for (ModAssignments::iterator j = mos.begin(); j != mos.end(); ++ j) {
ModAssignments::iterator k;
for (k = j, ++ k; k != mos.end(); ++ k)
if ((*k).m_key == (*j).m_key)
break;
if (k != mos.end()) {
k = j;
++ j;
mos.erase(k);
break;
}
}
m_modAssignments[i] = mos;
}
}
// describe
void Keymap::describe(tostream &i_ost, DescribeParam *i_dp) const
{
// Is this keymap already described ?
{
DescribeParam::DescribedKeymap::iterator
i = std::find(i_dp->m_dkeymap.begin(), i_dp->m_dkeymap.end(), this);
if (i != i_dp->m_dkeymap.end())
return; // yes!
i_dp->m_dkeymap.push_back(this);
}
switch (m_type) {
case Type_keymap:
i_ost << _T("keymap ") << m_name;
break;
case Type_windowAnd:
i_ost << _T("window ") << m_name << _T(" ");
if (m_windowTitle.str() == _T(".*"))
i_ost << _T("/") << m_windowClass.str() << _T("/");
else
i_ost << _T("( /") << m_windowClass.str() << _T("/ && /")
<< m_windowTitle.str() << _T("/ )");
break;
case Type_windowOr:
i_ost << _T("window ") << m_name << _T(" ( /")
<< m_windowClass.str() << _T("/ || /") << m_windowTitle.str()
<< _T("/ )");
break;
}
if (m_parentKeymap)
i_ost << _T(" : ") << m_parentKeymap->m_name;
i_ost << _T(" = ") << *m_defaultKeySeq << std::endl;
// describe modifiers
if (i_dp->m_doesDescribeModifiers) {
for (int t = Modifier::Type_begin; t != Modifier::Type_end; ++ t) {
Modifier::Type type = static_cast<Modifier::Type>(t);
const Keymap::ModAssignments &ma = getModAssignments(type);
if (ma.size()) {
i_ost << _T(" mod ") << type << _T("\t= ");
for (Keymap::ModAssignments::const_iterator
j = ma.begin(); j != ma.end(); ++ j) {
switch (j->m_assignMode) {
case Keymap::AM_true:
i_ost << _T("!");
break;
case Keymap::AM_oneShot:
i_ost << _T("!!");
break;
case Keymap::AM_oneShotRepeatable:
i_ost << _T("!!!");
break;
default:
break;
}
i_ost << *j->m_key << _T(" ");
}
i_ost << std::endl;
}
}
i_dp->m_doesDescribeModifiers = false;
}
typedef std::vector<KeyAssignment> SortedKeyAssignments;
SortedKeyAssignments ska;
for (size_t i = 0; i < HASHED_KEY_ASSIGNMENT_SIZE; ++ i) {
const KeyAssignments &ka = m_hashedKeyAssignments[i];
for (KeyAssignments::const_iterator j = ka.begin(); j != ka.end(); ++ j)
ska.push_back(*j);
}
std::sort(ska.begin(), ska.end());
for (SortedKeyAssignments::iterator i = ska.begin(); i != ska.end(); ++ i) {
// Is this key assignment already described ?
DescribeParam::DescribedKeys::iterator
j = std::find(i_dp->m_dk.begin(), i_dp->m_dk.end(), i->m_modifiedKey);
if (j != i_dp->m_dk.end())
continue; // yes!
// check if the key is an event
Key **e;
for (e = Event::events; *e; ++ e)
if (i->m_modifiedKey.m_key == *e)
break;
if (*e)
i_ost << _T(" event ") << *i->m_modifiedKey.m_key;
else
i_ost << _T(" key ") << i->m_modifiedKey;
i_ost << _T("\t= ") << *i->m_keySeq << std::endl;
i_dp->m_dk.push_back(i->m_modifiedKey);
}
i_ost << std::endl;
if (m_parentKeymap)
m_parentKeymap->describe(i_ost, i_dp);
}
// set default keySeq and parent keymap if default keySeq has not been set
bool Keymap::setIfNotYet(KeySeq *i_keySeq, Keymap *i_parentKeymap)
{
if (m_defaultKeySeq)
return false;
m_defaultKeySeq = i_keySeq;
m_parentKeymap = i_parentKeymap;
return true;
}
// stream output
extern tostream &operator<<(tostream &i_ost, const Keymap *i_keymap)
{
return i_ost << i_keymap->getName();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Keymaps
Keymaps::Keymaps()
{
}
// search by name
Keymap *Keymaps::searchByName(const tstringi &i_name)
{
for (KeymapList::iterator
i = m_keymapList.begin(); i != m_keymapList.end(); ++ i)
if ((*i).getName() == i_name)
return &*i;
return NULL;
}
// search window
void Keymaps::searchWindow(KeymapPtrList *o_keymapPtrList,
const tstringi &i_className,
const tstringi &i_titleName)
{
o_keymapPtrList->clear();
for (KeymapList::iterator
i = m_keymapList.begin(); i != m_keymapList.end(); ++ i)
if ((*i).doesSameWindow(i_className, i_titleName))
o_keymapPtrList->push_back(&(*i));
}
// add keymap
Keymap *Keymaps::add(const Keymap &i_keymap)
{
if (Keymap *k = searchByName(i_keymap.getName()))
return k;
m_keymapList.push_front(i_keymap);
return &m_keymapList.front();
}
// adjust modifier
void Keymaps::adjustModifier(Keyboard &i_keyboard)
{
for (KeymapList::reverse_iterator i = m_keymapList.rbegin();
i != m_keymapList.rend(); ++ i)
(*i).adjustModifier(i_keyboard);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// KeySeqs
// add a named keyseq (name can be empty)
KeySeq *KeySeqs::add(const KeySeq &i_keySeq)
{
if (!i_keySeq.getName().empty()) {
KeySeq *ks = searchByName(i_keySeq.getName());
if (ks)
return &(*ks = i_keySeq);
}
m_keySeqList.push_front(i_keySeq);
return &m_keySeqList.front();
}
// search by name
KeySeq *KeySeqs::searchByName(const tstringi &i_name)
{
for (KeySeqList::iterator
i = m_keySeqList.begin(); i != m_keySeqList.end(); ++ i)
if ((*i).getName() == i_name)
return &(*i);
return NULL;
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// function.cpp
#include "engine.h"
#include "hook.h"
#include "mayu.h"
#include "mayurc.h"
#include "misc.h"
#include "registry.h"
#include "vkeytable.h"
#include "windowstool.h"
#include <algorithm>
#include <process.h>
#define FUNCTION_DATA
#include "functions.h"
#undef FUNCTION_DATA
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// TypeTable
template <class T> class TypeTable
{
public:
T m_type;
const _TCHAR *m_name;
};
template <class T> static inline
bool getTypeName(tstring *o_name, T i_type,
const TypeTable<T> *i_table, size_t i_n)
{
for (size_t i = 0; i < i_n; ++ i)
if (i_table[i].m_type == i_type) {
*o_name = i_table[i].m_name;
return true;
}
return false;
}
template <class T> static inline
bool getTypeValue(T *o_type, const tstringi &i_name,
const TypeTable<T> *i_table, size_t i_n)
{
for (size_t i = 0; i < i_n; ++ i)
if (i_table[i].m_name == i_name) {
*o_type = i_table[i].m_type;
return true;
}
return false;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// VKey
// stream output
tostream &operator<<(tostream &i_ost, VKey i_data)
{
if (i_data & VKey_extended)
i_ost << _T("E-");
if (i_data & VKey_released)
i_ost << _T("U-");
if (i_data & VKey_pressed)
i_ost << _T("D-");
u_int8 code = i_data & ~(VKey_extended | VKey_released | VKey_pressed);
const VKeyTable *vkt;
for (vkt = g_vkeyTable; vkt->m_name; ++ vkt)
if (vkt->m_code == code)
break;
if (vkt->m_name)
i_ost << vkt->m_name;
else
i_ost << _T("0x") << std::hex << code << std::dec;
return i_ost;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ToWindowType
// ToWindowType table
typedef TypeTable<ToWindowType> TypeTable_ToWindowType;
static const TypeTable_ToWindowType g_toWindowTypeTable[] = {
{ ToWindowType_toOverlappedWindow, _T("toOverlappedWindow") },
{ ToWindowType_toMainWindow, _T("toMainWindow") },
{ ToWindowType_toItself, _T("toItself") },
{ ToWindowType_toParentWindow, _T("toParentWindow") },
};
// stream output
tostream &operator<<(tostream &i_ost, ToWindowType i_data)
{
tstring name;
if (getTypeName(&name, i_data,
g_toWindowTypeTable, NUMBER_OF(g_toWindowTypeTable)))
i_ost << name;
else
i_ost << static_cast<int>(i_data);
return i_ost;
}
// get value of ToWindowType
bool getTypeValue(ToWindowType *o_type, const tstring &i_name)
{
return getTypeValue(o_type, i_name,
g_toWindowTypeTable, NUMBER_OF(g_toWindowTypeTable));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// GravityType
// GravityType table
typedef TypeTable<GravityType> TypeTable_GravityType;
static const TypeTable_GravityType g_gravityTypeTable[] = {
{ GravityType_C, _T("C") },
{ GravityType_N, _T("N") },
{ GravityType_E, _T("E") },
{ GravityType_W, _T("W") },
{ GravityType_S, _T("S") },
{ GravityType_NW, _T("NW") },
{ GravityType_NW, _T("WN") },
{ GravityType_NE, _T("NE") },
{ GravityType_NE, _T("EN") },
{ GravityType_SW, _T("SW") },
{ GravityType_SW, _T("WS") },
{ GravityType_SE, _T("SE") },
{ GravityType_SE, _T("ES") },
};
// stream output
tostream &operator<<(tostream &i_ost, GravityType i_data)
{
tstring name;
if (getTypeName(&name, i_data,
g_gravityTypeTable, NUMBER_OF(g_gravityTypeTable)))
i_ost << name;
else
i_ost << _T("(GravityType internal error)");
return i_ost;
}
// get value of GravityType
bool getTypeValue(GravityType *o_type, const tstring &i_name)
{
return getTypeValue(o_type, i_name,
g_gravityTypeTable, NUMBER_OF(g_gravityTypeTable));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// MouseHookType
// MouseHookType table
typedef TypeTable<MouseHookType> TypeTable_MouseHookType;
static const TypeTable_MouseHookType g_mouseHookTypeTable[] = {
{ MouseHookType_None, _T("None") },
{ MouseHookType_Wheel, _T("Wheel") },
{ MouseHookType_WindowMove, _T("WindowMove") },
};
// stream output
tostream &operator<<(tostream &i_ost, MouseHookType i_data)
{
tstring name;
if (getTypeName(&name, i_data,
g_mouseHookTypeTable, NUMBER_OF(g_mouseHookTypeTable)))
i_ost << name;
else
i_ost << _T("(MouseHookType internal error)");
return i_ost;
}
// get value of MouseHookType
bool getTypeValue(MouseHookType *o_type, const tstring &i_name)
{
return getTypeValue(o_type, i_name, g_mouseHookTypeTable,
NUMBER_OF(g_mouseHookTypeTable));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// MayuDialogType
// ModifierLockType table
typedef TypeTable<MayuDialogType> TypeTable_MayuDialogType;
static const TypeTable_MayuDialogType g_mayuDialogTypeTable[] = {
{ MayuDialogType_investigate, _T("investigate") },
{ MayuDialogType_log, _T("log") },
};
// stream output
tostream &operator<<(tostream &i_ost, MayuDialogType i_data)
{
tstring name;
if (getTypeName(&name, i_data,
g_mayuDialogTypeTable, NUMBER_OF(g_mayuDialogTypeTable)))
i_ost << name;
else
i_ost << _T("(MayuDialogType internal error)");
return i_ost;
}
// get value of MayuDialogType
bool getTypeValue(MayuDialogType *o_type, const tstring &i_name)
{
return getTypeValue(o_type, i_name, g_mayuDialogTypeTable,
NUMBER_OF(g_mayuDialogTypeTable));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ToggleType
// ToggleType table
typedef TypeTable<ToggleType> TypeTable_ToggleType;
static const TypeTable_ToggleType g_toggleType[] = {
{ ToggleType_toggle, _T("toggle") },
{ ToggleType_off, _T("off") },
{ ToggleType_off, _T("false") },
{ ToggleType_off, _T("released") },
{ ToggleType_on, _T("on") },
{ ToggleType_on, _T("true") },
{ ToggleType_on, _T("pressed") },
};
// stream output
tostream &operator<<(tostream &i_ost, ToggleType i_data)
{
tstring name;
if (getTypeName(&name, i_data, g_toggleType, NUMBER_OF(g_toggleType)))
i_ost << name;
else
i_ost << _T("(ToggleType internal error)");
return i_ost;
}
// get value of ToggleType
bool getTypeValue(ToggleType *o_type, const tstring &i_name)
{
return getTypeValue(o_type, i_name, g_toggleType,
NUMBER_OF(g_toggleType));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ModifierLockType
// ModifierLockType table
typedef TypeTable<ModifierLockType> TypeTable_ModifierLockType;
static const TypeTable_ModifierLockType g_modifierLockTypeTable[] = {
{ ModifierLockType_Lock0, _T("lock0") },
{ ModifierLockType_Lock1, _T("lock1") },
{ ModifierLockType_Lock2, _T("lock2") },
{ ModifierLockType_Lock3, _T("lock3") },
{ ModifierLockType_Lock4, _T("lock4") },
{ ModifierLockType_Lock5, _T("lock5") },
{ ModifierLockType_Lock6, _T("lock6") },
{ ModifierLockType_Lock7, _T("lock7") },
{ ModifierLockType_Lock8, _T("lock8") },
{ ModifierLockType_Lock9, _T("lock9") },
};
// stream output
tostream &operator<<(tostream &i_ost, ModifierLockType i_data)
{
tstring name;
if (getTypeName(&name, i_data,
g_modifierLockTypeTable, NUMBER_OF(g_modifierLockTypeTable)))
i_ost << name;
else
i_ost << _T("(ModifierLockType internal error)");
return i_ost;
}
// get value of ModifierLockType
bool getTypeValue(ModifierLockType *o_type, const tstring &i_name)
{
return getTypeValue(o_type, i_name, g_modifierLockTypeTable,
NUMBER_OF(g_modifierLockTypeTable));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ShowCommandType
// ShowCommandType table
typedef TypeTable<ShowCommandType> TypeTable_ShowCommandType;
static const TypeTable_ShowCommandType g_showCommandTypeTable[] = {
{ ShowCommandType_hide, _T("hide") },
{ ShowCommandType_maximize, _T("maximize") },
{ ShowCommandType_minimize, _T("minimize") },
{ ShowCommandType_restore, _T("restore") },
{ ShowCommandType_show, _T("show") },
{ ShowCommandType_showDefault, _T("showDefault") },
{ ShowCommandType_showMaximized, _T("showMaximized") },
{ ShowCommandType_showMinimized, _T("showMinimized") },
{ ShowCommandType_showMinNoActive, _T("showMinNoActive") },
{ ShowCommandType_showNA, _T("showNA") },
{ ShowCommandType_showNoActivate, _T("showNoActivate") },
{ ShowCommandType_showNormal, _T("showNormal") },
};
// stream output
tostream &operator<<(tostream &i_ost, ShowCommandType i_data)
{
tstring name;
if (getTypeName(&name, i_data,
g_showCommandTypeTable, NUMBER_OF(g_showCommandTypeTable)))
i_ost << name;
else
i_ost << _T("(ShowCommandType internal error)");
return i_ost;
}
// get value of ShowCommandType
bool getTypeValue(ShowCommandType *o_type, const tstring &i_name)
{
return getTypeValue(o_type, i_name, g_showCommandTypeTable,
NUMBER_OF(g_showCommandTypeTable));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// TargetWindowType
// ModifierLockType table
typedef TypeTable<TargetWindowType> TypeTable_TargetWindowType;
static const TypeTable_TargetWindowType g_targetWindowType[] = {
{ TargetWindowType_overlapped, _T("overlapped") },
{ TargetWindowType_mdi, _T("mdi") },
};
// stream output
tostream &operator<<(tostream &i_ost, TargetWindowType i_data)
{
tstring name;
if (getTypeName(&name, i_data,
g_targetWindowType, NUMBER_OF(g_targetWindowType)))
i_ost << name;
else
i_ost << _T("(TargetWindowType internal error)");
return i_ost;
}
// get value of TargetWindowType
bool getTypeValue(TargetWindowType *o_type, const tstring &i_name)
{
return getTypeValue(o_type, i_name, g_targetWindowType,
NUMBER_OF(g_targetWindowType));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// BooleanType
// BooleanType table
typedef TypeTable<BooleanType> TypeTable_BooleanType;
static const TypeTable_BooleanType g_booleanType[] = {
{ BooleanType_false, _T("false") },
{ BooleanType_true, _T("true") },
};
// stream output
tostream &operator<<(tostream &i_ost, BooleanType i_data)
{
tstring name;
if (getTypeName(&name, i_data, g_booleanType, NUMBER_OF(g_booleanType)))
i_ost << name;
else
i_ost << _T("(BooleanType internal error)");
return i_ost;
}
// get value of BooleanType
bool getTypeValue(BooleanType *o_type, const tstring &i_name)
{
return getTypeValue(o_type, i_name, g_booleanType,
NUMBER_OF(g_booleanType));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// LogicalOperatorType
// LogicalOperatorType table
typedef TypeTable<LogicalOperatorType> TypeTable_LogicalOperatorType;
static const TypeTable_LogicalOperatorType g_logicalOperatorType[] = {
{ LogicalOperatorType_or, _T("||") },
{ LogicalOperatorType_and, _T("&&") },
};
// stream output
tostream &operator<<(tostream &i_ost, LogicalOperatorType i_data)
{
tstring name;
if (getTypeName(&name, i_data, g_logicalOperatorType,
NUMBER_OF(g_logicalOperatorType)))
i_ost << name;
else
i_ost << _T("(LogicalOperatorType internal error)");
return i_ost;
}
// get value of LogicalOperatorType
bool getTypeValue(LogicalOperatorType *o_type, const tstring &i_name)
{
return getTypeValue(o_type, i_name, g_logicalOperatorType,
NUMBER_OF(g_logicalOperatorType));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// WindowMonitorFromType
// WindowMonitorFromType table
typedef TypeTable<WindowMonitorFromType> TypeTable_WindowMonitorFromType;
static const TypeTable_WindowMonitorFromType g_windowMonitorFromType[] = {
{ WindowMonitorFromType_primary, _T("primary") },
{ WindowMonitorFromType_current, _T("current") },
};
// stream output
tostream &operator<<(tostream &i_ost, WindowMonitorFromType i_data)
{
tstring name;
if (getTypeName(&name, i_data, g_windowMonitorFromType,
NUMBER_OF(g_windowMonitorFromType)))
i_ost << name;
else
i_ost << _T("(WindowMonitorFromType internal error)");
return i_ost;
}
// get value of WindowMonitorFromType
bool getTypeValue(WindowMonitorFromType *o_type, const tstring &i_name)
{
return getTypeValue(o_type, i_name, g_windowMonitorFromType,
NUMBER_OF(g_windowMonitorFromType));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// std::list<tstringq>
/// stream output
tostream &operator<<(tostream &i_ost, const std::list<tstringq> &i_data)
{
for (std::list<tstringq>::const_iterator
i = i_data.begin(); i != i_data.end(); ++ i) {
i_ost << *i << _T(", ");
}
return i_ost;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FunctionData
//
FunctionData::~FunctionData()
{
}
// stream output
tostream &operator<<(tostream &i_ost, const FunctionData *i_data)
{
return i_data->output(i_ost);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FunctionCreator
///
class FunctionCreator
{
public:
typedef FunctionData *(*Creator)(); ///
public:
const _TCHAR *m_name; /// function name
Creator m_creator; /// function data creator
};
// create function
FunctionData *createFunctionData(const tstring &i_name)
{
static
#define FUNCTION_CREATOR
#include "functions.h"
#undef FUNCTION_CREATOR
;
for (size_t i = 0; i != NUMBER_OF(functionCreators); ++ i)
if (i_name == functionCreators[i].m_name)
return functionCreators[i].m_creator();
return NULL;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// misc. functions
//
bool getSuitableWindow(FunctionParam *i_param, HWND *o_hwnd)
{
if (!i_param->m_isPressed)
return false;
*o_hwnd = getToplevelWindow(i_param->m_hwnd, NULL);
if (!*o_hwnd)
return false;
return true;
}
//
bool getSuitableMdiWindow(FunctionParam *i_param, HWND *o_hwnd,
TargetWindowType *io_twt,
RECT *o_rcWindow = NULL, RECT *o_rcParent = NULL)
{
if (!i_param->m_isPressed)
return false;
bool isMdi = *io_twt == TargetWindowType_mdi;
*o_hwnd = getToplevelWindow(i_param->m_hwnd, &isMdi);
*io_twt = isMdi ? TargetWindowType_mdi : TargetWindowType_overlapped;
if (!*o_hwnd)
return false;
switch (*io_twt) {
case TargetWindowType_overlapped:
if (o_rcWindow)
GetWindowRect(*o_hwnd, o_rcWindow);
if (o_rcParent) {
HMONITOR hm = monitorFromWindow(i_param->m_hwnd,
MONITOR_DEFAULTTONEAREST);
MONITORINFO mi;
mi.cbSize = sizeof(mi);
getMonitorInfo(hm, &mi);
*o_rcParent = mi.rcWork;
}
break;
case TargetWindowType_mdi:
if (o_rcWindow)
getChildWindowRect(*o_hwnd, o_rcWindow);
if (o_rcParent)
GetClientRect(GetParent(*o_hwnd), o_rcParent);
break;
}
return true;
}
// get clipboard text (you must call closeClopboard())
static const _TCHAR *getTextFromClipboard(HGLOBAL *o_hdata)
{
*o_hdata = NULL;
if (!OpenClipboard(NULL))
return NULL;
#ifdef UNICODE
*o_hdata = GetClipboardData(CF_UNICODETEXT);
#else
*o_hdata = GetClipboardData(CF_TEXT);
#endif
if (!*o_hdata)
return NULL;
_TCHAR *data = reinterpret_cast<_TCHAR *>(GlobalLock(*o_hdata));
if (!data)
return NULL;
return data;
}
// close clipboard that opend by getTextFromClipboard()
static void closeClipboard(HGLOBAL i_hdata, HGLOBAL i_hdataNew = NULL)
{
if (i_hdata)
GlobalUnlock(i_hdata);
if (i_hdataNew) {
EmptyClipboard();
#ifdef UNICODE
SetClipboardData(CF_UNICODETEXT, i_hdataNew);
#else
SetClipboardData(CF_TEXT, i_hdataNew);
#endif
}
CloseClipboard();
}
// EmacsEditKillLineFunc.
// clear the contents of the clopboard
// at that time, confirm if it is the result of the previous kill-line
void Engine::EmacsEditKillLine::func()
{
if (!m_buf.empty()) {
HGLOBAL g;
const _TCHAR *text = getTextFromClipboard(&g);
if (text == NULL || m_buf != text)
reset();
closeClipboard(g);
}
if (OpenClipboard(NULL)) {
EmptyClipboard();
CloseClipboard();
}
}
/** if the text of the clipboard is
@doc
<pre>
1: EDIT Control (at EOL C-K): "" => buf + "\r\n", Delete
0: EDIT Control (other C-K): "(.+)" => buf + "\1"
0: IE FORM TEXTAREA (at EOL C-K): "\r\n" => buf + "\r\n"
2: IE FORM TEXTAREA (other C-K): "(.+)\r\n" => buf + "\1", Return Left
^retval
</pre>
*/
HGLOBAL Engine::EmacsEditKillLine::makeNewKillLineBuf(
const _TCHAR *i_data, int *o_retval)
{
size_t len = m_buf.size();
len += _tcslen(i_data) + 3;
HGLOBAL hdata = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
len * sizeof(_TCHAR));
if (!hdata)
return NULL;
_TCHAR *dataNew = reinterpret_cast<_TCHAR *>(GlobalLock(hdata));
*dataNew = _T('\0');
if (!m_buf.empty())
_tcscpy(dataNew, m_buf.c_str());
len = _tcslen(i_data);
if (3 <= len &&
i_data[len - 2] == _T('\r') && i_data[len - 1] == _T('\n')) {
_tcscat(dataNew, i_data);
len = _tcslen(dataNew);
dataNew[len - 2] = _T('\0'); // chomp
*o_retval = 2;
} else if (len == 0) {
_tcscat(dataNew, _T("\r\n"));
*o_retval = 1;
} else {
_tcscat(dataNew, i_data);
*o_retval = 0;
}
m_buf = dataNew;
GlobalUnlock(hdata);
return hdata;
}
// EmacsEditKillLinePred
int Engine::EmacsEditKillLine::pred()
{
HGLOBAL g;
const _TCHAR *text = getTextFromClipboard(&g);
int retval;
HGLOBAL hdata = makeNewKillLineBuf(text ? text : _T(""), &retval);
closeClipboard(g, hdata);
return retval;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// functions
// send a default key to Windows
void Engine::funcDefault(FunctionParam *i_param)
{
{
Acquire a(&m_log, 1);
m_log << std::endl;
i_param->m_doesNeedEndl = false;
}
if (i_param->m_isPressed)
generateModifierEvents(i_param->m_c.m_mkey.m_modifier);
generateKeyEvent(i_param->m_c.m_mkey.m_key, i_param->m_isPressed, true);
}
// use a corresponding key of a parent keymap
void Engine::funcKeymapParent(FunctionParam *i_param)
{
Current c(i_param->m_c);
c.m_keymap = c.m_keymap->getParentKeymap();
if (!c.m_keymap) {
funcDefault(i_param);
return;
}
{
Acquire a(&m_log, 1);
m_log << _T("(") << c.m_keymap->getName() << _T(")") << std::endl;
}
i_param->m_doesNeedEndl = false;
generateKeyboardEvents(c);
}
// use a corresponding key of a current window
void Engine::funcKeymapWindow(FunctionParam *i_param)
{
Current c(i_param->m_c);
c.m_keymap = m_currentFocusOfThread->m_keymaps.front();
c.m_i = m_currentFocusOfThread->m_keymaps.begin();
generateKeyboardEvents(c);
}
// use a corresponding key of the previous prefixed keymap
void Engine::funcKeymapPrevPrefix(FunctionParam *i_param, int i_previous)
{
Current c(i_param->m_c);
if (0 < i_previous && 0 <= m_keymapPrefixHistory.size() - i_previous) {
int n = i_previous - 1;
KeymapPtrList::reverse_iterator i = m_keymapPrefixHistory.rbegin();
while (0 < n && i != m_keymapPrefixHistory.rend())
--n, ++i;
c.m_keymap = *i;
generateKeyboardEvents(c);
}
}
// use a corresponding key of an other window class, or use a default key
void Engine::funcOtherWindowClass(FunctionParam *i_param)
{
Current c(i_param->m_c);
++ c.m_i;
if (c.m_i == m_currentFocusOfThread->m_keymaps.end()) {
funcDefault(i_param);
return;
}
c.m_keymap = *c.m_i;
{
Acquire a(&m_log, 1);
m_log << _T("(") << c.m_keymap->getName() << _T(")") << std::endl;
}
i_param->m_doesNeedEndl = false;
generateKeyboardEvents(c);
}
// prefix key
void Engine::funcPrefix(FunctionParam *i_param, const Keymap *i_keymap,
BooleanType i_doesIgnoreModifiers)
{
if (!i_param->m_isPressed)
return;
setCurrentKeymap(i_keymap, true);
// generate prefixed event
generateEvents(i_param->m_c, m_currentKeymap, &Event::prefixed);
m_isPrefix = true;
m_doesEditNextModifier = false;
m_doesIgnoreModifierForPrefix = !!i_doesIgnoreModifiers;
{
Acquire a(&m_log, 1);
m_log << _T("(") << i_keymap->getName() << _T(", ")
<< (i_doesIgnoreModifiers ? _T("true") : _T("false")) << _T(")");
}
}
// other keymap's key
void Engine::funcKeymap(FunctionParam *i_param, const Keymap *i_keymap)
{
Current c(i_param->m_c);
c.m_keymap = i_keymap;
{
Acquire a(&m_log, 1);
m_log << _T("(") << c.m_keymap->getName() << _T(")") << std::endl;
i_param->m_doesNeedEndl = false;
}
generateKeyboardEvents(c);
}
// sync
void Engine::funcSync(FunctionParam *i_param)
{
if (i_param->m_isPressed)
generateModifierEvents(i_param->m_af->m_modifier);
if (!i_param->m_isPressed || m_currentFocusOfThread->m_isConsole)
return;
Key *sync = m_setting->m_keyboard.getSyncKey();
if (sync->getScanCodesSize() == 0)
return;
const ScanCode *sc = sync->getScanCodes();
// set variables exported from mayu.dll
g_hookData->m_syncKey = sc->m_scan;
g_hookData->m_syncKeyIsExtended = !!(sc->m_flags & ScanCode::E0E1);
m_isSynchronizing = true;
generateKeyEvent(sync, false, false);
m_cs.release();
DWORD r = WaitForSingleObject(m_eSync, 5000);
if (r == WAIT_TIMEOUT) {
Acquire a(&m_log, 0);
m_log << _T(" *FAILED*") << std::endl;
}
m_cs.acquire();
m_isSynchronizing = false;
}
// toggle lock
void Engine::funcToggle(FunctionParam *i_param, ModifierLockType i_lock,
ToggleType i_toggle)
{
if (i_param->m_isPressed) // ignore PRESS
return;
Modifier::Type mt = static_cast<Modifier::Type>(i_lock);
switch (i_toggle) {
case ToggleType_toggle:
m_currentLock.press(mt, !m_currentLock.isPressed(mt));
break;
case ToggleType_off:
m_currentLock.press(mt, false);
break;
case ToggleType_on:
m_currentLock.press(mt, true);
break;
}
}
// edit next user input key's modifier
void Engine::funcEditNextModifier(FunctionParam *i_param,
const Modifier &i_modifier)
{
if (!i_param->m_isPressed)
return;
m_isPrefix = true;
m_doesEditNextModifier = true;
m_doesIgnoreModifierForPrefix = true;
m_modifierForNextKey = i_modifier;
}
// variable
void Engine::funcVariable(FunctionParam *i_param, int i_mag, int i_inc)
{
if (!i_param->m_isPressed)
return;
m_variable *= i_mag;
m_variable += i_inc;
}
// repeat N times
void Engine::funcRepeat(FunctionParam *i_param, const KeySeq *i_keySeq,
int i_max)
{
if (i_param->m_isPressed) {
int end = MIN(m_variable, i_max);
for (int i = 0; i < end - 1; ++ i)
generateKeySeqEvents(i_param->m_c, i_keySeq, Part_all);
if (0 < end)
generateKeySeqEvents(i_param->m_c, i_keySeq, Part_down);
} else
generateKeySeqEvents(i_param->m_c, i_keySeq, Part_up);
}
// undefined (bell)
void Engine::funcUndefined(FunctionParam *i_param)
{
if (!i_param->m_isPressed)
return;
MessageBeep(MB_OK);
}
// ignore
void Engine::funcIgnore(FunctionParam *)
{
// do nothing
}
// post message
void Engine::funcPostMessage(FunctionParam *i_param, ToWindowType i_window,
UINT i_message, WPARAM i_wParam, LPARAM i_lParam)
{
if (!i_param->m_isPressed)
return;
int window = static_cast<int>(i_window);
HWND hwnd = i_param->m_hwnd;
if (0 < window) {
for (int i = 0; i < window; ++ i)
hwnd = GetParent(hwnd);
} else if (window == ToWindowType_toMainWindow) {
while (true) {
HWND p = GetParent(hwnd);
if (!p)
break;
hwnd = p;
}
} else if (window == ToWindowType_toOverlappedWindow) {
while (hwnd) {
#ifdef MAYU64
LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE);
#else
LONG style = GetWindowLong(hwnd, GWL_STYLE);
#endif
if ((style & WS_CHILD) == 0)
break;
hwnd = GetParent(hwnd);
}
}
if (hwnd)
PostMessage(hwnd, i_message, i_wParam, i_lParam);
}
// ShellExecute
void Engine::funcShellExecute(FunctionParam *i_param,
const StrExprArg &/*i_operation*/,
const StrExprArg &/*i_file*/,
const StrExprArg &/*i_parameters*/,
const StrExprArg &/*i_directory*/,
ShowCommandType /*i_showCommand*/)
{
if (!i_param->m_isPressed)
return;
m_afShellExecute = i_param->m_af;
PostMessage(m_hwndAssocWindow,
WM_APP_engineNotify, EngineNotify_shellExecute, 0);
}
// shell execute
void Engine::shellExecute()
{
Acquire a(&m_cs);
FunctionData_ShellExecute *fd =
reinterpret_cast<FunctionData_ShellExecute *>(
m_afShellExecute->m_functionData);
int r = (int)ShellExecute(
NULL,
fd->m_operation.eval().empty() ? _T("open") : fd->m_operation.eval().c_str(),
fd->m_file.eval().empty() ? NULL : fd->m_file.eval().c_str(),
fd->m_parameters.eval().empty() ? NULL : fd->m_parameters.eval().c_str(),
fd->m_directory.eval().empty() ? NULL : fd->m_directory.eval().c_str(),
fd->m_showCommand);
if (32 < r)
return; // success
typedef TypeTable<int> ErrorTable;
static const ErrorTable errorTable[] = {
{ 0, _T("The operating system is out of memory or resources.") },
{ ERROR_FILE_NOT_FOUND, _T("The specified file was not found.") },
{ ERROR_PATH_NOT_FOUND, _T("The specified path was not found.") },
{ ERROR_BAD_FORMAT, _T("The .exe file is invalid ")
_T("(non-Win32R .exe or error in .exe image).") },
{ SE_ERR_ACCESSDENIED,
_T("The operating system denied access to the specified file.") },
{ SE_ERR_ASSOCINCOMPLETE,
_T("The file name association is incomplete or invalid.") },
{ SE_ERR_DDEBUSY,
_T("The DDE transaction could not be completed ")
_T("because other DDE transactions were being processed. ") },
{ SE_ERR_DDEFAIL, _T("The DDE transaction failed.") },
{ SE_ERR_DDETIMEOUT, _T("The DDE transaction could not be completed ")
_T("because the request timed out.") },
{ SE_ERR_DLLNOTFOUND,
_T("The specified dynamic-link library was not found.") },
{ SE_ERR_FNF, _T("The specified file was not found.") },
{ SE_ERR_NOASSOC, _T("There is no application associated ")
_T("with the given file name extension.") },
{ SE_ERR_OOM,
_T("There was not enough memory to complete the operation.") },
{ SE_ERR_PNF, _T("The specified path was not found.") },
{ SE_ERR_SHARE, _T("A sharing violation occurred.") },
};
tstring errorMessage(_T("Unknown error."));
getTypeName(&errorMessage, r, errorTable, NUMBER_OF(errorTable));
Acquire b(&m_log, 0);
m_log << _T("error: ") << fd << _T(": ") << errorMessage << std::endl;
}
struct EnumWindowsForSetForegroundWindowParam {
const FunctionData_SetForegroundWindow *m_fd;
HWND m_hwnd;
public:
EnumWindowsForSetForegroundWindowParam(
const FunctionData_SetForegroundWindow *i_fd)
: m_fd(i_fd),
m_hwnd(NULL) {
}
};
/// enum windows for SetForegroundWindow
static BOOL CALLBACK enumWindowsForSetForegroundWindow(
HWND i_hwnd, LPARAM i_lParam)
{
EnumWindowsForSetForegroundWindowParam &ep =
*reinterpret_cast<EnumWindowsForSetForegroundWindowParam *>(i_lParam);
_TCHAR name[GANA_MAX_ATOM_LENGTH];
if (!GetClassName(i_hwnd, name, NUMBER_OF(name)))
return TRUE;
tsmatch what;
if (!boost::regex_search(tstring(name), what, ep.m_fd->m_windowClassName))
if (ep.m_fd->m_logicalOp == LogicalOperatorType_and)
return TRUE; // match failed
if (ep.m_fd->m_logicalOp == LogicalOperatorType_and) {
if (GetWindowText(i_hwnd, name, NUMBER_OF(name)) == 0)
name[0] = _T('\0');
if (!boost::regex_search(tstring(name), what,
ep.m_fd->m_windowTitleName))
return TRUE; // match failed
}
ep.m_hwnd = i_hwnd;
return FALSE;
}
/// SetForegroundWindow
void Engine::funcSetForegroundWindow(FunctionParam *i_param, const tregex &,
LogicalOperatorType , const tregex &)
{
if (!i_param->m_isPressed)
return;
EnumWindowsForSetForegroundWindowParam
ep(static_cast<const FunctionData_SetForegroundWindow *>(
i_param->m_af->m_functionData));
EnumWindows(enumWindowsForSetForegroundWindow,
reinterpret_cast<LPARAM>(&ep));
if (ep.m_hwnd)
PostMessage(m_hwndAssocWindow,
WM_APP_engineNotify, EngineNotify_setForegroundWindow,
reinterpret_cast<LPARAM>(ep.m_hwnd));
}
// load setting
void Engine::funcLoadSetting(FunctionParam *i_param, const StrExprArg &i_name)
{
if (!i_param->m_isPressed)
return;
if (!i_name.eval().empty()) {
// set MAYU_REGISTRY_ROOT\.mayuIndex which name is same with i_name
Registry reg(MAYU_REGISTRY_ROOT);
tregex split(_T("^([^;]*);([^;]*);(.*)$"));
tstringi dot_mayu;
for (size_t i = 0; i < MAX_MAYU_REGISTRY_ENTRIES; ++ i) {
_TCHAR buf[100];
_sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), i);
if (!reg.read(buf, &dot_mayu))
break;
tsmatch what;
if (boost::regex_match(dot_mayu, what, split) &&
what.str(1) == i_name.eval()) {
reg.write(_T(".mayuIndex"), i);
goto success;
}
}
{
Acquire a(&m_log, 0);
m_log << _T("unknown setting name: ") << i_name;
}
return;
success:
;
}
PostMessage(m_hwndAssocWindow,
WM_APP_engineNotify, EngineNotify_loadSetting, 0);
}
// virtual key
void Engine::funcVK(FunctionParam *i_param, VKey i_vkey)
{
long key = static_cast<long>(i_vkey);
BYTE vkey = static_cast<BYTE>(i_vkey);
bool isExtended = !!(key & VKey_extended);
bool isUp = !i_param->m_isPressed && !!(key & VKey_released);
bool isDown = i_param->m_isPressed && !!(key & VKey_pressed);
if (vkey == VK_LBUTTON && isDown)
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
else if (vkey == VK_LBUTTON && isUp)
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
else if (vkey == VK_MBUTTON && isDown)
mouse_event(MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0, 0);
else if (vkey == VK_MBUTTON && isUp)
mouse_event(MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
else if (vkey == VK_RBUTTON && isDown)
mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
else if (vkey == VK_RBUTTON && isUp)
mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
else if (vkey == VK_XBUTTON1 && isDown)
mouse_event(MOUSEEVENTF_XDOWN, 0, 0, XBUTTON1, 0);
else if (vkey == VK_XBUTTON1 && isUp)
mouse_event(MOUSEEVENTF_XUP, 0, 0, XBUTTON1, 0);
else if (vkey == VK_XBUTTON2 && isDown)
mouse_event(MOUSEEVENTF_XDOWN, 0, 0, XBUTTON2, 0);
else if (vkey == VK_XBUTTON2 && isUp)
mouse_event(MOUSEEVENTF_XUP, 0, 0, XBUTTON2, 0);
else if (isUp || isDown)
keybd_event(vkey,
static_cast<BYTE>(MapVirtualKey(vkey, 0)),
(isExtended ? KEYEVENTF_EXTENDEDKEY : 0) |
(i_param->m_isPressed ? 0 : KEYEVENTF_KEYUP), 0);
}
// wait
void Engine::funcWait(FunctionParam *i_param, int i_milliSecond)
{
if (!i_param->m_isPressed)
return;
if (i_milliSecond < 0 || 5000 < i_milliSecond) // too long wait
return;
m_isSynchronizing = true;
m_cs.release();
Sleep(i_milliSecond);
m_cs.acquire();
m_isSynchronizing = false;
}
// investigate WM_COMMAND, WM_SYSCOMMAND
void Engine::funcInvestigateCommand(FunctionParam *i_param)
{
if (!i_param->m_isPressed)
return;
Acquire a(&m_log, 0);
g_hookData->m_doesNotifyCommand = !g_hookData->m_doesNotifyCommand;
if (g_hookData->m_doesNotifyCommand)
m_log << _T(" begin") << std::endl;
else
m_log << _T(" end") << std::endl;
}
// show mayu dialog box
void Engine::funcMayuDialog(FunctionParam *i_param, MayuDialogType i_dialog,
ShowCommandType i_showCommand)
{
if (!i_param->m_isPressed)
return;
PostMessage(getAssociatedWndow(), WM_APP_engineNotify, EngineNotify_showDlg,
static_cast<LPARAM>(i_dialog) |
static_cast<LPARAM>(i_showCommand));
}
// describe bindings
void Engine::funcDescribeBindings(FunctionParam *i_param)
{
if (!i_param->m_isPressed)
return;
{
Acquire a(&m_log, 1);
m_log << std::endl;
}
describeBindings();
}
// show help message
void Engine::funcHelpMessage(FunctionParam *i_param, const StrExprArg &i_title,
const StrExprArg &i_message)
{
if (!i_param->m_isPressed)
return;
m_helpTitle = i_title.eval();
m_helpMessage = i_message.eval();
bool doesShow = !(i_title.eval().size() == 0 && i_message.eval().size() == 0);
PostMessage(getAssociatedWndow(), WM_APP_engineNotify,
EngineNotify_helpMessage, doesShow);
}
// show variable
void Engine::funcHelpVariable(FunctionParam *i_param, const StrExprArg &i_title)
{
if (!i_param->m_isPressed)
return;
_TCHAR buf[20];
_sntprintf(buf, NUMBER_OF(buf), _T("%d"), m_variable);
m_helpTitle = i_title.eval();
m_helpMessage = buf;
PostMessage(getAssociatedWndow(), WM_APP_engineNotify,
EngineNotify_helpMessage, true);
}
// raise window
void Engine::funcWindowRaise(FunctionParam *i_param,
TargetWindowType i_twt)
{
HWND hwnd;
if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt))
return;
SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0,
SWP_ASYNCWINDOWPOS | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOSIZE);
}
// lower window
void Engine::funcWindowLower(FunctionParam *i_param, TargetWindowType i_twt)
{
HWND hwnd;
if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt))
return;
SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0,
SWP_ASYNCWINDOWPOS | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOSIZE);
}
// minimize window
void Engine::funcWindowMinimize(FunctionParam *i_param, TargetWindowType i_twt)
{
HWND hwnd;
if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt))
return;
PostMessage(hwnd, WM_SYSCOMMAND,
IsIconic(hwnd) ? SC_RESTORE : SC_MINIMIZE, 0);
}
// maximize window
void Engine::funcWindowMaximize(FunctionParam *i_param, TargetWindowType i_twt)
{
HWND hwnd;
if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt))
return;
PostMessage(hwnd, WM_SYSCOMMAND,
IsZoomed(hwnd) ? SC_RESTORE : SC_MAXIMIZE, 0);
}
// maximize horizontally or virtically
void Engine::funcWindowHVMaximize(FunctionParam *i_param,
BooleanType i_isHorizontal,
TargetWindowType i_twt)
{
HWND hwnd;
RECT rc, rcd;
if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt, &rc, &rcd))
return;
// erase non window
while (true) {
WindowPositions::iterator i = m_windowPositions.begin();
WindowPositions::iterator end = m_windowPositions.end();
for (; i != end; ++ i)
if (!IsWindow((*i).m_hwnd))
break;
if (i == end)
break;
m_windowPositions.erase(i);
}
// find target
WindowPositions::iterator i = m_windowPositions.begin();
WindowPositions::iterator end = m_windowPositions.end();
WindowPositions::iterator target = end;
for (; i != end; ++ i)
if ((*i).m_hwnd == hwnd) {
target = i;
break;
}
if (IsZoomed(hwnd))
PostMessage(hwnd, WM_SYSCOMMAND, SC_RESTORE, 0);
else {
WindowPosition::Mode mode = WindowPosition::Mode_normal;
if (target != end) {
WindowPosition &wp = *target;
rc = wp.m_rc;
if (wp.m_mode == WindowPosition::Mode_HV)
mode = wp.m_mode =
i_isHorizontal ? WindowPosition::Mode_V : WindowPosition::Mode_H;
else if (( i_isHorizontal && wp.m_mode == WindowPosition::Mode_V) ||
(!i_isHorizontal && wp.m_mode == WindowPosition::Mode_H))
mode = wp.m_mode = WindowPosition::Mode_HV;
else
m_windowPositions.erase(target);
} else {
mode = i_isHorizontal ? WindowPosition::Mode_H : WindowPosition::Mode_V;
m_windowPositions.push_front(WindowPosition(hwnd, rc, mode));
}
if (static_cast<int>(mode) & static_cast<int>(WindowPosition::Mode_H))
rc.left = rcd.left, rc.right = rcd.right;
if (static_cast<int>(mode) & static_cast<int>(WindowPosition::Mode_V))
rc.top = rcd.top, rc.bottom = rcd.bottom;
asyncMoveWindow(hwnd, rc.left, rc.top, rcWidth(&rc), rcHeight(&rc));
}
}
// maximize window horizontally
void Engine::funcWindowHMaximize(FunctionParam *i_param,
TargetWindowType i_twt)
{
funcWindowHVMaximize(i_param, BooleanType_true, i_twt);
}
// maximize window virtically
void Engine::funcWindowVMaximize(FunctionParam *i_param,
TargetWindowType i_twt)
{
funcWindowHVMaximize(i_param, BooleanType_false, i_twt);
}
// move window
void Engine::funcWindowMove(FunctionParam *i_param, int i_dx, int i_dy,
TargetWindowType i_twt)
{
funcWindowMoveTo(i_param, GravityType_C, i_dx, i_dy, i_twt);
}
// move window to ...
void Engine::funcWindowMoveTo(FunctionParam *i_param,
GravityType i_gravityType,
int i_dx, int i_dy, TargetWindowType i_twt)
{
HWND hwnd;
RECT rc, rcd;
if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt, &rc, &rcd))
return;
int x = rc.left + i_dx;
int y = rc.top + i_dy;
if (i_gravityType & GravityType_N)
y = i_dy + rcd.top;
if (i_gravityType & GravityType_E)
x = i_dx + rcd.right - rcWidth(&rc);
if (i_gravityType & GravityType_W)
x = i_dx + rcd.left;
if (i_gravityType & GravityType_S)
y = i_dy + rcd.bottom - rcHeight(&rc);
asyncMoveWindow(hwnd, x, y);
}
// move window visibly
void Engine::funcWindowMoveVisibly(FunctionParam *i_param,
TargetWindowType i_twt)
{
HWND hwnd;
RECT rc, rcd;
if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt, &rc, &rcd))
return;
int x = rc.left;
int y = rc.top;
if (rc.left < rcd.left)
x = rcd.left;
else if (rcd.right < rc.right)
x = rcd.right - rcWidth(&rc);
if (rc.top < rcd.top)
y = rcd.top;
else if (rcd.bottom < rc.bottom)
y = rcd.bottom - rcHeight(&rc);
asyncMoveWindow(hwnd, x, y);
}
struct EnumDisplayMonitorsForWindowMonitorToParam {
std::vector<HMONITOR> m_monitors;
std::vector<MONITORINFO> m_monitorinfos;
int m_primaryMonitorIdx;
int m_currentMonitorIdx;
HMONITOR m_hmon;
public:
EnumDisplayMonitorsForWindowMonitorToParam(HMONITOR i_hmon)
: m_hmon(i_hmon),
m_primaryMonitorIdx(-1), m_currentMonitorIdx(-1) {
}
};
static BOOL CALLBACK enumDisplayMonitorsForWindowMonitorTo(
HMONITOR i_hmon, HDC i_hdc, LPRECT i_rcMonitor, LPARAM i_data)
{
EnumDisplayMonitorsForWindowMonitorToParam &ep =
*reinterpret_cast<EnumDisplayMonitorsForWindowMonitorToParam *>(i_data);
ep.m_monitors.push_back(i_hmon);
MONITORINFO mi;
mi.cbSize = sizeof(mi);
getMonitorInfo(i_hmon, &mi);
ep.m_monitorinfos.push_back(mi);
if (mi.dwFlags & MONITORINFOF_PRIMARY)
ep.m_primaryMonitorIdx = ep.m_monitors.size() - 1;
if (i_hmon == ep.m_hmon)
ep.m_currentMonitorIdx = ep.m_monitors.size() - 1;
return TRUE;
}
/// move window to other monitor
void Engine::funcWindowMonitorTo(
FunctionParam *i_param, WindowMonitorFromType i_fromType, int i_monitor,
BooleanType i_adjustPos, BooleanType i_adjustSize)
{
HWND hwnd;
if (! getSuitableWindow(i_param, &hwnd))
return;
HMONITOR hmonCur;
hmonCur = monitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
EnumDisplayMonitorsForWindowMonitorToParam ep(hmonCur);
enumDisplayMonitors(NULL, NULL, enumDisplayMonitorsForWindowMonitorTo,
reinterpret_cast<LPARAM>(&ep));
if (ep.m_monitors.size() < 1 ||
ep.m_primaryMonitorIdx < 0 || ep.m_currentMonitorIdx < 0)
return;
int targetIdx;
switch (i_fromType) {
case WindowMonitorFromType_primary:
targetIdx = (ep.m_primaryMonitorIdx + i_monitor) % ep.m_monitors.size();
break;
case WindowMonitorFromType_current:
targetIdx = (ep.m_currentMonitorIdx + i_monitor) % ep.m_monitors.size();
break;
}
if (ep.m_currentMonitorIdx == targetIdx)
return;
RECT rcCur, rcTarget, rcWin;
rcCur = ep.m_monitorinfos[ep.m_currentMonitorIdx].rcWork;
rcTarget = ep.m_monitorinfos[targetIdx].rcWork;
GetWindowRect(hwnd, &rcWin);
int x = rcTarget.left + (rcWin.left - rcCur.left);
int y = rcTarget.top + (rcWin.top - rcCur.top);
int w = rcWidth(&rcWin);
int h = rcHeight(&rcWin);
if (i_adjustPos) {
if (x + w > rcTarget.right)
x = rcTarget.right - w;
if (x < rcTarget.left)
x = rcTarget.left;
if (w > rcWidth(&rcTarget)) {
x = rcTarget.left;
w = rcWidth(&rcTarget);
}
if (y + h > rcTarget.bottom)
y = rcTarget.bottom - h;
if (y < rcTarget.top)
y = rcTarget.top;
if (h > rcHeight(&rcTarget)) {
y = rcTarget.top;
h = rcHeight(&rcTarget);
}
}
if (i_adjustPos && i_adjustSize) {
if (IsZoomed(hwnd))
PostMessage(hwnd, WM_SYSCOMMAND, SC_RESTORE, 0);
asyncMoveWindow(hwnd, x, y, w, h);
} else {
asyncMoveWindow(hwnd, x, y);
}
}
/// move window to other monitor
void Engine::funcWindowMonitor(
FunctionParam *i_param, int i_monitor,
BooleanType i_adjustPos, BooleanType i_adjustSize)
{
funcWindowMonitorTo(i_param, WindowMonitorFromType_primary, i_monitor,
i_adjustPos, i_adjustSize);
}
//
void Engine::funcWindowClingToLeft(FunctionParam *i_param,
TargetWindowType i_twt)
{
funcWindowMoveTo(i_param, GravityType_W, 0, 0, i_twt);
}
//
void Engine::funcWindowClingToRight(FunctionParam *i_param,
TargetWindowType i_twt)
{
funcWindowMoveTo(i_param, GravityType_E, 0, 0, i_twt);
}
//
void Engine::funcWindowClingToTop(FunctionParam *i_param,
TargetWindowType i_twt)
{
funcWindowMoveTo(i_param, GravityType_N, 0, 0, i_twt);
}
//
void Engine::funcWindowClingToBottom(FunctionParam *i_param,
TargetWindowType i_twt)
{
funcWindowMoveTo(i_param, GravityType_S, 0, 0, i_twt);
}
// close window
void Engine::funcWindowClose(FunctionParam *i_param, TargetWindowType i_twt)
{
HWND hwnd;
if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt))
return;
PostMessage(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0);
}
// toggle top-most flag of the window
void Engine::funcWindowToggleTopMost(FunctionParam *i_param)
{
HWND hwnd;
if (!getSuitableWindow(i_param, &hwnd))
return;
SetWindowPos(
hwnd,
#ifdef MAYU64
(GetWindowLongPtr(hwnd, GWL_EXSTYLE) & WS_EX_TOPMOST) ?
#else
(GetWindowLong(hwnd, GWL_EXSTYLE) & WS_EX_TOPMOST) ?
#endif
HWND_NOTOPMOST : HWND_TOPMOST,
0, 0, 0, 0,
SWP_ASYNCWINDOWPOS | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOSIZE);
}
// identify the window
void Engine::funcWindowIdentify(FunctionParam *i_param)
{
if (!i_param->m_isPressed)
return;
_TCHAR className[GANA_MAX_ATOM_LENGTH];
bool ok = false;
if (GetClassName(i_param->m_hwnd, className, NUMBER_OF(className))) {
if (_tcsicmp(className, _T("ConsoleWindowClass")) == 0) {
_TCHAR titleName[1024];
if (GetWindowText(i_param->m_hwnd, titleName, NUMBER_OF(titleName)) == 0)
titleName[0] = _T('\0');
{
Acquire a(&m_log, 1);
m_log << _T("HWND:\t") << std::hex
<< reinterpret_cast<int>(i_param->m_hwnd)
<< std::dec << std::endl;
}
Acquire a(&m_log, 0);
m_log << _T("CLASS:\t") << className << std::endl;
m_log << _T("TITLE:\t") << titleName << std::endl;
HWND hwnd = getToplevelWindow(i_param->m_hwnd, NULL);
RECT rc;
GetWindowRect(hwnd, &rc);
m_log << _T("Toplevel Window Position/Size: (")
<< rc.left << _T(", ") << rc.top << _T(") / (")
<< rcWidth(&rc) << _T("x") << rcHeight(&rc)
<< _T(")") << std::endl;
SystemParametersInfo(SPI_GETWORKAREA, 0, (void *)&rc, FALSE);
m_log << _T("Desktop Window Position/Size: (")
<< rc.left << _T(", ") << rc.top << _T(") / (")
<< rcWidth(&rc) << _T("x") << rcHeight(&rc)
<< _T(")") << std::endl;
m_log << std::endl;
ok = true;
}
}
if (!ok) {
UINT WM_MAYU_MESSAGE = RegisterWindowMessage(
addSessionId(WM_MAYU_MESSAGE_NAME).c_str());
CHECK_TRUE( PostMessage(i_param->m_hwnd, WM_MAYU_MESSAGE,
MayuMessage_notifyName, 0) );
}
}
// set alpha blending parameter to the window
void Engine::funcWindowSetAlpha(FunctionParam *i_param, int i_alpha)
{
HWND hwnd;
if (!getSuitableWindow(i_param, &hwnd))
return;
if (i_alpha < 0) { // remove all alpha
for (WindowsWithAlpha::iterator i = m_windowsWithAlpha.begin();
i != m_windowsWithAlpha.end(); ++ i) {
#ifdef MAYU64
SetWindowLongPtr(*i, GWL_EXSTYLE,
GetWindowLongPtr(*i, GWL_EXSTYLE) & ~WS_EX_LAYERED);
#else
SetWindowLong(*i, GWL_EXSTYLE,
GetWindowLong(*i, GWL_EXSTYLE) & ~WS_EX_LAYERED);
#endif
RedrawWindow(*i, NULL, NULL,
RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
}
m_windowsWithAlpha.clear();
} else {
#ifdef MAYU64
LONG_PTR exStyle = GetWindowLongPtr(hwnd, GWL_EXSTYLE);
#else
LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
#endif
if (exStyle & WS_EX_LAYERED) { // remove alpha
WindowsWithAlpha::iterator
i = std::find(m_windowsWithAlpha.begin(), m_windowsWithAlpha.end(),
hwnd);
if (i == m_windowsWithAlpha.end())
return; // already layered by the application
m_windowsWithAlpha.erase(i);
#ifdef MAYU64
SetWindowLongPtr(hwnd, GWL_EXSTYLE, exStyle & ~WS_EX_LAYERED);
#else
SetWindowLong(hwnd, GWL_EXSTYLE, exStyle & ~WS_EX_LAYERED);
#endif
} else { // add alpha
#ifdef MAYU64
SetWindowLongPtr(hwnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED);
#else
SetWindowLong(hwnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED);
#endif
i_alpha %= 101;
if (!setLayeredWindowAttributes(hwnd, 0,
(BYTE)(255 * i_alpha / 100), LWA_ALPHA)) {
Acquire a(&m_log, 0);
m_log << _T("error: &WindowSetAlpha(") << i_alpha
<< _T(") failed for HWND: ") << std::hex
<< hwnd << std::dec << std::endl;
return;
}
m_windowsWithAlpha.push_front(hwnd);
}
RedrawWindow(hwnd, NULL, NULL,
RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
}
}
// redraw the window
void Engine::funcWindowRedraw(FunctionParam *i_param)
{
HWND hwnd;
if (!getSuitableWindow(i_param, &hwnd))
return;
RedrawWindow(hwnd, NULL, NULL,
RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
}
// resize window to
void Engine::funcWindowResizeTo(FunctionParam *i_param, int i_width,
int i_height, TargetWindowType i_twt)
{
HWND hwnd;
RECT rc, rcd;
if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt, &rc, &rcd))
return;
if (i_width == 0)
i_width = rcWidth(&rc);
else if (i_width < 0)
i_width += rcWidth(&rcd);
if (i_height == 0)
i_height = rcHeight(&rc);
else if (i_height < 0)
i_height += rcHeight(&rcd);
asyncResize(hwnd, i_width, i_height);
}
// move the mouse cursor
void Engine::funcMouseMove(FunctionParam *i_param, int i_dx, int i_dy)
{
if (!i_param->m_isPressed)
return;
POINT pt;
GetCursorPos(&pt);
SetCursorPos(pt.x + i_dx, pt.y + i_dy);
}
// send a mouse-wheel-message to Windows
void Engine::funcMouseWheel(FunctionParam *i_param, int i_delta)
{
if (!i_param->m_isPressed)
return;
mouse_event(MOUSEEVENTF_WHEEL, 0, 0, i_delta, 0);
}
// convert the contents of the Clipboard to upper case
void Engine::funcClipboardChangeCase(FunctionParam *i_param,
BooleanType i_doesConvertToUpperCase)
{
if (!i_param->m_isPressed)
return;
HGLOBAL hdata;
const _TCHAR *text = getTextFromClipboard(&hdata);
HGLOBAL hdataNew = NULL;
if (text) {
int size = static_cast<int>(GlobalSize(hdata));
hdataNew = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, size);
if (hdataNew) {
if (_TCHAR *dataNew = reinterpret_cast<_TCHAR *>(GlobalLock(hdataNew))) {
std::memcpy(dataNew, text, size);
_TCHAR *dataEnd = dataNew + size;
while (dataNew < dataEnd && *dataNew) {
_TCHAR c = *dataNew;
if (_istlead(c))
dataNew += 2;
else
*dataNew++ =
i_doesConvertToUpperCase ? _totupper(c) : _totlower(c);
}
GlobalUnlock(hdataNew);
}
}
}
closeClipboard(hdata, hdataNew);
}
// convert the contents of the Clipboard to upper case
void Engine::funcClipboardUpcaseWord(FunctionParam *i_param)
{
funcClipboardChangeCase(i_param, BooleanType_true);
}
// convert the contents of the Clipboard to lower case
void Engine::funcClipboardDowncaseWord(FunctionParam *i_param)
{
funcClipboardChangeCase(i_param, BooleanType_false);
}
// set the contents of the Clipboard to the string
void Engine::funcClipboardCopy(FunctionParam *i_param, const StrExprArg &i_text)
{
if (!i_param->m_isPressed)
return;
if (!OpenClipboard(NULL))
return;
HGLOBAL hdataNew =
GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
(i_text.eval().size() + 1) * sizeof(_TCHAR));
if (!hdataNew)
return;
_TCHAR *dataNew = reinterpret_cast<_TCHAR *>(GlobalLock(hdataNew));
_tcscpy(dataNew, i_text.eval().c_str());
GlobalUnlock(hdataNew);
closeClipboard(NULL, hdataNew);
}
//
void Engine::funcEmacsEditKillLinePred(
FunctionParam *i_param, const KeySeq *i_keySeq1, const KeySeq *i_keySeq2)
{
m_emacsEditKillLine.m_doForceReset = false;
if (!i_param->m_isPressed)
return;
int r = m_emacsEditKillLine.pred();
const KeySeq *keySeq;
if (r == 1)
keySeq = i_keySeq1;
else if (r == 2)
keySeq = i_keySeq2;
else // r == 0
return;
ASSERT(keySeq);
generateKeySeqEvents(i_param->m_c, keySeq, Part_all);
}
//
void Engine::funcEmacsEditKillLineFunc(FunctionParam *i_param)
{
if (!i_param->m_isPressed)
return;
m_emacsEditKillLine.func();
m_emacsEditKillLine.m_doForceReset = false;
}
// clear log
void Engine::funcLogClear(FunctionParam *i_param)
{
if (!i_param->m_isPressed)
return;
PostMessage(getAssociatedWndow(), WM_APP_engineNotify,
EngineNotify_clearLog, 0);
}
// recenter
void Engine::funcRecenter(FunctionParam *i_param)
{
if (!i_param->m_isPressed)
return;
if (m_hwndFocus) {
UINT WM_MAYU_MESSAGE = RegisterWindowMessage(
addSessionId(WM_MAYU_MESSAGE_NAME).c_str());
PostMessage(m_hwndFocus, WM_MAYU_MESSAGE, MayuMessage_funcRecenter, 0);
}
}
// set IME open status
void Engine::funcSetImeStatus(FunctionParam *i_param, ToggleType i_toggle)
{
if (!i_param->m_isPressed)
return;
if (m_hwndFocus) {
UINT WM_MAYU_MESSAGE = RegisterWindowMessage(
addSessionId(WM_MAYU_MESSAGE_NAME).c_str());
int status = -1;
switch (i_toggle) {
case ToggleType_toggle:
status = -1;
break;
case ToggleType_off:
status = 0;
break;
case ToggleType_on:
status = 1;
break;
}
PostMessage(m_hwndFocus, WM_MAYU_MESSAGE, MayuMessage_funcSetImeStatus, status);
}
}
// set IME open status
void Engine::funcSetImeString(FunctionParam *i_param, const StrExprArg &i_data)
{
if (!i_param->m_isPressed)
return;
if (m_hwndFocus) {
UINT WM_MAYU_MESSAGE = RegisterWindowMessage(
addSessionId(WM_MAYU_MESSAGE_NAME).c_str());
PostMessage(m_hwndFocus, WM_MAYU_MESSAGE, MayuMessage_funcSetImeString, i_data.eval().size() * sizeof(_TCHAR));
DWORD len = 0;
DWORD error;
DisconnectNamedPipe(m_hookPipe);
ConnectNamedPipe(m_hookPipe, NULL);
error = WriteFile(m_hookPipe, i_data.eval().c_str(),
i_data.eval().size() * sizeof(_TCHAR),
&len, NULL);
//FlushFileBuffers(m_hookPipe);
}
}
// Direct SSTP Server
class DirectSSTPServer
{
public:
tstring m_path;
HWND m_hwnd;
tstring m_name;
tstring m_keroname;
public:
DirectSSTPServer()
: m_hwnd(NULL) {
}
};
class ParseDirectSSTPData
{
typedef boost::match_results<boost::regex::const_iterator> MR;
public:
typedef std::map<tstring, DirectSSTPServer> DirectSSTPServers;
private:
DirectSSTPServers *m_directSSTPServers;
public:
// constructor
ParseDirectSSTPData(DirectSSTPServers *i_directSSTPServers)
: m_directSSTPServers(i_directSSTPServers) {
}
bool operator()(const MR& i_what) {
#ifdef _UNICODE
tstring id(to_wstring(std::string(i_what[1].first, i_what[1].second)));
tstring member(to_wstring(std::string(i_what[2].first, i_what[2].second)));
tstring value(to_wstring(std::string(i_what[3].first, i_what[3].second)));
#else
tstring id(i_what[1].first, i_what[1].second);
tstring member(i_what[2].first, i_what[2].second);
tstring value(i_what[3].first, i_what[3].second);
#endif
if (member == _T("path"))
(*m_directSSTPServers)[id].m_path = value;
else if (member == _T("hwnd"))
(*m_directSSTPServers)[id].m_hwnd =
reinterpret_cast<HWND>(_ttoi(value.c_str()));
else if (member == _T("name"))
(*m_directSSTPServers)[id].m_name = value;
else if (member == _T("keroname"))
(*m_directSSTPServers)[id].m_keroname = value;
return true;
}
};
// Direct SSTP
void Engine::funcDirectSSTP(FunctionParam *i_param,
const tregex &i_name,
const StrExprArg &i_protocol,
const std::list<tstringq> &i_headers)
{
if (!i_param->m_isPressed)
return;
// check Direct SSTP server exist ?
if (HANDLE hm = OpenMutex(MUTEX_ALL_ACCESS, FALSE, _T("sakura")))
CloseHandle(hm);
else {
Acquire a(&m_log, 0);
m_log << _T(" Error(1): Direct SSTP server does not exist.");
return;
}
HANDLE hfm = OpenFileMapping(FILE_MAP_READ, FALSE, _T("Sakura"));
if (!hfm) {
Acquire a(&m_log, 0);
m_log << _T(" Error(2): Direct SSTP server does not provide data.");
return;
}
char *data =
reinterpret_cast<char *>(MapViewOfFile(hfm, FILE_MAP_READ, 0, 0, 0));
if (!data) {
CloseHandle(hfm);
Acquire a(&m_log, 0);
m_log << _T(" Error(3): Direct SSTP server does not provide data.");
return;
}
long length = *(long *)data;
const char *begin = data + 4;
const char *end = data + length;
boost::regex getSakura("([0-9a-fA-F]{32})\\.([^\x01]+)\x01(.*?)\r\n");
ParseDirectSSTPData::DirectSSTPServers servers;
boost::regex_iterator<boost::regex::const_iterator>
it(begin, end, getSakura), last;
for (; it != last; ++it)
((ParseDirectSSTPData)(&servers))(*it);
// make request
tstring request;
if (!i_protocol.eval().size())
request += _T("NOTIFY SSTP/1.1");
else
request += i_protocol.eval();
request += _T("\r\n");
bool hasSender = false;
for (std::list<tstringq>::const_iterator
i = i_headers.begin(); i != i_headers.end(); ++ i) {
if (_tcsnicmp(_T("Charset"), i->c_str(), 7) == 0 ||
_tcsnicmp(_T("Hwnd"), i->c_str(), 4) == 0)
continue;
if (_tcsnicmp(_T("Sender"), i->c_str(), 6) == 0)
hasSender = true;
request += i->c_str();
request += _T("\r\n");
}
if (!hasSender) {
request += _T("Sender: ");
request += loadString(IDS_mayu);
request += _T("\r\n");
}
_TCHAR buf[100];
_sntprintf(buf, NUMBER_OF(buf), _T("HWnd: %d\r\n"),
reinterpret_cast<int>(m_hwndAssocWindow));
request += buf;
#ifdef _UNICODE
request += _T("Charset: UTF-8\r\n");
#else
request += _T("Charset: Shift_JIS\r\n");
#endif
request += _T("\r\n");
#ifdef _UNICODE
std::string request_UTF_8 = to_UTF_8(request);
#endif
// send request to Direct SSTP Server which matches i_name;
for (ParseDirectSSTPData::DirectSSTPServers::iterator
i = servers.begin(); i != servers.end(); ++ i) {
tsmatch what;
if (boost::regex_match(i->second.m_name, what, i_name)) {
COPYDATASTRUCT cd;
cd.dwData = 9801;
#ifdef _UNICODE
cd.cbData = request_UTF_8.size();
cd.lpData = (void *)request_UTF_8.c_str();
#else
cd.cbData = request.size();
cd.lpData = (void *)request.c_str();
#endif
#ifdef MAYU64
DWORD_PTR result;
#else
DWORD result;
#endif
SendMessageTimeout(i->second.m_hwnd, WM_COPYDATA,
reinterpret_cast<WPARAM>(m_hwndAssocWindow),
reinterpret_cast<LPARAM>(&cd),
SMTO_ABORTIFHUNG | SMTO_BLOCK, 5000, &result);
}
}
UnmapViewOfFile(data);
CloseHandle(hfm);
}
namespace shu
{
class PlugIn
{
enum Type {
Type_A,
Type_W
};
private:
HMODULE m_dll;
FARPROC m_func;
Type m_type;
tstringq m_funcParam;
public:
PlugIn() : m_dll(NULL) {
}
~PlugIn() {
FreeLibrary(m_dll);
}
bool load(const tstringq &i_dllName, const tstringq &i_funcName,
const tstringq &i_funcParam, tomsgstream &i_log) {
m_dll = LoadLibrary((_T("Plugins\\") + i_dllName).c_str());
if (!m_dll) {
m_dll = LoadLibrary((_T("Plugin\\") + i_dllName).c_str());
if (!m_dll) {
m_dll = LoadLibrary(i_dllName.c_str());
if (!m_dll) {
Acquire a(&i_log);
i_log << std::endl;
i_log << _T("error: &PlugIn() failed to load ") << i_dllName << std::endl;
return false;
}
}
}
// get function
#ifdef UNICODE
# define to_wstring
#else
# define to_string
#endif
m_type = Type_W;
m_func = GetProcAddress(m_dll, to_string(_T("mayu") + i_funcName + _T("W")).c_str());
if (!m_func) {
m_type = Type_A;
m_func
= GetProcAddress(m_dll, to_string(_T("mayu") + i_funcName + _T("A")).c_str());
if (!m_func) {
m_func = GetProcAddress(m_dll, to_string(_T("mayu") + i_funcName).c_str());
if (!m_func) {
m_func = GetProcAddress(m_dll, to_string(i_funcName).c_str());
if (!m_func) {
Acquire a(&i_log);
i_log << std::endl;
i_log << _T("error: &PlugIn() failed to find function: ")
<< i_funcName << std::endl;
return false;
}
}
}
}
m_funcParam = i_funcParam;
return true;
}
void exec() {
ASSERT( m_dll );
ASSERT( m_func );
typedef void (WINAPI * PLUGIN_FUNCTION_A)(const char *i_arg);
typedef void (WINAPI * PLUGIN_FUNCTION_W)(const wchar_t *i_arg);
switch (m_type) {
case Type_A:
reinterpret_cast<PLUGIN_FUNCTION_A>(m_func)(to_string(m_funcParam).c_str());
break;
case Type_W:
reinterpret_cast<PLUGIN_FUNCTION_W>(m_func)(to_wstring(m_funcParam).c_str());
break;
}
}
#undef to_string
#undef to_wstring
};
static void plugInThread(void *i_plugin)
{
PlugIn *plugin = static_cast<PlugIn *>(i_plugin);
plugin->exec();
delete plugin;
}
}
void Engine::funcPlugIn(FunctionParam *i_param,
const StrExprArg &i_dllName,
const StrExprArg &i_funcName,
const StrExprArg &i_funcParam,
BooleanType i_doesCreateThread)
{
if (!i_param->m_isPressed)
return;
shu::PlugIn *plugin = new shu::PlugIn();
if (!plugin->load(i_dllName.eval(), i_funcName.eval(), i_funcParam.eval(), m_log)) {
delete plugin;
return;
}
if (i_doesCreateThread) {
if (_beginthread(shu::plugInThread, 0, plugin) == -1) {
delete plugin;
Acquire a(&m_log);
m_log << std::endl;
m_log << _T("error: &PlugIn() failed to create thread.");
}
return;
} else
plugin->exec();
}
void Engine::funcMouseHook(FunctionParam *i_param,
MouseHookType i_hookType, int i_hookParam)
{
GetCursorPos(&g_hookData->m_mousePos);
g_hookData->m_mouseHookType = i_hookType;
g_hookData->m_mouseHookParam = i_hookParam;
switch (i_hookType) {
case MouseHookType_WindowMove: {
// For this type, g_hookData->m_mouseHookParam means
// target window type to move.
HWND target;
bool isMDI;
// i_hooParam < 0 means target window to move is MDI.
if (i_hookParam < 0)
isMDI = true;
else
isMDI = false;
// abs(i_hookParam) == 2: target is window under mouse cursor
// otherwise: target is current focus window
if (i_hookParam == 2 || i_hookParam == -2)
target = WindowFromPoint(g_hookData->m_mousePos);
else
target = i_param->m_hwnd;
g_hookData->m_hwndMouseHookTarget =
reinterpret_cast<DWORD>(getToplevelWindow(target, &isMDI));
break;
default:
g_hookData->m_hwndMouseHookTarget = NULL;
break;
}
}
return;
}
// cancel prefix
void Engine::funcCancelPrefix(FunctionParam *i_param)
{
m_isPrefix = false;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// StrExpr
class StrExpr
{
private:
tstringq m_symbol;
protected:
static const Engine *s_engine;
public:
StrExpr(const tstringq &i_symbol) : m_symbol(i_symbol) {};
virtual ~StrExpr() {};
virtual StrExpr *clone() const {
return new StrExpr(*this);
}
virtual tstringq eval() const {
return m_symbol;
}
static void setEngine(const Engine *i_engine) {
s_engine = i_engine;
}
};
const Engine *StrExpr::s_engine = NULL;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// StrExprClipboard
class StrExprClipboard : public StrExpr
{
public:
StrExprClipboard(const tstringq &i_symbol) : StrExpr(i_symbol) {};
~StrExprClipboard() {};
StrExpr *clone() const {
return new StrExprClipboard(*this);
}
tstringq eval() const {
HGLOBAL g;
const _TCHAR *text = getTextFromClipboard(&g);
const tstring value(text == NULL ? _T("") : text);
closeClipboard(g);
return value;
}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// StrExprWindowClassName
class StrExprWindowClassName : public StrExpr
{
public:
StrExprWindowClassName(const tstringq &i_symbol) : StrExpr(i_symbol) {};
~StrExprWindowClassName() {};
StrExpr *clone() const {
return new StrExprWindowClassName(*this);
}
tstringq eval() const {
return s_engine->getCurrentWindowClassName();
}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// StrExprWindowTitleName
class StrExprWindowTitleName : public StrExpr
{
public:
StrExprWindowTitleName(const tstringq &i_symbol) : StrExpr(i_symbol) {};
~StrExprWindowTitleName() {};
StrExpr *clone() const {
return new StrExprWindowTitleName(*this);
}
tstringq eval() const {
return s_engine->getCurrentWindowTitleName();
}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// StrExprArg
// default constructor
StrExprArg::StrExprArg()
{
m_expr = new StrExpr(_T(""));
}
// copy contructor
StrExprArg::StrExprArg(const StrExprArg &i_data)
{
m_expr = i_data.m_expr->clone();
}
StrExprArg &StrExprArg::operator=(const StrExprArg &i_data)
{
if (i_data.m_expr == m_expr)
return *this;
delete m_expr;
m_expr = i_data.m_expr->clone();
return *this;
}
// initializer
StrExprArg::StrExprArg(const tstringq &i_symbol, Type i_type)
{
switch (i_type) {
case Literal:
m_expr = new StrExpr(i_symbol);
break;
case Builtin:
if (i_symbol == _T("Clipboard"))
m_expr = new StrExprClipboard(i_symbol);
else if (i_symbol == _T("WindowClassName"))
m_expr = new StrExprWindowClassName(i_symbol);
else if (i_symbol == _T("WindowTitleName"))
m_expr = new StrExprWindowTitleName(i_symbol);
break;
default:
break;
}
}
StrExprArg::~StrExprArg()
{
delete m_expr;
}
tstringq StrExprArg::eval() const
{
return m_expr->eval();
}
void StrExprArg::setEngine(const Engine *i_engine)
{
StrExpr::setEngine(i_engine);
}
// stream output
tostream &operator<<(tostream &i_ost, const StrExprArg &i_data)
{
i_ost << i_data.eval();
return i_ost;
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// dlgsetting.h
#ifndef _DLGSETTING_H
# define _DLGSETTING_H
# include <windows.h>
///
#ifdef MAYU64
INT_PTR CALLBACK dlgSetting_dlgProc(
#else
BOOL CALLBACK dlgSetting_dlgProc(
#endif
HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam);
#endif // !_DLGSETTING_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// mayu.h
#ifndef _MAYU_H
# define _MAYU_H
///
#ifdef USE_INI
# define MAYU_REGISTRY_ROOT 0, _T("yamy")
#else // !USE_INI
# define MAYU_REGISTRY_ROOT HKEY_CURRENT_USER, _T("Software\\gimy.net\\yamy")
#endif // !USE_INI
///
# define MUTEX_MAYU_EXCLUSIVE_RUNNING \
_T("{46269F4D-D560-40f9-B38B-DB5E280FEF47}")
///
# define MUTEX_YAMYD_BLOCKER \
_T("{267C9CA1-C4DC-4011-B78A-745781FD60F4}")
///
# define MAX_MAYU_REGISTRY_ENTRIES 256
#endif // _MAYU_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// dlgeditsetting.cpp
#include "misc.h"
#include "mayurc.h"
#include "windowstool.h"
#include "dlgeditsetting.h"
#include "layoutmanager.h"
#include <windowsx.h>
///
class DlgEditSetting : public LayoutManager
{
HWND m_hwndMayuPathName; ///
HWND m_hwndMayuPath; ///
HWND m_hwndSymbols; ///
DlgEditSettingData *m_data; ///
public:
///
DlgEditSetting(HWND i_hwnd)
: LayoutManager(i_hwnd),
m_hwndMayuPathName(NULL),
m_hwndMayuPath(NULL),
m_hwndSymbols(NULL),
m_data(NULL) {
}
/// WM_INITDIALOG
BOOL wmInitDialog(HWND /* focus */, LPARAM i_lParam) {
m_data = reinterpret_cast<DlgEditSettingData *>(i_lParam);
setSmallIcon(m_hwnd, IDI_ICON_mayu);
setBigIcon(m_hwnd, IDI_ICON_mayu);
CHECK_TRUE( m_hwndMayuPathName
= GetDlgItem(m_hwnd, IDC_EDIT_mayuPathName) );
CHECK_TRUE( m_hwndMayuPath = GetDlgItem(m_hwnd, IDC_EDIT_mayuPath) );
CHECK_TRUE( m_hwndSymbols = GetDlgItem(m_hwnd, IDC_EDIT_symbols) );
SetWindowText(m_hwndMayuPathName, m_data->m_name.c_str());
SetWindowText(m_hwndMayuPath, m_data->m_filename.c_str());
SetWindowText(m_hwndSymbols, m_data->m_symbols.c_str());
restrictSmallestSize();
// set layout manager
typedef LayoutManager LM;
addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuPathName));
addItem(GetDlgItem(m_hwnd, IDC_EDIT_mayuPathName),
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuPathNameComment),
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuPath));
addItem(GetDlgItem(m_hwnd, IDC_EDIT_mayuPath),
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_BUTTON_browse),
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_STATIC_symbols));
addItem(GetDlgItem(m_hwnd, IDC_EDIT_symbols),
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_STATIC_symbolsComment),
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE);
addItem(GetDlgItem(m_hwnd, IDOK),
LM::ORIGIN_CENTER, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_CENTER, LM::ORIGIN_TOP_EDGE);
addItem(GetDlgItem(m_hwnd, IDCANCEL),
LM::ORIGIN_CENTER, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_CENTER, LM::ORIGIN_TOP_EDGE);
restrictSmallestSize(LM::RESTRICT_BOTH);
restrictLargestSize(LM::RESTRICT_VERTICALLY);
return TRUE;
}
/// WM_CLOSE
BOOL wmClose() {
CHECK_TRUE( EndDialog(m_hwnd, 0) );
return TRUE;
}
/// WM_COMMAND
BOOL wmCommand(int /* i_notify_code */, int i_id, HWND /* i_hwnd_control */) {
_TCHAR buf[GANA_MAX_PATH];
switch (i_id) {
case IDC_BUTTON_browse: {
tstring title = loadString(IDS_openMayu);
tstring filter = loadString(IDS_openMayuFilter);
for (size_t i = 0; i < filter.size(); ++ i)
if (filter[i] == _T('|'))
filter[i] = _T('\0');
_tcscpy(buf, _T(".mayu"));
OPENFILENAME of;
memset(&of, 0, sizeof(of));
of.lStructSize = sizeof(of);
of.hwndOwner = m_hwnd;
of.lpstrFilter = filter.c_str();
of.nFilterIndex = 1;
of.lpstrFile = buf;
of.nMaxFile = NUMBER_OF(buf);
of.lpstrTitle = title.c_str();
of.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST |
OFN_HIDEREADONLY | OFN_PATHMUSTEXIST;
if (GetOpenFileName(&of))
SetWindowText(m_hwndMayuPath, buf);
return TRUE;
}
case IDOK: {
GetWindowText(m_hwndMayuPathName, buf, NUMBER_OF(buf));
m_data->m_name = buf;
GetWindowText(m_hwndMayuPath, buf, NUMBER_OF(buf));
m_data->m_filename = buf;
GetWindowText(m_hwndSymbols, buf, NUMBER_OF(buf));
m_data->m_symbols = buf;
CHECK_TRUE( EndDialog(m_hwnd, 1) );
return TRUE;
}
case IDCANCEL: {
CHECK_TRUE( EndDialog(m_hwnd, 0) );
return TRUE;
}
}
return FALSE;
}
};
//
#ifdef MAYU64
INT_PTR CALLBACK dlgEditSetting_dlgProc(HWND i_hwnd, UINT i_message,
#else
BOOL CALLBACK dlgEditSetting_dlgProc(HWND i_hwnd, UINT i_message,
#endif
WPARAM i_wParam, LPARAM i_lParam)
{
DlgEditSetting *wc;
getUserData(i_hwnd, &wc);
if (!wc)
switch (i_message) {
case WM_INITDIALOG:
wc = setUserData(i_hwnd, new DlgEditSetting(i_hwnd));
return wc->wmInitDialog(
reinterpret_cast<HWND>(i_wParam), i_lParam);
}
else
switch (i_message) {
case WM_COMMAND:
return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam),
reinterpret_cast<HWND>(i_lParam));
case WM_CLOSE:
return wc->wmClose();
case WM_NCDESTROY:
delete wc;
return TRUE;
default:
return wc->defaultWMHandler(i_message, i_wParam, i_lParam);
}
return FALSE;
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// yamyd.cpp
#include "mayu.h"
#include "hook.h"
/// main
int WINAPI _tWinMain(HINSTANCE /* i_hInstance */, HINSTANCE /* i_hPrevInstance */,
LPTSTR /* i_lpszCmdLine */, int /* i_nCmdShow */)
{
HANDLE mutex = OpenMutex(SYNCHRONIZE, FALSE, MUTEX_YAMYD_BLOCKER);
if (mutex != NULL) {
CHECK_FALSE( installMessageHook(0) );
// wait for master process exit
WaitForSingleObject(mutex, INFINITE);
CHECK_FALSE( uninstallMessageHook() );
ReleaseMutex(mutex);
}
return 0;
}
<file_sep>///////////////////////////////////////////////////////////////////////////////
// setup.cpp
#include "../misc.h"
#include "../registry.h"
#include "../stringtool.h"
#include "../windowstool.h"
#include "installer.h"
#include <shlobj.h>
#include <sys/types.h>
#include <sys/stat.h>
namespace Installer
{
using namespace std;
/////////////////////////////////////////////////////////////////////////////
// Utility Functions
/** createLink
uses the shell's IShellLink and IPersistFile interfaces to
create and store a shortcut to the specified object.
@return
the result of calling the member functions of the interfaces.
@param i_pathObj
address of a buffer containing the path of the object.
@param i_pathLink
address of a buffer containing the path where the
shell link is to be stored.
@param i_desc
address of a buffer containing the description of the
shell link.
*/
HRESULT createLink(LPCTSTR i_pathObj, LPCTSTR i_pathLink, LPCTSTR i_desc,
LPCTSTR i_workingDirectory)
{
// Get a pointer to the IShellLink interface.
IShellLink* psl;
HRESULT hres =
CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
IID_IShellLink, (void **)&psl);
if (SUCCEEDED(hres)) {
// Set the path to the shortcut target and add the description.
psl->SetPath(i_pathObj);
psl->SetDescription(i_desc);
if (i_workingDirectory)
psl->SetWorkingDirectory(i_workingDirectory);
// Query IShellLink for the IPersistFile interface for saving the
// shortcut in persistent storage.
IPersistFile* ppf;
hres = psl->QueryInterface(IID_IPersistFile, (void **)&ppf);
if (SUCCEEDED(hres)) {
#ifdef UNICODE
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(i_pathLink, TRUE);
#else
wchar_t wsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, i_pathLink, -1, wsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(wsz, TRUE);
#endif
ppf->Release();
}
psl->Release();
}
return hres;
}
// create file extension information
void createFileExtension(const tstringi &i_ext, const tstring &i_contentType,
const tstringi &i_fileType,
const tstring &i_fileTypeName,
const tstringi &i_iconPath,
const tstring &i_command)
{
tstring dummy;
Registry regExt(HKEY_CLASSES_ROOT, i_ext);
if (! regExt.read (_T(""), &dummy))
CHECK_TRUE( regExt.write(_T(""), i_fileType) );
if (! regExt.read (_T("Content Type"), &dummy))
CHECK_TRUE( regExt.write(_T("Content Type"), i_contentType) );
Registry regFileType(HKEY_CLASSES_ROOT, i_fileType);
if (! regFileType.read (_T(""), &dummy))
CHECK_TRUE( regFileType.write(_T(""), i_fileTypeName) );
Registry regFileTypeIcon(HKEY_CLASSES_ROOT,
i_fileType + _T("\\DefaultIcon"));
if (! regFileTypeIcon.read (_T(""), &dummy))
CHECK_TRUE( regFileTypeIcon.write(_T(""), i_iconPath) );
Registry regFileTypeComand(HKEY_CLASSES_ROOT,
i_fileType + _T("\\shell\\open\\command"));
if (! regFileTypeComand.read (_T(""), &dummy))
CHECK_TRUE( regFileTypeComand.write(_T(""), i_command) );
}
// remove file extension information
void removeFileExtension(const tstringi &i_ext, const tstringi &i_fileType)
{
Registry::remove(HKEY_CLASSES_ROOT, i_ext);
Registry::remove(HKEY_CLASSES_ROOT,
i_fileType + _T("\\shell\\open\\command"));
Registry::remove(HKEY_CLASSES_ROOT, i_fileType + _T("\\shell\\open"));
Registry::remove(HKEY_CLASSES_ROOT, i_fileType + _T("\\shell"));
Registry::remove(HKEY_CLASSES_ROOT, i_fileType);
}
// create uninstallation information
void createUninstallInformation(const tstringi &i_name,
const tstring &i_displayName,
const tstring &i_commandLine)
{
Registry reg(
HKEY_LOCAL_MACHINE,
_T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\")
+ i_name);
CHECK_TRUE( reg.write(_T("DisplayName"), i_displayName) );
CHECK_TRUE( reg.write(_T("UninstallString"), i_commandLine) );
}
// remove uninstallation information
void removeUninstallInformation(const tstringi &i_name)
{
Registry::
remove(HKEY_LOCAL_MACHINE,
_T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\")
+ i_name);
}
// normalize path
tstringi normalizePath(tstringi i_path)
{
tregex regSlash(_T("^(.*)/(.*)$"));
tsmatch what;
while (boost::regex_search(i_path, what, regSlash))
i_path = what.str(1) + _T("\\") + what.str(2);
tregex regTailBackSlash(_T("^(.*)\\\\$"));
while (boost::regex_search(i_path, what, regTailBackSlash))
i_path = what.str(1);
return i_path;
}
// create deep directory
bool createDirectories(const _TCHAR *i_folder)
{
const _TCHAR *s = _tcschr(i_folder, _T('\\')); // TODO: '/'
if (s && s - i_folder == 2 && i_folder[1] == _T(':'))
s = _tcschr(s + 1, _T('\\'));
struct _stat sbuf;
while (s) {
tstringi f(i_folder, 0, s - i_folder);
if (_tstat(f.c_str(), &sbuf) < 0)
if (!CreateDirectory(f.c_str(), NULL))
return false;
s = _tcschr(s + 1, _T('\\'));
}
if (_tstat(i_folder, &sbuf) < 0)
if (!CreateDirectory(i_folder, NULL))
return false;
return true;
}
// get driver directory
tstringi getDriverDirectory()
{
_TCHAR buf[GANA_MAX_PATH];
CHECK_TRUE( GetSystemDirectory(buf, NUMBER_OF(buf)) );
return tstringi(buf) + _T("\\drivers");
}
// get current directory
tstringi getModuleDirectory()
{
_TCHAR buf[GANA_MAX_PATH];
CHECK_TRUE( GetModuleFileName(g_hInst, buf, NUMBER_OF(buf)) );
tregex reg(_T("^(.*)\\\\[^\\\\]*$"));
tsmatch what;
tstringi path(buf);
if (boost::regex_search(path, what, reg))
return what.str(1);
else
return path;
}
// get start menu name
tstringi getStartMenuName(const tstringi &i_shortcutName)
{
#if 0
char programDir[GANA_MAX_PATH];
if (SUCCEEDED(SHGetSpecialFolderPath(NULL, programDir,
CSIDL_COMMON_PROGRAMS, FALSE)))
return tstringi(programDir) + "\\" + shortcutName + ".lnk";
#else
tstringi programDir;
if (Registry::read(HKEY_LOCAL_MACHINE,
_T("Software\\Microsoft\\Windows\\CurrentVersion\\")
_T("Explorer\\Shell Folders"), _T("Common Programs"),
&programDir))
return programDir + _T("\\") + i_shortcutName + _T(".lnk");
#endif
return _T("");
}
// get start up name
tstringi getStartUpName(const tstringi &i_shortcutName)
{
tstringi startupDir;
if (Registry::read(HKEY_CURRENT_USER,
_T("Software\\Microsoft\\Windows\\CurrentVersion\\")
_T("Explorer\\Shell Folders"), _T("Startup"),
&startupDir))
return startupDir + _T("\\") + i_shortcutName + _T(".lnk");
return _T("");
}
#if defined(_WINNT)
# define MAYUD_FILTER_KEY _T("System\\CurrentControlSet\\Control\\Class\\{4D36E96B-E325-11CE-BFC1-08002BE10318}")
// create driver service
DWORD createDriverService(const tstringi &i_serviceName,
const tstring &i_serviceDescription,
const tstringi &i_driverPath,
const _TCHAR *i_preloadedGroups,
bool forUsb)
{
SC_HANDLE hscm =
OpenSCManager(NULL, NULL,
SC_MANAGER_CREATE_SERVICE | SC_MANAGER_CONNECT);
if (!hscm)
return false;
SC_HANDLE hs =
CreateService(hscm, i_serviceName.c_str(), i_serviceDescription.c_str(),
SERVICE_START | SERVICE_STOP, SERVICE_KERNEL_DRIVER,
forUsb == true ? SERVICE_DEMAND_START : SERVICE_AUTO_START,
SERVICE_ERROR_IGNORE,
i_driverPath.c_str(), NULL, NULL,
i_preloadedGroups, NULL, NULL);
DWORD err = GetLastError();
if (hs == NULL) {
switch (err) {
case ERROR_SERVICE_EXISTS: {
#if 0
hs = OpenService(hscm, i_serviceName.c_str(), SERVICE_CHANGE_CONFIG);
if (hs == NULL) {
CloseServiceHandle(hscm);
return GetLastError();
}
if (!ChangeServiceConfig(
hscm, SERVICE_KERNEL_DRIVER,
forUsb == true ? SERVICE_DEMAND_START : SERVICE_AUTO_START,
SERVICE_ERROR_IGNORE,
i_driverPath.c_str(), NULL, NULL,
i_preloadedGroups, NULL, NULL,
i_serviceDescription.c_str())) {
CloseServiceHandle(hs);
CloseServiceHandle(hscm);
return GetLastError(); // ERROR_IO_PENDING!
// this code always reaches here. why?
}
#else
Registry reg(HKEY_LOCAL_MACHINE,
_T("SYSTEM\\CurrentControlSet\\Services\\mayud"));
reg.write(_T("Start"),
forUsb ? SERVICE_DEMAND_START : SERVICE_AUTO_START);
#endif
break;
}
default: {
CloseServiceHandle(hscm);
return err;
}
}
}
CloseServiceHandle(hs);
CloseServiceHandle(hscm);
if (forUsb == true) {
Registry reg(HKEY_LOCAL_MACHINE, MAYUD_FILTER_KEY);
typedef std::list<tstring> Filters;
Filters filters;
if (!reg.read(_T("UpperFilters"), &filters))
return false;
for (Filters::iterator i = filters.begin(); i != filters.end(); ) {
Filters::iterator next = i;
++ next;
if (*i == _T("mayud")) {
filters.erase(i);
}
i = next;
}
filters.push_back(_T("mayud"));
if (!reg.write(_T("UpperFilters"), filters))
return false;
}
return ERROR_SUCCESS;
}
#endif // _WINNT
#if defined(_WINNT)
// remove driver service
DWORD removeDriverService(const tstringi &i_serviceName)
{
DWORD err = ERROR_SUCCESS;
Registry reg(HKEY_LOCAL_MACHINE, MAYUD_FILTER_KEY);
std::list<tstring> filters;
if (reg.read(_T("UpperFilters"), &filters)) {
filters.remove(_T("mayud"));
reg.write(_T("UpperFilters"), filters);
}
SC_HANDLE hscm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
SC_HANDLE hs =
OpenService(hscm, i_serviceName.c_str(),
SERVICE_START | SERVICE_STOP | DELETE);
if (!hs) {
err = GetLastError();
goto error;
}
SERVICE_STATUS ss;
ControlService(hs, SERVICE_CONTROL_STOP, &ss);
if (!DeleteService(hs)) {
err = GetLastError();
goto error;
}
error:
CloseServiceHandle(hs);
CloseServiceHandle(hscm);
return err;
}
#endif // _WINNT
// check operating system
bool checkOs(SetupFile::OS os)
{
OSVERSIONINFO ver;
ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&ver);
switch (os) {
default:
case SetupFile::ALL:
return true;
case SetupFile::W9x:
return (ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
4 <= ver.dwMajorVersion);
case SetupFile::NT :
return (ver.dwPlatformId == VER_PLATFORM_WIN32_NT &&
4 <= ver.dwMajorVersion);
case SetupFile::NT4:
return (ver.dwPlatformId == VER_PLATFORM_WIN32_NT &&
ver.dwMajorVersion == 4);
case SetupFile::W2k: // W2k, XP, ...
return (ver.dwPlatformId == VER_PLATFORM_WIN32_NT &&
5 <= ver.dwMajorVersion);
}
}
// install files
bool installFiles(const SetupFile::Data *i_setupFiles,
size_t i_setupFilesSize, u_int32 i_flags,
const tstringi &i_srcDir, const tstringi &i_destDir)
{
tstringi to, from;
tstringi destDriverDir = getDriverDirectory();
for (size_t i = 0; i < i_setupFilesSize; ++ i) {
const SetupFile::Data &s = i_setupFiles[i];
const tstringi &fromDir = i_srcDir;
const tstringi &toDir =
(s.m_destination == SetupFile::ToDriver) ? destDriverDir : i_destDir;
if (!s.m_from)
continue; // remove only
if (fromDir == toDir)
continue; // same directory
if (!checkOs(s.m_os)) // check operating system
continue;
if ((s.m_flags & i_flags) != i_flags) // check flags
continue;
// type
switch (s.m_kind) {
case SetupFile::Dll: {
// rename driver
tstringi from_ = toDir + _T("\\") + s.m_to;
tstringi to_ = toDir + _T("\\deleted.") + s.m_to;
DeleteFile(to_.c_str());
MoveFile(from_.c_str(), to_.c_str());
DeleteFile(to_.c_str());
}
// fall through
default:
case SetupFile::File: {
from += fromDir + _T('\\') + s.m_from + _T('\0');
to += toDir + _T('\\') + s.m_to + _T('\0');
break;
}
case SetupFile::Dir: {
createDirectories((toDir + _T('\\') + s.m_to).c_str());
break;
}
}
}
#if 0
{
tstringi to_(to), from_(from);
for (size_t i = 0; i < to_.size(); ++ i)
if (!to_[i])
to_[i] = ' ';
for (size_t i = 0; i < from_.size(); ++ i)
if (!from_[i])
from_[i] = ' ';
MessageBox(NULL, to_.c_str(), from_.c_str(), MB_OK);
}
#endif
SHFILEOPSTRUCT fo;
::ZeroMemory(&fo, sizeof(fo));
fo.wFunc = FO_COPY;
fo.fFlags = FOF_MULTIDESTFILES;
fo.pFrom = from.c_str();
fo.pTo = to.c_str();
if (SHFileOperation(&fo) || fo.fAnyOperationsAborted)
return false;
return true;
}
// remove files from src
bool removeSrcFiles(const SetupFile::Data *i_setupFiles,
size_t i_setupFilesSize, u_int32 i_flags,
const tstringi &i_srcDir)
{
tstringi destDriverDir = getDriverDirectory();
for (size_t i = 0; i < i_setupFilesSize; ++ i) {
const SetupFile::Data &s = i_setupFiles[i_setupFilesSize - i - 1];
const tstringi &fromDir = i_srcDir;
if (!s.m_from)
continue; // remove only
if (!checkOs(s.m_os)) // check operating system
continue;
if ((s.m_flags & i_flags) != i_flags) // check flags
continue;
// type
switch (s.m_kind) {
default:
case SetupFile::Dll:
case SetupFile::File:
DeleteFile((fromDir + _T('\\') + s.m_from).c_str());
break;
case SetupFile::Dir:
RemoveDirectory((fromDir + _T('\\') + s.m_from).c_str());
break;
}
}
RemoveDirectory(i_srcDir.c_str());
return true;
}
// remove files
void removeFiles(const SetupFile::Data *i_setupFiles,
size_t i_setupFilesSize, u_int32 i_flags,
const tstringi &i_destDir)
{
tstringi destDriverDir = getDriverDirectory();
for (size_t i = 0; i < i_setupFilesSize; ++ i) {
const SetupFile::Data &s = i_setupFiles[i_setupFilesSize - i - 1];
const tstringi &toDir =
(s.m_destination == SetupFile::ToDriver) ? destDriverDir : i_destDir;
if (!checkOs(s.m_os)) // check operating system
continue;
if ((s.m_flags & i_flags) != i_flags) // check flags
continue;
// type
switch (s.m_kind) {
case SetupFile::Dll:
DeleteFile((toDir + _T("\\deleted.") + s.m_to).c_str());
// fall through
default:
case SetupFile::File:
DeleteFile((toDir + _T('\\') + s.m_to).c_str());
break;
case SetupFile::Dir:
RemoveDirectory((toDir + _T('\\') + s.m_to).c_str());
break;
}
}
RemoveDirectory(i_destDir.c_str());
}
// uninstall step1
int uninstallStep1(const _TCHAR *i_uninstallOption)
{
// copy this EXEcutable image into the user's temp directory
_TCHAR setup_exe[GANA_MAX_PATH], tmp_setup_exe[GANA_MAX_PATH];
GetModuleFileName(NULL, setup_exe, NUMBER_OF(setup_exe));
GetTempPath(NUMBER_OF(tmp_setup_exe), tmp_setup_exe);
GetTempFileName(tmp_setup_exe, _T("del"), 0, tmp_setup_exe);
CopyFile(setup_exe, tmp_setup_exe, FALSE);
// open the clone EXE using FILE_FLAG_DELETE_ON_CLOSE
HANDLE hfile = CreateFile(tmp_setup_exe, 0, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, NULL);
// spawn the clone EXE passing it our EXE's process handle
// and the full path name to the original EXE file.
_TCHAR commandLine[512];
HANDLE hProcessOrig =
OpenProcess(SYNCHRONIZE, TRUE, GetCurrentProcessId());
_sntprintf(commandLine, NUMBER_OF(commandLine), _T("%s %s %d"),
tmp_setup_exe, i_uninstallOption, hProcessOrig);
STARTUPINFO si;
::ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
PROCESS_INFORMATION pi;
CreateProcess(NULL, commandLine, NULL, NULL, TRUE, 0, NULL, NULL, &si,&pi);
Sleep(2000); // important
CloseHandle(hProcessOrig);
CloseHandle(hfile);
return 0;
}
// uninstall step2
// (after this function, we cannot use any resource)
void uninstallStep2(const _TCHAR *argByStep1)
{
// clone EXE: When original EXE terminates, delete it
HANDLE hProcessOrig = (HANDLE)_ttoi(argByStep1);
WaitForSingleObject(hProcessOrig, INFINITE);
CloseHandle(hProcessOrig);
}
/////////////////////////////////////////////////////////////////////////////
// Locale / StringResource
// constructor
Resource::Resource(const StringResource *i_stringResources)
: m_stringResources(i_stringResources),
m_locale(LOCALE_C)
{
struct LocaleInformaton {
const _TCHAR *m_localeString;
Locale m_locale;
};
// set locale information
const _TCHAR *localeString = ::_tsetlocale(LC_ALL, _T(""));
static const LocaleInformaton locales[] = {
{ _T("Japanese_Japan.932"), LOCALE_Japanese_Japan_932 },
};
for (size_t i = 0; i < NUMBER_OF(locales); ++ i)
if (_tcsicmp(localeString, locales[i].m_localeString) == 0) {
m_locale = locales[i].m_locale;
break;
}
}
// get resource string
const _TCHAR *Resource::loadString(UINT i_id)
{
int n = static_cast<int>(m_locale);
int index = -1;
for (int i = 0; m_stringResources[i].m_str; ++ i)
if (m_stringResources[i].m_id == i_id) {
if (n == 0)
return m_stringResources[i].m_str;
index = i;
n --;
}
if (0 <= index)
return m_stringResources[index].m_str;
else
return _T("");
}
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// focus.cpp
#include "focus.h"
#include "windowstool.h"
///
static LRESULT CALLBACK WndProc(
HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam)
{
switch (i_message) {
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
SendMessage(GetParent(i_hwnd), WM_APP_notifyVKey, i_wParam, i_lParam);
return 0;
case WM_CHAR:
case WM_DEADCHAR:
return 0;
case WM_LBUTTONDOWN: {
SetFocus(i_hwnd);
return 0;
}
case WM_SETFOCUS: {
RECT rc;
GetClientRect(i_hwnd, &rc);
CreateCaret(i_hwnd, reinterpret_cast<HBITMAP>(NULL), 2,
rcHeight(&rc) / 2);
ShowCaret(i_hwnd);
SetCaretPos(rcWidth(&rc) / 2, rcHeight(&rc) / 4);
SendMessage(GetParent(i_hwnd), WM_APP_notifyFocus,
TRUE, (LPARAM)i_hwnd);
return 0;
}
case WM_KILLFOCUS: {
HideCaret(i_hwnd);
DestroyCaret();
SendMessage(GetParent(i_hwnd), WM_APP_notifyFocus,
FALSE, (LPARAM)i_hwnd);
return 0;
}
case WM_GETDLGCODE:
return DLGC_WANTALLKEYS;
}
return DefWindowProc(i_hwnd, i_message, i_wParam, i_lParam);
}
ATOM Register_focus()
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = g_hInst;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_IBEAM);
wc.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = _T("mayuFocus");
return RegisterClass(&wc);
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// compiler_specific_func.h
#ifndef _COMPILER_SPECIFIC_FUNC_H
# define _COMPILER_SPECIFIC_FUNC_H
#include "misc.h"
#include "stringtool.h"
/// get compiler version string
tstring getCompilerVersionString();
#endif // !_COMPILER_SPECIFIC_FUNC_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// registry.h
#ifndef _REGISTRY_H
# define _REGISTRY_H
# include "stringtool.h"
# include <list>
/// registry access class
class Registry
{
HKEY m_root; /// registry root
tstring m_path; /// path from registry root
public:
typedef std::list<tstring> tstrings;
public:
///
Registry() : m_root(NULL) {
setRoot(NULL, _T(""));
}
///
Registry(HKEY i_root, const tstring &i_path)
: m_root(i_root), m_path(i_path) {
setRoot(i_root, i_path);
}
/// set registry root and path
void setRoot(HKEY i_root, const tstring &i_path) {
m_root = i_root;
if (m_root) {
m_path = i_path;
} else {
_TCHAR exePath[GANA_MAX_PATH];
_TCHAR exeDrive[GANA_MAX_PATH];
_TCHAR exeDir[GANA_MAX_PATH];
GetModuleFileName(NULL, exePath, GANA_MAX_PATH);
_tsplitpath_s(exePath, exeDrive, GANA_MAX_PATH, exeDir, GANA_MAX_PATH, NULL, 0, NULL, 0);
m_path = exeDrive;
m_path += exeDir;
m_path += _T("yamy.ini");
}
}
/// remvoe
bool remove(const tstring &i_name = _T("")) const {
return remove(m_root, m_path, i_name);
}
/// does exist the key ?
bool doesExist() const {
return doesExist(m_root, m_path);
}
/// read DWORD
bool read(const tstring &i_name, int *o_value, int i_defaultValue = 0)
const {
return read(m_root, m_path, i_name, o_value, i_defaultValue);
}
/// write DWORD
bool write(const tstring &i_name, int i_value) const {
return write(m_root, m_path, i_name, i_value);
}
/// read tstring
bool read(const tstring &i_name, tstring *o_value,
const tstring &i_defaultValue = _T("")) const {
return read(m_root, m_path, i_name, o_value, i_defaultValue);
}
/// write tstring
bool write(const tstring &i_name, const tstring &i_value) const {
return write(m_root, m_path, i_name, i_value);
}
#ifndef USE_INI
/// read list of tstring
bool read(const tstring &i_name, tstrings *o_value,
const tstrings &i_defaultValue = tstrings()) const {
return read(m_root, m_path, i_name, o_value, i_defaultValue);
}
/// write list of tstring
bool write(const tstring &i_name, const tstrings &i_value) const {
return write(m_root, m_path, i_name, i_value);
}
#endif //!USE_INI
/// read binary data
bool read(const tstring &i_name, BYTE *o_value, DWORD *i_valueSize,
const BYTE *i_defaultValue = NULL, DWORD i_defaultValueSize = 0)
const {
return read(m_root, m_path, i_name, o_value, i_valueSize, i_defaultValue,
i_defaultValueSize);
}
/// write binary data
bool write(const tstring &i_name, const BYTE *i_value,
DWORD i_valueSize) const {
return write(m_root, m_path, i_name, i_value, i_valueSize);
}
public:
/// remove
static bool remove(HKEY i_root, const tstring &i_path,
const tstring &i_name = _T(""));
/// does exist the key ?
static bool doesExist(HKEY i_root, const tstring &i_path);
/// read DWORD
static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name,
int *o_value, int i_defaultValue = 0);
/// write DWORD
static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name,
int i_value);
/// read tstring
static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name,
tstring *o_value, const tstring &i_defaultValue = _T(""));
/// write tstring
static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name,
const tstring &i_value);
#ifndef USE_INI
/// read list of tstring
static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name,
tstrings *o_value, const tstrings &i_defaultValue = tstrings());
/// write list of tstring
static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name,
const tstrings &i_value);
#endif //!USE_INI
/// read binary data
static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name,
BYTE *o_value, DWORD *i_valueSize,
const BYTE *i_defaultValue = NULL,
DWORD i_defaultValueSize = 0);
/// write binary data
static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name,
const BYTE *i_value, DWORD i_valueSize);
/// read LOGFONT
static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name,
LOGFONT *o_value, const tstring &i_defaultStringValue);
/// write LOGFONT
static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name,
const LOGFONT &i_value);
};
#endif // !_REGISTRY_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// engine.cpp
#include "misc.h"
#include "engine.h"
#include "errormessage.h"
#include "hook.h"
#include "mayurc.h"
#include "windowstool.h"
#include <iomanip>
#include <process.h>
// check focus window
void Engine::checkFocusWindow()
{
int count = 0;
restart:
count ++;
HWND hwndFore = GetForegroundWindow();
DWORD threadId = GetWindowThreadProcessId(hwndFore, NULL);
if (hwndFore) {
{
Acquire a(&m_cs);
if (m_currentFocusOfThread &&
m_currentFocusOfThread->m_threadId == threadId &&
m_currentFocusOfThread->m_hwndFocus == m_hwndFocus)
return;
m_emacsEditKillLine.reset();
// erase dead thread
if (!m_detachedThreadIds.empty()) {
for (ThreadIds::iterator i = m_detachedThreadIds.begin();
i != m_detachedThreadIds.end(); i ++) {
FocusOfThreads::iterator j = m_focusOfThreads.find((*i));
if (j != m_focusOfThreads.end()) {
FocusOfThread *fot = &((*j).second);
Acquire a(&m_log, 1);
m_log << _T("RemoveThread") << std::endl;
m_log << _T("\tHWND:\t") << std::hex << (int)fot->m_hwndFocus
<< std::dec << std::endl;
m_log << _T("\tTHREADID:") << fot->m_threadId << std::endl;
m_log << _T("\tCLASS:\t") << fot->m_className << std::endl;
m_log << _T("\tTITLE:\t") << fot->m_titleName << std::endl;
m_log << std::endl;
m_focusOfThreads.erase(j);
}
}
m_detachedThreadIds.erase
(m_detachedThreadIds.begin(), m_detachedThreadIds.end());
}
FocusOfThreads::iterator i = m_focusOfThreads.find(threadId);
if (i != m_focusOfThreads.end()) {
m_currentFocusOfThread = &((*i).second);
if (!m_currentFocusOfThread->m_isConsole || 2 <= count) {
if (m_currentFocusOfThread->m_keymaps.empty())
setCurrentKeymap(NULL);
else
setCurrentKeymap(*m_currentFocusOfThread->m_keymaps.begin());
m_hwndFocus = m_currentFocusOfThread->m_hwndFocus;
checkShow(m_hwndFocus);
Acquire a(&m_log, 1);
m_log << _T("FocusChanged") << std::endl;
m_log << _T("\tHWND:\t")
<< std::hex << (int)m_currentFocusOfThread->m_hwndFocus
<< std::dec << std::endl;
m_log << _T("\tTHREADID:")
<< m_currentFocusOfThread->m_threadId << std::endl;
m_log << _T("\tCLASS:\t")
<< m_currentFocusOfThread->m_className << std::endl;
m_log << _T("\tTITLE:\t")
<< m_currentFocusOfThread->m_titleName << std::endl;
m_log << std::endl;
return;
}
}
}
_TCHAR className[GANA_MAX_ATOM_LENGTH];
if (GetClassName(hwndFore, className, NUMBER_OF(className))) {
if (_tcsicmp(className, _T("ConsoleWindowClass")) == 0) {
_TCHAR titleName[1024];
if (GetWindowText(hwndFore, titleName, NUMBER_OF(titleName)) == 0)
titleName[0] = _T('\0');
setFocus(hwndFore, threadId, className, titleName, true);
Acquire a(&m_log, 1);
m_log << _T("HWND:\t") << std::hex << reinterpret_cast<int>(hwndFore)
<< std::dec << std::endl;
m_log << _T("THREADID:") << threadId << std::endl;
m_log << _T("CLASS:\t") << className << std::endl;
m_log << _T("TITLE:\t") << titleName << std::endl << std::endl;
goto restart;
}
}
}
Acquire a(&m_cs);
if (m_globalFocus.m_keymaps.empty()) {
Acquire a(&m_log, 1);
m_log << _T("NO GLOBAL FOCUS") << std::endl;
m_currentFocusOfThread = NULL;
setCurrentKeymap(NULL);
} else {
if (m_currentFocusOfThread != &m_globalFocus) {
Acquire a(&m_log, 1);
m_log << _T("GLOBAL FOCUS") << std::endl;
m_currentFocusOfThread = &m_globalFocus;
setCurrentKeymap(m_globalFocus.m_keymaps.front());
}
}
m_hwndFocus = NULL;
}
// is modifier pressed ?
bool Engine::isPressed(Modifier::Type i_mt)
{
const Keymap::ModAssignments &ma = m_currentKeymap->getModAssignments(i_mt);
for (Keymap::ModAssignments::const_iterator i = ma.begin();
i != ma.end(); ++ i)
if ((*i).m_key->m_isPressed)
return true;
return false;
}
// fix modifier key (if fixed, return true)
bool Engine::fixModifierKey(ModifiedKey *io_mkey, Keymap::AssignMode *o_am)
{
// for all modifier ...
for (int i = Modifier::Type_begin; i != Modifier::Type_end; ++ i) {
// get modifier assignments (list of modifier keys)
const Keymap::ModAssignments &ma =
m_currentKeymap->getModAssignments(static_cast<Modifier::Type>(i));
for (Keymap::ModAssignments::const_iterator
j = ma.begin(); j != ma.end(); ++ j)
if (io_mkey->m_key == (*j).m_key) { // is io_mkey a modifier ?
{
Acquire a(&m_log, 1);
m_log << _T("* Modifier Key") << std::endl;
}
// set dontcare for this modifier
io_mkey->m_modifier.dontcare(static_cast<Modifier::Type>(i));
*o_am = (*j).m_assignMode;
return true;
}
}
*o_am = Keymap::AM_notModifier;
return false;
}
// output to m_log
void Engine::outputToLog(const Key *i_key, const ModifiedKey &i_mkey,
int i_debugLevel)
{
size_t i;
Acquire a(&m_log, i_debugLevel);
// output scan codes
for (i = 0; i < i_key->getScanCodesSize(); ++ i) {
if (i_key->getScanCodes()[i].m_flags & ScanCode::E0) m_log << _T("E0-");
if (i_key->getScanCodes()[i].m_flags & ScanCode::E1) m_log << _T("E1-");
if (!(i_key->getScanCodes()[i].m_flags & ScanCode::E0E1))
m_log << _T(" ");
m_log << _T("0x") << std::hex << std::setw(2) << std::setfill(_T('0'))
<< static_cast<int>(i_key->getScanCodes()[i].m_scan)
<< std::dec << _T(" ");
}
if (!i_mkey.m_key) { // key corresponds to no phisical key
m_log << std::endl;
return;
}
m_log << _T(" ") << i_mkey << std::endl;
}
// describe bindings
void Engine::describeBindings()
{
Acquire a(&m_log, 0);
Keymap::DescribeParam dp;
for (KeymapPtrList::iterator i = m_currentFocusOfThread->m_keymaps.begin();
i != m_currentFocusOfThread->m_keymaps.end(); ++ i)
(*i)->describe(m_log, &dp);
m_log << std::endl;
}
// update m_lastPressedKey
void Engine::updateLastPressedKey(Key *i_key)
{
m_lastPressedKey[1] = m_lastPressedKey[0];
m_lastPressedKey[0] = i_key;
}
// set current keymap
void Engine::setCurrentKeymap(const Keymap *i_keymap, bool i_doesAddToHistory)
{
if (i_doesAddToHistory) {
m_keymapPrefixHistory.push_back(const_cast<Keymap *>(m_currentKeymap));
if (MAX_KEYMAP_PREFIX_HISTORY < m_keymapPrefixHistory.size())
m_keymapPrefixHistory.pop_front();
} else
m_keymapPrefixHistory.clear();
m_currentKeymap = i_keymap;
}
// get current modifiers
Modifier Engine::getCurrentModifiers(Key *i_key, bool i_isPressed)
{
Modifier cmods;
cmods.add(m_currentLock);
cmods.press(Modifier::Type_Shift , isPressed(Modifier::Type_Shift ));
cmods.press(Modifier::Type_Alt , isPressed(Modifier::Type_Alt ));
cmods.press(Modifier::Type_Control, isPressed(Modifier::Type_Control));
cmods.press(Modifier::Type_Windows, isPressed(Modifier::Type_Windows));
cmods.press(Modifier::Type_Up , !i_isPressed);
cmods.press(Modifier::Type_Down , i_isPressed);
cmods.press(Modifier::Type_Repeat , false);
if (m_lastPressedKey[0] == i_key) {
if (i_isPressed)
cmods.press(Modifier::Type_Repeat, true);
else
if (m_lastPressedKey[1] == i_key)
cmods.press(Modifier::Type_Repeat, true);
}
for (int i = Modifier::Type_Mod0; i <= Modifier::Type_Mod9; ++ i)
cmods.press(static_cast<Modifier::Type>(i),
isPressed(static_cast<Modifier::Type>(i)));
return cmods;
}
// generate keyboard event for a key
void Engine::generateKeyEvent(Key *i_key, bool i_doPress, bool i_isByAssign)
{
// check if key is event
bool isEvent = false;
for (Key **e = Event::events; *e; ++ e)
if (*e == i_key) {
isEvent = true;
break;
}
bool isAlreadyReleased = false;
if (!isEvent) {
if (i_doPress && !i_key->m_isPressedOnWin32)
++ m_currentKeyPressCountOnWin32;
else if (!i_doPress) {
if (i_key->m_isPressedOnWin32)
-- m_currentKeyPressCountOnWin32;
else
isAlreadyReleased = true;
}
i_key->m_isPressedOnWin32 = i_doPress;
if (i_isByAssign)
i_key->m_isPressedByAssign = i_doPress;
Key *sync = m_setting->m_keyboard.getSyncKey();
if (!isAlreadyReleased || i_key == sync) {
KEYBOARD_INPUT_DATA kid = { 0, 0, 0, 0, 0 };
const ScanCode *sc = i_key->getScanCodes();
for (size_t i = 0; i < i_key->getScanCodesSize(); ++ i) {
kid.MakeCode = sc[i].m_scan;
kid.Flags = sc[i].m_flags;
if (!i_doPress)
kid.Flags |= KEYBOARD_INPUT_DATA::BREAK;
injectInput(&kid, NULL);
}
m_lastGeneratedKey = i_doPress ? i_key : NULL;
}
}
{
Acquire a(&m_log, 1);
m_log << _T("\t\t =>\t");
if (isAlreadyReleased)
m_log << _T("(already released) ");
}
ModifiedKey mkey(i_key);
mkey.m_modifier.on(Modifier::Type_Up, !i_doPress);
mkey.m_modifier.on(Modifier::Type_Down, i_doPress);
outputToLog(i_key, mkey, 1);
}
// genete event
void Engine::generateEvents(Current i_c, const Keymap *i_keymap, Key *i_event)
{
// generate
i_c.m_keymap = i_keymap;
i_c.m_mkey.m_key = i_event;
if (const Keymap::KeyAssignment *keyAssign =
i_c.m_keymap->searchAssignment(i_c.m_mkey)) {
{
Acquire a(&m_log, 1);
m_log << std::endl << _T(" ")
<< i_event->getName() << std::endl;
}
generateKeySeqEvents(i_c, keyAssign->m_keySeq, Part_all);
}
}
// genete modifier events
void Engine::generateModifierEvents(const Modifier &i_mod)
{
{
Acquire a(&m_log, 1);
m_log << _T("* Gen Modifiers\t{") << std::endl;
}
for (int i = Modifier::Type_begin; i < Modifier::Type_BASIC; ++ i) {
Keyboard::Mods &mods =
m_setting->m_keyboard.getModifiers(static_cast<Modifier::Type>(i));
if (i_mod.isDontcare(static_cast<Modifier::Type>(i)))
// no need to process
;
else if (i_mod.isPressed(static_cast<Modifier::Type>(i)))
// we have to press this modifier
{
bool noneIsPressed = true;
bool noneIsPressedByAssign = true;
for (Keyboard::Mods::iterator i = mods.begin(); i != mods.end(); ++ i) {
if ((*i)->m_isPressedOnWin32)
noneIsPressed = false;
if ((*i)->m_isPressedByAssign)
noneIsPressedByAssign = false;
}
if (noneIsPressed) {
if (noneIsPressedByAssign)
generateKeyEvent(mods.front(), true, false);
else
for (Keyboard::Mods::iterator
i = mods.begin(); i != mods.end(); ++ i)
if ((*i)->m_isPressedByAssign)
generateKeyEvent((*i), true, false);
}
}
else
// we have to release this modifier
{
// avoid such sequences as "Alt U-ALt" or "Windows U-Windows"
if (i == Modifier::Type_Alt || i == Modifier::Type_Windows) {
for (Keyboard::Mods::iterator j = mods.begin(); j != mods.end(); ++ j)
if ((*j) == m_lastGeneratedKey) {
Keyboard::Mods *mods =
&m_setting->m_keyboard.getModifiers(Modifier::Type_Shift);
if (mods->size() == 0)
mods = &m_setting->m_keyboard.getModifiers(
Modifier::Type_Control);
if (0 < mods->size()) {
generateKeyEvent(mods->front(), true, false);
generateKeyEvent(mods->front(), false, false);
}
break;
}
}
for (Keyboard::Mods::iterator j = mods.begin(); j != mods.end(); ++ j) {
if ((*j)->m_isPressedOnWin32)
generateKeyEvent((*j), false, false);
}
}
}
{
Acquire a(&m_log, 1);
m_log << _T("\t\t}") << std::endl;
}
}
// generate keyboard events for action
void Engine::generateActionEvents(const Current &i_c, const Action *i_a,
bool i_doPress)
{
switch (i_a->getType()) {
// key
case Action::Type_key: {
const ModifiedKey &mkey
= reinterpret_cast<ActionKey *>(
const_cast<Action *>(i_a))->m_modifiedKey;
// release
if (!i_doPress &&
(mkey.m_modifier.isOn(Modifier::Type_Up) ||
mkey.m_modifier.isDontcare(Modifier::Type_Up)))
generateKeyEvent(mkey.m_key, false, true);
// press
else if (i_doPress &&
(mkey.m_modifier.isOn(Modifier::Type_Down) ||
mkey.m_modifier.isDontcare(Modifier::Type_Down))) {
Modifier modifier = mkey.m_modifier;
modifier.add(i_c.m_mkey.m_modifier);
generateModifierEvents(modifier);
generateKeyEvent(mkey.m_key, true, true);
}
break;
}
// keyseq
case Action::Type_keySeq: {
const ActionKeySeq *aks = reinterpret_cast<const ActionKeySeq *>(i_a);
generateKeySeqEvents(i_c, aks->m_keySeq,
i_doPress ? Part_down : Part_up);
break;
}
// function
case Action::Type_function: {
const ActionFunction *af = reinterpret_cast<const ActionFunction *>(i_a);
bool is_up = (!i_doPress &&
(af->m_modifier.isOn(Modifier::Type_Up) ||
af->m_modifier.isDontcare(Modifier::Type_Up)));
bool is_down = (i_doPress &&
(af->m_modifier.isOn(Modifier::Type_Down) ||
af->m_modifier.isDontcare(Modifier::Type_Down)));
if (!is_down && !is_up)
break;
{
Acquire a(&m_log, 1);
m_log << _T("\t\t >\t") << af->m_functionData;
}
FunctionParam param;
param.m_isPressed = i_doPress;
param.m_hwnd = m_currentFocusOfThread->m_hwndFocus;
param.m_c = i_c;
param.m_doesNeedEndl = true;
param.m_af = af;
param.m_c.m_mkey.m_modifier.on(Modifier::Type_Up, !i_doPress);
param.m_c.m_mkey.m_modifier.on(Modifier::Type_Down, i_doPress);
af->m_functionData->exec(this, ¶m);
if (param.m_doesNeedEndl) {
Acquire a(&m_log, 1);
m_log << std::endl;
}
break;
}
}
}
// generate keyboard events for keySeq
void Engine::generateKeySeqEvents(const Current &i_c, const KeySeq *i_keySeq,
Part i_part)
{
const KeySeq::Actions &actions = i_keySeq->getActions();
if (actions.empty())
return;
if (i_part == Part_up)
generateActionEvents(i_c, actions[actions.size() - 1], false);
else {
size_t i;
for (i = 0 ; i < actions.size() - 1; ++ i) {
generateActionEvents(i_c, actions[i], true);
generateActionEvents(i_c, actions[i], false);
}
generateActionEvents(i_c, actions[i], true);
if (i_part == Part_all)
generateActionEvents(i_c, actions[i], false);
}
}
// generate keyboard events for current key
void Engine::generateKeyboardEvents(const Current &i_c)
{
if (++ m_generateKeyboardEventsRecursionGuard ==
MAX_GENERATE_KEYBOARD_EVENTS_RECURSION_COUNT) {
Acquire a(&m_log);
m_log << _T("error: too deep keymap recursion. there may be a loop.")
<< std::endl;
return;
}
const Keymap::KeyAssignment *keyAssign
= i_c.m_keymap->searchAssignment(i_c.m_mkey);
if (!keyAssign) {
const KeySeq *keySeq = i_c.m_keymap->getDefaultKeySeq();
ASSERT( keySeq );
generateKeySeqEvents(i_c, keySeq, i_c.isPressed() ? Part_down : Part_up);
} else {
if (keyAssign->m_modifiedKey.m_modifier.isOn(Modifier::Type_Up) ||
keyAssign->m_modifiedKey.m_modifier.isOn(Modifier::Type_Down))
generateKeySeqEvents(i_c, keyAssign->m_keySeq, Part_all);
else
generateKeySeqEvents(i_c, keyAssign->m_keySeq,
i_c.isPressed() ? Part_down : Part_up);
}
m_generateKeyboardEventsRecursionGuard --;
}
// generate keyboard events for current key
void Engine::beginGeneratingKeyboardEvents(
const Current &i_c, bool i_isModifier)
{
// (1) (2) (3) (4) (1)
// up/down: D- U- D- U- D-
// keymap: m_currentKeymap m_currentKeymap X X m_currentKeymap
// memo: &Prefix(X) ... ... ... ...
// m_isPrefix: false true true false false
Current cnew(i_c);
bool isPhysicallyPressed
= cnew.m_mkey.m_modifier.isPressed(Modifier::Type_Down);
// substitute
ModifiedKey mkey = m_setting->m_keyboard.searchSubstitute(cnew.m_mkey);
if (mkey.m_key) {
cnew.m_mkey = mkey;
if (isPhysicallyPressed) {
cnew.m_mkey.m_modifier.off(Modifier::Type_Up);
cnew.m_mkey.m_modifier.on(Modifier::Type_Down);
} else {
cnew.m_mkey.m_modifier.on(Modifier::Type_Up);
cnew.m_mkey.m_modifier.off(Modifier::Type_Down);
}
for (int i = Modifier::Type_begin; i != Modifier::Type_end; ++ i) {
Modifier::Type type = static_cast<Modifier::Type>(i);
if (cnew.m_mkey.m_modifier.isDontcare(type) &&
!i_c.m_mkey.m_modifier.isDontcare(type))
cnew.m_mkey.m_modifier.press(
type, i_c.m_mkey.m_modifier.isPressed(type));
}
{
Acquire a(&m_log, 1);
m_log << _T("* substitute") << std::endl;
}
outputToLog(mkey.m_key, cnew.m_mkey, 1);
}
// for prefix key
const Keymap *tmpKeymap = m_currentKeymap;
if (i_isModifier || !m_isPrefix) ;
else if (isPhysicallyPressed) // when (3)
m_isPrefix = false;
else if (!isPhysicallyPressed) // when (2)
m_currentKeymap = m_currentFocusOfThread->m_keymaps.front();
// for m_emacsEditKillLine function
m_emacsEditKillLine.m_doForceReset = !i_isModifier;
// generate key event !
m_generateKeyboardEventsRecursionGuard = 0;
if (isPhysicallyPressed)
generateEvents(cnew, cnew.m_keymap, &Event::before_key_down);
generateKeyboardEvents(cnew);
if (!isPhysicallyPressed)
generateEvents(cnew, cnew.m_keymap, &Event::after_key_up);
// for m_emacsEditKillLine function
if (m_emacsEditKillLine.m_doForceReset)
m_emacsEditKillLine.reset();
// for prefix key
if (i_isModifier)
;
else if (!m_isPrefix) // when (1), (4)
m_currentKeymap = m_currentFocusOfThread->m_keymaps.front();
else if (!isPhysicallyPressed) // when (2)
m_currentKeymap = tmpKeymap;
}
unsigned int Engine::injectInput(const KEYBOARD_INPUT_DATA *i_kid, const KBDLLHOOKSTRUCT *i_kidRaw)
{
if (i_kid->Flags & KEYBOARD_INPUT_DATA::E1) {
INPUT kid[2];
int count = 1;
kid[0].type = INPUT_MOUSE;
kid[0].mi.dx = 0;
kid[0].mi.dy = 0;
kid[0].mi.time = 0;
kid[0].mi.mouseData = 0;
kid[0].mi.dwExtraInfo = 0;
switch (i_kid->MakeCode) {
case 1:
if (i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) {
kid[0].mi.dwFlags = MOUSEEVENTF_LEFTUP;
} else {
kid[0].mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
}
break;
case 2:
if (i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) {
kid[0].mi.dwFlags = MOUSEEVENTF_RIGHTUP;
} else {
kid[0].mi.dwFlags = MOUSEEVENTF_RIGHTDOWN;
}
break;
case 3:
if (i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) {
kid[0].mi.dwFlags = MOUSEEVENTF_MIDDLEUP;
} else {
kid[0].mi.dwFlags = MOUSEEVENTF_MIDDLEDOWN;
}
break;
case 4:
if (i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) {
return 1;
} else {
kid[0].mi.mouseData = WHEEL_DELTA;
kid[0].mi.dwFlags = MOUSEEVENTF_WHEEL;
}
break;
case 5:
if (i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) {
return 1;
} else {
kid[0].mi.mouseData = -WHEEL_DELTA;
kid[0].mi.dwFlags = MOUSEEVENTF_WHEEL;
}
break;
case 6:
kid[0].mi.mouseData = XBUTTON1;
if (i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) {
kid[0].mi.dwFlags = MOUSEEVENTF_XUP;
} else {
kid[0].mi.dwFlags = MOUSEEVENTF_XDOWN;
}
break;
case 7:
kid[0].mi.mouseData = XBUTTON2;
if (i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) {
kid[0].mi.dwFlags = MOUSEEVENTF_XUP;
} else {
kid[0].mi.dwFlags = MOUSEEVENTF_XDOWN;
}
break;
case 8:
if (i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) {
return 1;
} else {
kid[0].mi.mouseData = WHEEL_DELTA;
kid[0].mi.dwFlags = MOUSEEVENTF_HWHEEL;
}
break;
case 9:
if (i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) {
return 1;
} else {
kid[0].mi.mouseData = -WHEEL_DELTA;
kid[0].mi.dwFlags = MOUSEEVENTF_HWHEEL;
}
break;
default:
return 1;
break;
}
if (!(i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) &&
i_kid->MakeCode != 4 && i_kid->MakeCode != 5 &&
i_kid->MakeCode != 8 && i_kid->MakeCode != 9) {
HWND hwnd;
POINT pt;
if (GetCursorPos(&pt) && (hwnd = WindowFromPoint(pt))) {
_TCHAR className[GANA_MAX_ATOM_LENGTH];
if (GetClassName(hwnd, className, NUMBER_OF(className))) {
if (_tcsicmp(className, _T("ConsoleWindowClass")) == 0) {
SetForegroundWindow(hwnd);
}
}
}
if (m_dragging) {
kid[0].mi.dx = 65535 * m_msllHookCurrent.pt.x / GetSystemMetrics(SM_CXVIRTUALSCREEN);
kid[0].mi.dy = 65535 * m_msllHookCurrent.pt.y / GetSystemMetrics(SM_CYVIRTUALSCREEN);
kid[0].mi.dwFlags |= MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK;
kid[1].type = INPUT_MOUSE;
kid[1].mi.dx = 65535 * pt.x / GetSystemMetrics(SM_CXVIRTUALSCREEN);
kid[1].mi.dy = 65535 * pt.y / GetSystemMetrics(SM_CYVIRTUALSCREEN);
kid[1].mi.time = 0;
kid[1].mi.mouseData = 0;
kid[1].mi.dwExtraInfo = 0;
kid[1].mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK;
count = 2;
}
}
SendInput(count, &kid[0], sizeof(kid[0]));
} else {
INPUT kid;
kid.type = INPUT_KEYBOARD;
kid.ki.wVk = 0;
kid.ki.wScan = i_kid->MakeCode;
kid.ki.dwFlags = KEYEVENTF_SCANCODE;
kid.ki.time = i_kidRaw ? i_kidRaw->time : 0;
kid.ki.dwExtraInfo = i_kidRaw ? i_kidRaw->dwExtraInfo : 0;
if (i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) {
kid.ki.dwFlags |= KEYEVENTF_KEYUP;
}
if (i_kid->Flags & KEYBOARD_INPUT_DATA::E0) {
kid.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
}
SendInput(1, &kid, sizeof(kid));
}
return 1;
}
// pop all pressed key on win32
void Engine::keyboardResetOnWin32()
{
for (Keyboard::KeyIterator
i = m_setting->m_keyboard.getKeyIterator(); *i; ++ i) {
if ((*i)->m_isPressedOnWin32)
generateKeyEvent((*i), false, true);
}
}
unsigned int WINAPI Engine::keyboardDetour(Engine *i_this, WPARAM i_wParam, LPARAM i_lParam)
{
return i_this->keyboardDetour(reinterpret_cast<KBDLLHOOKSTRUCT*>(i_lParam));
}
unsigned int Engine::keyboardDetour(KBDLLHOOKSTRUCT *i_kid)
{
#if 0
Acquire a(&m_log, 1);
m_log << std::hex
<< _T("keyboardDetour: vkCode=") << i_kid->vkCode
<< _T(" scanCode=") << i_kid->scanCode
<< _T(" flags=") << i_kid->flags << std::endl;
#endif
if ((i_kid->flags & LLKHF_INJECTED) || !m_isEnabled) {
return 0;
} else {
Key key;
KEYBOARD_INPUT_DATA kid;
kid.UnitId = 0;
kid.MakeCode = i_kid->scanCode;
kid.Flags = 0;
if (i_kid->flags & LLKHF_UP) {
kid.Flags |= KEYBOARD_INPUT_DATA::BREAK;
}
if (i_kid->flags & LLKHF_EXTENDED) {
kid.Flags |= KEYBOARD_INPUT_DATA::E0;
}
kid.Reserved = 0;
kid.ExtraInformation = 0;
WaitForSingleObject(m_queueMutex, INFINITE);
m_inputQueue->push_back(kid);
SetEvent(m_readEvent);
ReleaseMutex(m_queueMutex);
return 1;
}
}
unsigned int WINAPI Engine::mouseDetour(Engine *i_this, WPARAM i_wParam, LPARAM i_lParam)
{
return i_this->mouseDetour(i_wParam, reinterpret_cast<MSLLHOOKSTRUCT*>(i_lParam));
}
unsigned int Engine::mouseDetour(WPARAM i_message, MSLLHOOKSTRUCT *i_mid)
{
if (i_mid->flags & LLMHF_INJECTED || !m_isEnabled || !m_setting || !m_setting->m_mouseEvent) {
return 0;
} else {
KEYBOARD_INPUT_DATA kid;
kid.UnitId = 0;
kid.Flags = KEYBOARD_INPUT_DATA::E1;
kid.Reserved = 0;
kid.ExtraInformation = 0;
switch (i_message) {
case WM_LBUTTONUP:
kid.Flags |= KEYBOARD_INPUT_DATA::BREAK;
case WM_LBUTTONDOWN:
kid.MakeCode = 1;
break;
case WM_RBUTTONUP:
kid.Flags |= KEYBOARD_INPUT_DATA::BREAK;
case WM_RBUTTONDOWN:
kid.MakeCode = 2;
break;
case WM_MBUTTONUP:
kid.Flags |= KEYBOARD_INPUT_DATA::BREAK;
case WM_MBUTTONDOWN:
kid.MakeCode = 3;
break;
case WM_MOUSEWHEEL:
if (i_mid->mouseData & (1<<31)) {
kid.MakeCode = 5;
} else {
kid.MakeCode = 4;
}
break;
case WM_XBUTTONUP:
kid.Flags |= KEYBOARD_INPUT_DATA::BREAK;
case WM_XBUTTONDOWN:
switch ((i_mid->mouseData >> 16) & 0xFFFFU) {
case XBUTTON1:
kid.MakeCode = 6;
break;
case XBUTTON2:
kid.MakeCode = 7;
break;
default:
return 0;
break;
}
break;
case WM_MOUSEHWHEEL:
if (i_mid->mouseData & (1<<31)) {
kid.MakeCode = 9;
} else {
kid.MakeCode = 8;
}
break;
case WM_MOUSEMOVE: {
LONG dx = i_mid->pt.x - g_hookData->m_mousePos.x;
LONG dy = i_mid->pt.y - g_hookData->m_mousePos.y;
HWND target = reinterpret_cast<HWND>(g_hookData->m_hwndMouseHookTarget);
LONG dr = 0;
dr += (i_mid->pt.x - m_msllHookCurrent.pt.x) * (i_mid->pt.x - m_msllHookCurrent.pt.x);
dr += (i_mid->pt.y - m_msllHookCurrent.pt.y) * (i_mid->pt.y - m_msllHookCurrent.pt.y);
if (m_buttonPressed && !m_dragging && m_setting->m_dragThreshold &&
(m_setting->m_dragThreshold * m_setting->m_dragThreshold < dr)) {
kid.MakeCode = 0;
WaitForSingleObject(m_queueMutex, INFINITE);
m_dragging = true;
m_inputQueue->push_back(kid);
SetEvent(m_readEvent);
ReleaseMutex(m_queueMutex);
}
switch (g_hookData->m_mouseHookType) {
case MouseHookType_Wheel:
// For this type, g_hookData->m_mouseHookParam means
// translate rate mouse move to wheel.
mouse_event(MOUSEEVENTF_WHEEL, 0, 0,
g_hookData->m_mouseHookParam * dy, 0);
return 1;
break;
case MouseHookType_WindowMove: {
RECT curRect;
if (!GetWindowRect(target, &curRect))
return 0;
// g_hookData->m_mouseHookParam < 0 means
// target window to move is MDI.
if (g_hookData->m_mouseHookParam < 0) {
HWND parent = GetParent(target);
POINT p = {curRect.left, curRect.top};
if (parent == NULL || !ScreenToClient(parent, &p))
return 0;
curRect.left = p.x;
curRect.top = p.y;
}
SetWindowPos(target, NULL,
curRect.left + dx,
curRect.top + dy,
0, 0,
SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE |
SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER);
g_hookData->m_mousePos = i_mid->pt;
return 0;
break;
}
case MouseHookType_None:
default:
return 0;
break;
}
}
case WM_LBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
case WM_MBUTTONDBLCLK:
case WM_XBUTTONDBLCLK:
default:
return 0;
break;
}
WaitForSingleObject(m_queueMutex, INFINITE);
if (kid.Flags & KEYBOARD_INPUT_DATA::BREAK) {
m_buttonPressed = false;
if (m_dragging) {
KEYBOARD_INPUT_DATA kid2;
m_dragging = false;
kid2.UnitId = 0;
kid2.Flags = KEYBOARD_INPUT_DATA::E1 | KEYBOARD_INPUT_DATA::BREAK;
kid2.Reserved = 0;
kid2.ExtraInformation = 0;
kid2.MakeCode = 0;
m_inputQueue->push_back(kid2);
}
} else if (i_message != WM_MOUSEWHEEL && i_message != WM_MOUSEHWHEEL) {
m_buttonPressed = true;
m_msllHookCurrent = *i_mid;
}
m_inputQueue->push_back(kid);
if (i_message == WM_MOUSEWHEEL || i_message == WM_MOUSEHWHEEL) {
kid.UnitId = 0;
kid.Flags |= KEYBOARD_INPUT_DATA::BREAK;
kid.Reserved = 0;
kid.ExtraInformation = 0;
m_inputQueue->push_back(kid);
}
SetEvent(m_readEvent);
ReleaseMutex(m_queueMutex);
return 1;
}
}
// keyboard handler thread
unsigned int WINAPI Engine::keyboardHandler(void *i_this)
{
reinterpret_cast<Engine *>(i_this)->keyboardHandler();
_endthreadex(0);
return 0;
}
void Engine::keyboardHandler()
{
// loop
Key key;
while (1) {
KEYBOARD_INPUT_DATA kid;
WaitForSingleObject(m_queueMutex, INFINITE);
while (SignalObjectAndWait(m_queueMutex, m_readEvent, INFINITE, true) == WAIT_OBJECT_0) {
if (m_inputQueue == NULL) {
ReleaseMutex(m_queueMutex);
return;
}
if (m_inputQueue->empty()) {
ResetEvent(m_readEvent);
continue;
}
kid = m_inputQueue->front();
m_inputQueue->pop_front();
if (m_inputQueue->empty()) {
ResetEvent(m_readEvent);
}
break;
#if 0
case WAIT_OBJECT_0 + NUMBER_OF(handles): {
MSG message;
while (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) {
switch (message.message) {
case WM_APP + 201: {
if (message.wParam) {
m_currentLock.on(Modifier::Type_Touchpad);
m_currentLock.on(Modifier::Type_TouchpadSticky);
} else
m_currentLock.off(Modifier::Type_Touchpad);
Acquire a(&m_log, 1);
m_log << _T("touchpad: ") << message.wParam
<< _T(".") << (message.lParam & 0xffff)
<< _T(".") << (message.lParam >> 16 & 0xffff)
<< std::endl;
break;
}
default:
break;
}
}
goto rewait;
}
#endif
}
ReleaseMutex(m_queueMutex);
checkFocusWindow();
if (!m_setting || // m_setting has not been loaded
!m_isEnabled) { // disabled
if (m_isLogMode) {
Key key;
key.addScanCode(ScanCode(kid.MakeCode, kid.Flags));
outputToLog(&key, ModifiedKey(), 0);
if (kid.Flags & KEYBOARD_INPUT_DATA::E1) {
// through mouse event even if log mode
injectInput(&kid, NULL);
}
} else {
injectInput(&kid, NULL);
}
updateLastPressedKey(NULL);
continue;
}
Acquire a(&m_cs);
if (!m_currentFocusOfThread ||
!m_currentKeymap) {
injectInput(&kid, NULL);
Acquire a(&m_log, 0);
if (!m_currentFocusOfThread)
m_log << _T("internal error: m_currentFocusOfThread == NULL")
<< std::endl;
if (!m_currentKeymap)
m_log << _T("internal error: m_currentKeymap == NULL")
<< std::endl;
updateLastPressedKey(NULL);
continue;
}
Current c;
c.m_keymap = m_currentKeymap;
c.m_i = m_currentFocusOfThread->m_keymaps.begin();
// search key
key.addScanCode(ScanCode(kid.MakeCode, kid.Flags));
c.m_mkey = m_setting->m_keyboard.searchKey(key);
if (!c.m_mkey.m_key) {
c.m_mkey.m_key = m_setting->m_keyboard.searchPrefixKey(key);
if (c.m_mkey.m_key)
continue;
}
// press the key and update counter
bool isPhysicallyPressed
= !(key.getScanCodes()[0].m_flags & ScanCode::BREAK);
if (c.m_mkey.m_key) {
if (!c.m_mkey.m_key->m_isPressed && isPhysicallyPressed)
++ m_currentKeyPressCount;
else if (c.m_mkey.m_key->m_isPressed && !isPhysicallyPressed)
-- m_currentKeyPressCount;
c.m_mkey.m_key->m_isPressed = isPhysicallyPressed;
}
// create modifiers
c.m_mkey.m_modifier = getCurrentModifiers(c.m_mkey.m_key,
isPhysicallyPressed);
Keymap::AssignMode am;
bool isModifier = fixModifierKey(&c.m_mkey, &am);
if (m_isPrefix) {
if (isModifier && m_doesIgnoreModifierForPrefix)
am = Keymap::AM_true;
if (m_doesEditNextModifier) {
Modifier modifier = m_modifierForNextKey;
modifier.add(c.m_mkey.m_modifier);
c.m_mkey.m_modifier = modifier;
}
}
if (m_isLogMode) {
outputToLog(&key, c.m_mkey, 0);
if (kid.Flags & KEYBOARD_INPUT_DATA::E1) {
// through mouse event even if log mode
injectInput(&kid, NULL);
}
} else if (am == Keymap::AM_true) {
{
Acquire a(&m_log, 1);
m_log << _T("* true modifier") << std::endl;
}
// true modifier doesn't generate scan code
outputToLog(&key, c.m_mkey, 1);
} else if (am == Keymap::AM_oneShot || am == Keymap::AM_oneShotRepeatable) {
{
Acquire a(&m_log, 1);
if (am == Keymap::AM_oneShot)
m_log << _T("* one shot modifier") << std::endl;
else
m_log << _T("* one shot repeatable modifier") << std::endl;
}
// oneShot modifier doesn't generate scan code
outputToLog(&key, c.m_mkey, 1);
if (isPhysicallyPressed) {
if (am == Keymap::AM_oneShotRepeatable // the key is repeating
&& m_oneShotKey.m_key == c.m_mkey.m_key) {
if (m_oneShotRepeatableRepeatCount <
m_setting->m_oneShotRepeatableDelay) {
; // delay
} else {
Current cnew = c;
beginGeneratingKeyboardEvents(cnew, false);
}
++ m_oneShotRepeatableRepeatCount;
} else {
m_oneShotKey = c.m_mkey;
m_oneShotRepeatableRepeatCount = 0;
}
} else {
if (m_oneShotKey.m_key) {
Current cnew = c;
cnew.m_mkey.m_modifier = m_oneShotKey.m_modifier;
cnew.m_mkey.m_modifier.off(Modifier::Type_Up);
cnew.m_mkey.m_modifier.on(Modifier::Type_Down);
beginGeneratingKeyboardEvents(cnew, false);
cnew = c;
cnew.m_mkey.m_modifier = m_oneShotKey.m_modifier;
cnew.m_mkey.m_modifier.on(Modifier::Type_Up);
cnew.m_mkey.m_modifier.off(Modifier::Type_Down);
beginGeneratingKeyboardEvents(cnew, false);
}
m_oneShotKey.m_key = NULL;
m_oneShotRepeatableRepeatCount = 0;
}
} else if (c.m_mkey.m_key) {
// normal key
outputToLog(&key, c.m_mkey, 1);
if (isPhysicallyPressed)
m_oneShotKey.m_key = NULL;
beginGeneratingKeyboardEvents(c, isModifier);
} else {
// undefined key
if (kid.Flags & KEYBOARD_INPUT_DATA::E1) {
// through mouse event even if undefined for fail safe
injectInput(&kid, NULL);
}
}
// if counter is zero, reset modifiers and keys on win32
if (m_currentKeyPressCount <= 0) {
{
Acquire a(&m_log, 1);
m_log << _T("* No key is pressed") << std::endl;
}
generateModifierEvents(Modifier());
if (0 < m_currentKeyPressCountOnWin32)
keyboardResetOnWin32();
m_currentKeyPressCount = 0;
m_currentKeyPressCountOnWin32 = 0;
m_oneShotKey.m_key = NULL;
if (m_currentLock.isOn(Modifier::Type_Touchpad) == false)
m_currentLock.off(Modifier::Type_TouchpadSticky);
}
key.initialize();
updateLastPressedKey(isPhysicallyPressed ? c.m_mkey.m_key : NULL);
}
}
Engine::Engine(tomsgstream &i_log)
: m_hwndAssocWindow(NULL),
m_setting(NULL),
m_buttonPressed(false),
m_dragging(false),
m_keyboardHandler(installKeyboardHook, Engine::keyboardDetour),
m_mouseHandler(installMouseHook, Engine::mouseDetour),
m_inputQueue(NULL),
m_readEvent(NULL),
m_queueMutex(NULL),
m_sts4mayu(NULL),
m_cts4mayu(NULL),
m_isLogMode(false),
m_isEnabled(true),
m_isSynchronizing(false),
m_eSync(NULL),
m_generateKeyboardEventsRecursionGuard(0),
m_currentKeyPressCount(0),
m_currentKeyPressCountOnWin32(0),
m_lastGeneratedKey(NULL),
m_oneShotRepeatableRepeatCount(0),
m_isPrefix(false),
m_currentKeymap(NULL),
m_currentFocusOfThread(NULL),
m_hwndFocus(NULL),
m_afShellExecute(NULL),
m_variable(0),
m_log(i_log) {
BOOL (WINAPI *pChangeWindowMessageFilter)(UINT, DWORD) =
reinterpret_cast<BOOL (WINAPI*)(UINT, DWORD)>(GetProcAddress(GetModuleHandle(_T("user32.dll")), "ChangeWindowMessageFilter"));
if(pChangeWindowMessageFilter != NULL) {
pChangeWindowMessageFilter(WM_COPYDATA, MSGFLT_ADD);
}
for (size_t i = 0; i < NUMBER_OF(m_lastPressedKey); ++ i)
m_lastPressedKey[i] = NULL;
// set default lock state
for (int i = 0; i < Modifier::Type_end; ++ i)
m_currentLock.dontcare(static_cast<Modifier::Type>(i));
for (int i = Modifier::Type_Lock0; i <= Modifier::Type_Lock9; ++ i)
m_currentLock.release(static_cast<Modifier::Type>(i));
// create event for sync
CHECK_TRUE( m_eSync = CreateEvent(NULL, FALSE, FALSE, NULL) );
// create named pipe for &SetImeString
m_hookPipe = CreateNamedPipe(addSessionId(HOOK_PIPE_NAME).c_str(),
PIPE_ACCESS_OUTBOUND,
PIPE_TYPE_BYTE, 1,
0, 0, 0, NULL);
StrExprArg::setEngine(this);
m_msllHookCurrent.pt.x = 0;
m_msllHookCurrent.pt.y = 0;
m_msllHookCurrent.mouseData = 0;
m_msllHookCurrent.flags = 0;
m_msllHookCurrent.time = 0;
m_msllHookCurrent.dwExtraInfo = 0;
}
// start keyboard handler thread
void Engine::start() {
m_keyboardHandler.start(this);
m_mouseHandler.start(this);
CHECK_TRUE( m_inputQueue = new std::deque<KEYBOARD_INPUT_DATA> );
CHECK_TRUE( m_queueMutex = CreateMutex(NULL, FALSE, NULL) );
CHECK_TRUE( m_readEvent = CreateEvent(NULL, TRUE, FALSE, NULL) );
m_ol.Offset = 0;
m_ol.OffsetHigh = 0;
m_ol.hEvent = m_readEvent;
CHECK_TRUE( m_threadHandle = (HANDLE)_beginthreadex(NULL, 0, keyboardHandler, this, 0, &m_threadId) );
}
// stop keyboard handler thread
void Engine::stop() {
m_mouseHandler.stop();
m_keyboardHandler.stop();
WaitForSingleObject(m_queueMutex, INFINITE);
delete m_inputQueue;
m_inputQueue = NULL;
SetEvent(m_readEvent);
ReleaseMutex(m_queueMutex);
WaitForSingleObject(m_threadHandle, 2000);
CHECK_TRUE( CloseHandle(m_threadHandle) );
m_threadHandle = NULL;
CHECK_TRUE( CloseHandle(m_readEvent) );
m_readEvent = NULL;
for (ThreadIds::iterator i = m_attachedThreadIds.begin();
i != m_attachedThreadIds.end(); i++) {
PostThreadMessage(*i, WM_NULL, 0, 0);
}
}
bool Engine::prepairQuit() {
// terminate and unload DLL for ThumbSense support if loaded
manageTs4mayu(_T("sts4mayu.dll"), _T("SynCOM.dll"),
false, &m_sts4mayu);
manageTs4mayu(_T("cts4mayu.dll"), _T("TouchPad.dll"),
false, &m_cts4mayu);
return true;
}
Engine::~Engine() {
CHECK_TRUE( CloseHandle(m_eSync) );
// destroy named pipe for &SetImeString
if (m_hookPipe && m_hookPipe != INVALID_HANDLE_VALUE) {
DisconnectNamedPipe(m_hookPipe);
CHECK_TRUE( CloseHandle(m_hookPipe) );
}
}
void Engine::manageTs4mayu(TCHAR *i_ts4mayuDllName,
TCHAR *i_dependDllName,
bool i_load, HMODULE *i_pTs4mayu) {
Acquire a(&m_log, 0);
if (i_load == false) {
if (*i_pTs4mayu) {
bool (WINAPI *pTs4mayuTerm)();
pTs4mayuTerm = (bool (WINAPI*)())GetProcAddress(*i_pTs4mayu, "ts4mayuTerm");
if (pTs4mayuTerm() == true)
FreeLibrary(*i_pTs4mayu);
*i_pTs4mayu = NULL;
m_log << i_ts4mayuDllName <<_T(" unloaded") << std::endl;
}
} else {
if (*i_pTs4mayu) {
m_log << i_ts4mayuDllName << _T(" already loaded") << std::endl;
} else {
if (SearchPath(NULL, i_dependDllName, NULL, 0, NULL, NULL) == 0) {
m_log << _T("load ") << i_ts4mayuDllName
<< _T(" failed: can't find ") << i_dependDllName
<< std::endl;
} else {
*i_pTs4mayu = LoadLibrary(i_ts4mayuDllName);
if (*i_pTs4mayu == NULL) {
m_log << _T("load ") << i_ts4mayuDllName
<< _T(" failed: can't find it") << std::endl;
} else {
bool (WINAPI *pTs4mayuInit)(UINT);
pTs4mayuInit = (bool (WINAPI*)(UINT))GetProcAddress(*i_pTs4mayu, "ts4mayuInit");
if (pTs4mayuInit(m_threadId) == true)
m_log << i_ts4mayuDllName <<_T(" loaded") << std::endl;
else
m_log << i_ts4mayuDllName
<<_T(" load failed: can't initialize") << std::endl;
}
}
}
}
}
// set m_setting
bool Engine::setSetting(Setting *i_setting) {
Acquire a(&m_cs);
if (m_isSynchronizing)
return false;
if (m_setting) {
for (Keyboard::KeyIterator i = m_setting->m_keyboard.getKeyIterator();
*i; ++ i) {
Key *key = i_setting->m_keyboard.searchKey(*(*i));
if (key) {
key->m_isPressed = (*i)->m_isPressed;
key->m_isPressedOnWin32 = (*i)->m_isPressedOnWin32;
key->m_isPressedByAssign = (*i)->m_isPressedByAssign;
}
}
if (m_lastGeneratedKey)
m_lastGeneratedKey =
i_setting->m_keyboard.searchKey(*m_lastGeneratedKey);
for (size_t i = 0; i < NUMBER_OF(m_lastPressedKey); ++ i)
if (m_lastPressedKey[i])
m_lastPressedKey[i] =
i_setting->m_keyboard.searchKey(*m_lastPressedKey[i]);
}
m_setting = i_setting;
manageTs4mayu(_T("sts4mayu.dll"), _T("SynCOM.dll"),
m_setting->m_sts4mayu, &m_sts4mayu);
manageTs4mayu(_T("cts4mayu.dll"), _T("TouchPad.dll"),
m_setting->m_cts4mayu, &m_cts4mayu);
g_hookData->m_correctKanaLockHandling = m_setting->m_correctKanaLockHandling;
if (m_currentFocusOfThread) {
for (FocusOfThreads::iterator i = m_focusOfThreads.begin();
i != m_focusOfThreads.end(); i ++) {
FocusOfThread *fot = &(*i).second;
m_setting->m_keymaps.searchWindow(&fot->m_keymaps,
fot->m_className, fot->m_titleName);
}
}
m_setting->m_keymaps.searchWindow(&m_globalFocus.m_keymaps, _T(""), _T(""));
if (m_globalFocus.m_keymaps.empty()) {
Acquire a(&m_log, 0);
m_log << _T("internal error: m_globalFocus.m_keymap is empty")
<< std::endl;
}
m_currentFocusOfThread = &m_globalFocus;
setCurrentKeymap(m_globalFocus.m_keymaps.front());
m_hwndFocus = NULL;
return true;
}
void Engine::checkShow(HWND i_hwnd) {
// update show style of window
// this update should be done in hook DLL, but to
// avoid update-loss for some applications(such as
// cmd.exe), we update here.
bool isMaximized = false;
bool isMinimized = false;
bool isMDIMaximized = false;
bool isMDIMinimized = false;
while (i_hwnd) {
#ifdef MAYU64
LONG_PTR exStyle = GetWindowLongPtr(i_hwnd, GWL_EXSTYLE);
#else
LONG exStyle = GetWindowLong(i_hwnd, GWL_EXSTYLE);
#endif
if (exStyle & WS_EX_MDICHILD) {
WINDOWPLACEMENT placement;
placement.length = sizeof(WINDOWPLACEMENT);
if (GetWindowPlacement(i_hwnd, &placement)) {
switch (placement.showCmd) {
case SW_SHOWMAXIMIZED:
isMDIMaximized = true;
break;
case SW_SHOWMINIMIZED:
isMDIMinimized = true;
break;
case SW_SHOWNORMAL:
default:
break;
}
}
}
#ifdef MAYU64
LONG_PTR style = GetWindowLongPtr(i_hwnd, GWL_STYLE);
#else
LONG style = GetWindowLong(i_hwnd, GWL_STYLE);
#endif
if ((style & WS_CHILD) == 0) {
WINDOWPLACEMENT placement;
placement.length = sizeof(WINDOWPLACEMENT);
if (GetWindowPlacement(i_hwnd, &placement)) {
switch (placement.showCmd) {
case SW_SHOWMAXIMIZED:
isMaximized = true;
break;
case SW_SHOWMINIMIZED:
isMinimized = true;
break;
case SW_SHOWNORMAL:
default:
break;
}
}
}
i_hwnd = GetParent(i_hwnd);
}
setShow(isMDIMaximized, isMDIMinimized, true);
setShow(isMaximized, isMinimized, false);
}
// focus
bool Engine::setFocus(HWND i_hwndFocus, DWORD i_threadId,
const tstringi &i_className, const tstringi &i_titleName,
bool i_isConsole) {
Acquire a(&m_cs);
if (m_isSynchronizing)
return false;
if (i_hwndFocus == NULL)
return true;
// remove newly created thread's id from m_detachedThreadIds
if (!m_detachedThreadIds.empty()) {
ThreadIds::iterator i;
bool retry;
do {
retry = false;
for (i = m_detachedThreadIds.begin();
i != m_detachedThreadIds.end(); ++ i)
if (*i == i_threadId) {
m_detachedThreadIds.erase(i);
retry = true;
break;
}
} while (retry);
}
FocusOfThread *fot;
FocusOfThreads::iterator i = m_focusOfThreads.find(i_threadId);
if (i != m_focusOfThreads.end()) {
fot = &(*i).second;
if (fot->m_hwndFocus == i_hwndFocus &&
fot->m_isConsole == i_isConsole &&
fot->m_className == i_className &&
fot->m_titleName == i_titleName)
return true;
} else {
i = m_focusOfThreads.insert(
FocusOfThreads::value_type(i_threadId, FocusOfThread())).first;
fot = &(*i).second;
fot->m_threadId = i_threadId;
}
fot->m_hwndFocus = i_hwndFocus;
fot->m_isConsole = i_isConsole;
fot->m_className = i_className;
fot->m_titleName = i_titleName;
if (m_setting) {
m_setting->m_keymaps.searchWindow(&fot->m_keymaps,
i_className, i_titleName);
ASSERT(0 < fot->m_keymaps.size());
} else
fot->m_keymaps.clear();
checkShow(i_hwndFocus);
return true;
}
// lock state
bool Engine::setLockState(bool i_isNumLockToggled,
bool i_isCapsLockToggled,
bool i_isScrollLockToggled,
bool i_isKanaLockToggled,
bool i_isImeLockToggled,
bool i_isImeCompToggled) {
Acquire a(&m_cs);
if (m_isSynchronizing)
return false;
m_currentLock.on(Modifier::Type_NumLock, i_isNumLockToggled);
m_currentLock.on(Modifier::Type_CapsLock, i_isCapsLockToggled);
m_currentLock.on(Modifier::Type_ScrollLock, i_isScrollLockToggled);
m_currentLock.on(Modifier::Type_KanaLock, i_isKanaLockToggled);
m_currentLock.on(Modifier::Type_ImeLock, i_isImeLockToggled);
m_currentLock.on(Modifier::Type_ImeComp, i_isImeCompToggled);
return true;
}
// show
bool Engine::setShow(bool i_isMaximized, bool i_isMinimized,
bool i_isMDI) {
Acquire a(&m_cs);
if (m_isSynchronizing)
return false;
Acquire b(&m_log, 1);
Modifier::Type max, min;
if (i_isMDI == true) {
max = Modifier::Type_MdiMaximized;
min = Modifier::Type_MdiMinimized;
} else {
max = Modifier::Type_Maximized;
min = Modifier::Type_Minimized;
}
m_currentLock.on(max, i_isMaximized);
m_currentLock.on(min, i_isMinimized);
m_log << _T("Set show to ") << (i_isMaximized ? _T("Maximized") :
i_isMinimized ? _T("Minimized") : _T("Normal"));
if (i_isMDI == true) {
m_log << _T(" (MDI)");
}
m_log << std::endl;
return true;
}
// sync
bool Engine::syncNotify() {
Acquire a(&m_cs);
if (!m_isSynchronizing)
return false;
CHECK_TRUE( SetEvent(m_eSync) );
return true;
}
// thread attach notify
bool Engine::threadAttachNotify(DWORD i_threadId) {
Acquire a(&m_cs);
m_attachedThreadIds.push_back(i_threadId);
return true;
}
// thread detach notify
bool Engine::threadDetachNotify(DWORD i_threadId) {
Acquire a(&m_cs);
m_detachedThreadIds.push_back(i_threadId);
m_attachedThreadIds.erase(remove(m_attachedThreadIds.begin(), m_attachedThreadIds.end(), i_threadId),
m_attachedThreadIds.end());
return true;
}
// get help message
void Engine::getHelpMessages(tstring *o_helpMessage, tstring *o_helpTitle) {
Acquire a(&m_cs);
*o_helpMessage = m_helpMessage;
*o_helpTitle = m_helpTitle;
}
unsigned int WINAPI Engine::InputHandler::run(void *i_this)
{
reinterpret_cast<InputHandler*>(i_this)->run();
_endthreadex(0);
return 0;
}
Engine::InputHandler::InputHandler(INSTALL_HOOK i_installHook, INPUT_DETOUR i_inputDetour)
: m_installHook(i_installHook), m_inputDetour(i_inputDetour)
{
CHECK_TRUE(m_hEvent = CreateEvent(NULL, FALSE, FALSE, NULL));
CHECK_TRUE(m_hThread = (HANDLE)_beginthreadex(NULL, 0, run, this, CREATE_SUSPENDED, &m_threadId));
}
Engine::InputHandler::~InputHandler()
{
CloseHandle(m_hEvent);
}
void Engine::InputHandler::run()
{
MSG msg;
CHECK_FALSE(m_installHook(m_inputDetour, m_engine, true));
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
SetEvent(m_hEvent);
while (GetMessage(&msg, NULL, 0, 0)) {
// nothing to do...
}
CHECK_FALSE(m_installHook(m_inputDetour, m_engine, false));
return;
}
int Engine::InputHandler::start(Engine *i_engine)
{
m_engine = i_engine;
ResumeThread(m_hThread);
WaitForSingleObject(m_hEvent, INFINITE);
return 0;
}
int Engine::InputHandler::stop()
{
PostThreadMessage(m_threadId, WM_QUIT, 0, 0);
WaitForSingleObject(m_hThread, INFINITE);
return 0;
}
<file_sep>var files = new Array("yamy.ini", "104.mayu", "109.mayu", "default.mayu", "emacsedit.mayu", "104on109.mayu", "109on104.mayu", "dot.mayu", "workaround.mayu", "workaround.reg", "readme.txt", "yamy.exe", "yamy32", "yamy32.dll", "yamyd32", "yamy64", "yamy64.dll");
var config = WScript.Arguments.Item(0); // "Debug" or "Release"
var version = WScript.Arguments.Item(1); // x.yz
if (config == null | version == null) {
throw new Error("usage: CScirpt.exe makedistrib.js {Debug | Release} <version>");
}
var targetDir = "..\\" + config + "\\";
var pkgFile = "yamy-" + version + ".zip";
function ProcessFiles(dir, files, process) {
for (var i = 0; i < files.length; i++) {
process(dir, files[i]);
}
}
var RemoveFile = function(dir, name) {
var path = dir + name;
if (fso.FileExists(path)) {
fso.DeleteFile(path);
}
};
var fso = WScript.CreateObject("Scripting.FileSystemObject");
if (fso == null) {
throw new Error("can't create File System Object!");
}
var shell = WScript.CreateObject("Shell.Application");
if (fso == null) {
throw new Error("can't create Shell Application Object!");
}
if (fso.FolderExists(targetDir) == false) {
fso.CreateFolder(targetDir);
}
RemoveFile(targetDir, pkgFile);
var file = fso.CreateTextFile(targetDir + pkgFile, true);
file.Write("PK\x05\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00");
file.Close();
var targetZip = shell.NameSpace(fso.GetAbsolutePathName(targetDir + pkgFile));
var PackFile = function(dir, name) {
var path = dir + name;
if (fso.FileExists(path) == false) {
RemoveFile(targetDir, pkgFile);
throw new Error("can't pack " + path + "!");
}
var item = shell.NameSpace(fso.GetAbsolutePathName(path) + "\\..\\").ParseName(name);
var count = targetZip.Items().Count;
targetZip.CopyHere(item);
while (targetZip.Items().Count != count + 1) {
WScript.Sleep(100);
}
};
ProcessFiles(targetDir, files, PackFile);
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// vkeytable.h
#ifndef _VKEYTABLE_H
# define _VKEYTABLE_H
# include "misc.h"
# include <tchar.h>
/// define virtual key code and its name
class VKeyTable
{
public:
u_int8 m_code; /// VKey code
const _TCHAR *m_name; /// VKey name
};
extern const VKeyTable g_vkeyTable[]; /** Vkey table (terminated by
NULL) */
#endif // !_VKEYTABLE_H
<file_sep>//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by mayu.rc
//
#define IDS_mayu 1
#define IDS_mayuAlreadyExists 2
#define IDS_cannotOpenDevice 3
#define IDS_driverNotInstalled 4
#define IDS_executedInRemoteDesktop 5
#define IDS_openMayu 10
#define IDS_openMayuFilter 11
#define IDS_helpFilename 12
#define IDS_mayuFile 13
#define IDS_mayuShellOpen 14
#define IDS_readFromHomeDirectory 15
#define IDS_logFont 16
#define IDS_109Emacs 17
#define IDS_104on109Emacs 18
#define IDS_109 19
#define IDS_104on109 20
#define IDS_104Emacs 21
#define IDS_109on104Emacs 22
#define IDS_104 23
#define IDS_109on104 24
#define IDS_mayuPathName 25
#define IDS_mayuPath 26
#define IDS_mayuSymbols 27
#define IDS_version 28
#define IDS_homepage 29
#define IDS_cannotInvoke 30
#define IDS_cannotPermitStandardUser 31
#define IDS_escapeNlsKeysFailed 32
#define IDS_escapeNlsKeysRetry 33
#define IDC_CURSOR_target 101
#define IDD_DIALOG_editSetting 102
#define IDD_DIALOG_investigate 103
#define IDD_DIALOG_log 104
#define IDD_DIALOG_setting 105
#define IDD_DIALOG_version 106
#define IDI_ICON_mayu 107
#define IDI_ICON_mayu_file 108
#define IDI_ICON_mayu_disabled 109
#define IDR_MENU_tasktray 110
#define IDC_BUTTON_add 1001
#define IDC_BUTTON_browse 1002
#define IDC_BUTTON_changeFont 1003
#define IDC_BUTTON_clearLog 1004
#define IDC_BUTTON_delete 1005
#define IDC_BUTTON_down 1006
#define IDC_BUTTON_download 1007
#define IDC_BUTTON_edit 1008
#define IDC_BUTTON_up 1009
#define IDC_CHECK_detail 1010
#define IDC_CUSTOM_scancode 1011
#define IDC_CUSTOM_target 1012
#define IDC_CUSTOM_vkey 1013
#define IDC_EDIT_log 1014
#define IDC_EDIT_mayuPath 1015
#define IDC_EDIT_mayuPathName 1016
#define IDC_EDIT_symbols 1017
#define IDC_LIST_mayuPaths 1018
#define IDC_STATIC_mayuPath 1019
#define IDC_STATIC_mayuPathName 1020
#define IDC_STATIC_mayuPathNameComment 1021
#define IDC_STATIC_mayuPaths 1022
#define IDC_STATIC_symbols 1023
#define IDC_STATIC_symbolsComment 1024
#define IDC_STATIC_url 1025
#define IDC_STATIC_version 1026
#define IDC_EDIT_builtBy 1027
#define IDC_STATIC_mayuIcon 1028
#define ID_MENUITEM_quit 40001
#define ID_MENUITEM_reload 40002
#define ID_MENUITEM_setting 40003
#define ID_MENUITEM_investigate 40004
#define ID_MENUITEM_version 40005
#define ID_MENUITEM_help 40006
#define ID_MENUITEM_disable 40007
#define ID_MENUITEM_log 40008
#define ID_MENUITEM_check 40009
#define IDC_STATIC -1
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 103
#define _APS_NEXT_COMMAND_VALUE 40012
#define _APS_NEXT_CONTROL_VALUE 1029
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by setup.rc
//
#define IDS_mayuSetup 1
#define IDS_mayuRunning 2
#define IDS_mayuEmpty 3
#define IDS_selectDir 4
#define IDS_invalidDirectory 5
#define IDS_removeOk 6
#define IDS_removeFinish 7
#define IDS_copyFinish 8
#define IDS_error 9
#define IDS_alreadyUninstalled 10
#define IDS_notAdministrator 11
#define IDS_invalidOS 12
#define IDS_mayuFile 13
#define IDS_mayuShellOpen 14
#define IDS_mayu 15
#define IDS_mayud 16
#define IDS_shortcutName 17
#define IDS_keyboard109usb 20
#define IDS_keyboard104usb 21
#define IDS_readFromHomeDirectory 22
#define IDS_note01 30
#define IDS_note02 31
#define IDS_note03 32
#define IDS_note04 33
#define IDS_note05 34
#define IDS_note06 35
#define IDS_note07 36
#define IDS_note08 37
#define IDS_note09 38
#define IDS_note10 39
#define IDS_note11 40
#define IDS_note12 41
#define IDS_note13 42
#define IDS_copyFinishUsb 43
#define IDS_failedToReboot 44
#define IDD_DIALOG_main 101
#define IDI_ICON_mayu 102
#define IDC_EDIT_path 1000
#define IDC_BUTTON_browse 1001
#define IDC_CHECK_registerStartMenu 1002
#define IDC_CHECK_registerStartUp 1003
#define IDC_COMBO_keyboard 1004
#define IDC_EDIT_note 1005
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 1
#define _APS_NEXT_RESOURCE_VALUE 103
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1006
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// keymap.h
#ifndef _FUNCTION_H
# define _FUNCTION_H
class SettingLoader;
class Engine;
class FunctionParam;
///
class FunctionData
{
public:
/// virtual destructor
virtual ~FunctionData() = 0;
///
virtual void load(SettingLoader *i_sl) = 0;
///
virtual void exec(Engine *i_engine, FunctionParam *i_param) const = 0;
///
virtual const _TCHAR *getName() const = 0;
///
virtual tostream &output(tostream &i_ost) const = 0;
///
virtual FunctionData *clone() const = 0;
};
/// stream output
extern tostream &operator<<(tostream &i_ost, const FunctionData *i_data);
// create function
extern FunctionData *createFunctionData(const tstring &i_name);
///
enum VKey {
VKey_extended = 0x100, ///
VKey_released = 0x200, ///
VKey_pressed = 0x400, ///
};
/// stream output
extern tostream &operator<<(tostream &i_ost, VKey i_data);
///
enum ToWindowType {
ToWindowType_toBegin = -2, ///
ToWindowType_toMainWindow = -2, ///
ToWindowType_toOverlappedWindow = -1, ///
ToWindowType_toItself = 0, ///
ToWindowType_toParentWindow = 1, ///
};
/// stream output
extern tostream &operator<<(tostream &i_ost, ToWindowType i_data);
// get value of ToWindowType
extern bool getTypeValue(ToWindowType *o_type, const tstring &i_name);
///
enum GravityType {
GravityType_C = 0, /// center
GravityType_N = 1 << 0, /// north
GravityType_E = 1 << 1, /// east
GravityType_W = 1 << 2, /// west
GravityType_S = 1 << 3, /// south
GravityType_NW = GravityType_N | GravityType_W, /// north west
GravityType_NE = GravityType_N | GravityType_E, /// north east
GravityType_SW = GravityType_S | GravityType_W, /// south west
GravityType_SE = GravityType_S | GravityType_E, /// south east
};
/// stream output
extern tostream &operator<<(tostream &i_ost, GravityType i_data);
/// get value of GravityType
extern bool getTypeValue(GravityType *o_type, const tstring &i_name);
/// enum MouseHookType is defined in hook.h
extern enum MouseHookType;
/// stream output
extern tostream &operator<<(tostream &i_ost, MouseHookType i_data);
/// get value of MouseHookType
extern bool getTypeValue(MouseHookType *o_type, const tstring &i_name);
///
enum MayuDialogType {
MayuDialogType_investigate = 0x10000, ///
MayuDialogType_log = 0x20000, ///
MayuDialogType_mask = 0xffff0000, ///
};
/// stream output
extern tostream &operator<<(tostream &i_ost, MayuDialogType i_data);
// get value of MayuDialogType
bool getTypeValue(MayuDialogType *o_type, const tstring &i_name);
///
enum ModifierLockType {
ModifierLockType_Lock0 = Modifier::Type_Lock0, ///
ModifierLockType_Lock1 = Modifier::Type_Lock1, ///
ModifierLockType_Lock2 = Modifier::Type_Lock2, ///
ModifierLockType_Lock3 = Modifier::Type_Lock3, ///
ModifierLockType_Lock4 = Modifier::Type_Lock4, ///
ModifierLockType_Lock5 = Modifier::Type_Lock5, ///
ModifierLockType_Lock6 = Modifier::Type_Lock6, ///
ModifierLockType_Lock7 = Modifier::Type_Lock7, ///
ModifierLockType_Lock8 = Modifier::Type_Lock8, ///
ModifierLockType_Lock9 = Modifier::Type_Lock9, ///
};
///
enum ToggleType {
ToggleType_toggle = -1, ///
ToggleType_off = 0, ///
ToggleType_on = 1, ///
};
/// stream output
extern tostream &operator<<(tostream &i_ost, ToggleType i_data);
// get value of ShowCommandType
extern bool getTypeValue(ToggleType *o_type, const tstring &i_name);
/// stream output
extern tostream &operator<<(tostream &i_ost, ModifierLockType i_data);
// get value of ModifierLockType
extern bool getTypeValue(ModifierLockType *o_type, const tstring &i_name);
///
enum ShowCommandType {
ShowCommandType_hide = SW_HIDE, ///
ShowCommandType_maximize = SW_MAXIMIZE, ///
ShowCommandType_minimize = SW_MINIMIZE, ///
ShowCommandType_restore = SW_RESTORE, ///
ShowCommandType_show = SW_SHOW, ///
ShowCommandType_showDefault = SW_SHOWDEFAULT, ///
ShowCommandType_showMaximized = SW_SHOWMAXIMIZED, ///
ShowCommandType_showMinimized = SW_SHOWMINIMIZED, ///
ShowCommandType_showMinNoActive = SW_SHOWMINNOACTIVE, ///
ShowCommandType_showNA = SW_SHOWNA, ///
ShowCommandType_showNoActivate = SW_SHOWNOACTIVATE, ///
ShowCommandType_showNormal = SW_SHOWNORMAL, ///
};
/// stream output
extern tostream &operator<<(tostream &i_ost, ShowCommandType i_data);
// get value of ShowCommandType
extern bool getTypeValue(ShowCommandType *o_type, const tstring &i_name);
///
enum TargetWindowType {
TargetWindowType_overlapped = 0, ///
TargetWindowType_mdi = 1, ///
};
/// stream output
extern tostream &operator<<(tostream &i_ost, TargetWindowType i_data);
// get value of ShowCommandType
extern bool getTypeValue(TargetWindowType *o_type, const tstring &i_name);
///
enum BooleanType {
BooleanType_false = 0, ///
BooleanType_true = 1, ///
};
/// stream output
extern tostream &operator<<(tostream &i_ost, BooleanType i_data);
// get value of ShowCommandType
extern bool getTypeValue(BooleanType *o_type, const tstring &i_name);
///
enum LogicalOperatorType {
LogicalOperatorType_or = 0, ///
LogicalOperatorType_and = 1, ///
};
/// stream output
extern tostream &operator<<(tostream &i_ost, LogicalOperatorType i_data);
// get value of LogicalOperatorType
extern bool getTypeValue(LogicalOperatorType *o_type, const tstring &i_name);
///
enum WindowMonitorFromType {
WindowMonitorFromType_primary = 0, ///
WindowMonitorFromType_current = 1, ///
};
// stream output
extern tostream &operator<<(tostream &i_ost, WindowMonitorFromType i_data);
// get value of WindowMonitorFromType
extern bool getTypeValue(WindowMonitorFromType *o_type, const tstring &i_name);
/// stream output
extern tostream &operator<<(tostream &i_ost,
const std::list<tstringq> &i_data);
/// string type expression
class StrExpr;
/// string type expression for function arguments
class StrExprArg
{
private:
StrExpr *m_expr;
public:
enum Type {
Literal,
Builtin,
};
StrExprArg();
StrExprArg(const StrExprArg &i_data);
StrExprArg(const tstringq &i_symbol, Type i_type);
~StrExprArg();
StrExprArg &operator=(const StrExprArg &i_data);
tstringq eval() const;
static void setEngine(const Engine *i_engine);
};
/// stream output
tostream &operator<<(tostream &i_ost, const StrExprArg &i_data);
#endif // !_FUNCTION_H
<file_sep>!include $(NTMAKEENV)\makefile.def
clean:
-del buildfre.log
-del i386\mayud.sys
-del i386\mayud.pdb
-del obj\_objects.mac
-del objfre\i386\*.obj
-del objfre\i386\*.mac
-del objfre_wxp_x86\i386\*.obj
-del objfre_wxp_x86\*.mac
-del *~
-rd obj
-rd objfre\i386
-rd objfre
-rd objfre_wxp_x86\i386
-rd objfre_wxp_x86
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// setting.h
#ifndef _SETTING_H
# define _SETTING_H
# include "keymap.h"
# include "parser.h"
# include "multithread.h"
# include <set>
/// this class contains all of loaded settings
class Setting
{
public:
typedef std::set<tstringi> Symbols; ///
typedef std::list<Modifier> Modifiers; ///
public:
Keyboard m_keyboard; ///
Keymaps m_keymaps; ///
KeySeqs m_keySeqs; ///
Symbols m_symbols; ///
bool m_correctKanaLockHandling; ///
bool m_sts4mayu; ///
bool m_cts4mayu; ///
bool m_mouseEvent; ///
LONG m_dragThreshold; ///
unsigned int m_oneShotRepeatableDelay; ///
public:
Setting()
: m_correctKanaLockHandling(false),
m_sts4mayu(false),
m_cts4mayu(false),
m_mouseEvent(false),
m_dragThreshold(0),
m_oneShotRepeatableDelay(0) { }
};
///
namespace Event
{
///
extern Key prefixed;
///
extern Key before_key_down;
///
extern Key after_key_up;
///
extern Key *events[];
}
///
class SettingLoader
{
# define FUNCTION_FRIEND
# include "functions.h"
# undef FUNCTION_FRIEND
public:
///
class FunctionCreator
{
public:
const _TCHAR *m_name; ///
FunctionData *m_creator; ///
};
private:
typedef std::vector<Token> Tokens; ///
typedef std::vector<tstringi> Prefixes; ///
typedef std::vector<bool> CanReadStack; ///
private:
Setting *m_setting; /// loaded setting
bool m_isThereAnyError; /// is there any error ?
SyncObject *m_soLog; /// guard log output stream
tostream *m_log; /// log output stream
tstringi m_currentFilename; /// current filename
Tokens m_tokens; /// tokens for current line
Tokens::iterator m_ti; /// current processing token
static Prefixes *m_prefixes; /// prefix terminal symbol
static size_t m_prefixesRefCcount; /// reference count of prefix
Keymap *m_currentKeymap; /// current keymap
CanReadStack m_canReadStack; /// for <COND_SYMBOL>
Modifier m_defaultAssignModifier; /** default
<ASSIGN_MODIFIER> */
Modifier m_defaultKeySeqModifier; /** default
<KEYSEQ_MODIFIER> */
private:
bool isEOL(); /// is there no more tokens ?
Token *getToken(); /// get next token
Token *lookToken(); /// look next token
bool getOpenParen(bool i_doesThrow, const _TCHAR *i_name); /// argument "("
bool getCloseParen(bool i_doesThrow, const _TCHAR *i_name); /// argument ")"
bool getComma(bool i_doesThrow, const _TCHAR *i_name); /// argument ","
void load_LINE(); /// <LINE>
void load_DEFINE(); /// <DEFINE>
void load_IF(); /// <IF>
void load_ELSE(bool i_isElseIf, const tstringi &i_token);
/// <ELSE> <ELSEIF>
bool load_ENDIF(const tstringi &i_token); /// <ENDIF>
void load_INCLUDE(); /// <INCLUDE>
void load_SCAN_CODES(Key *o_key); /// <SCAN_CODES>
void load_DEFINE_KEY(); /// <DEFINE_KEY>
void load_DEFINE_MODIFIER(); /// <DEFINE_MODIFIER>
void load_DEFINE_SYNC_KEY(); /// <DEFINE_SYNC_KEY>
void load_DEFINE_ALIAS(); /// <DEFINE_ALIAS>
void load_DEFINE_SUBSTITUTE(); /// <DEFINE_SUBSTITUTE>
void load_DEFINE_OPTION(); /// <DEFINE_OPTION>
void load_KEYBOARD_DEFINITION(); /// <KEYBOARD_DEFINITION>
Modifier load_MODIFIER(Modifier::Type i_mode, Modifier i_modifier,
Modifier::Type *o_mode = NULL);
/// <..._MODIFIER>
Key *load_KEY_NAME(); /// <KEY_NAME>
void load_KEYMAP_DEFINITION(const Token *i_which);
/// <KEYMAP_DEFINITION>
void load_ARGUMENT(bool *o_arg); /// <ARGUMENT>
void load_ARGUMENT(int *o_arg); /// <ARGUMENT>
void load_ARGUMENT(unsigned int *o_arg); /// <ARGUMENT>
void load_ARGUMENT(long *o_arg); /// <ARGUMENT>
void load_ARGUMENT(unsigned __int64 *o_arg); /// <ARGUMENT>
void load_ARGUMENT(__int64 *o_arg); /// <ARGUMENT>
void load_ARGUMENT(tstringq *o_arg); /// <ARGUMENT>
void load_ARGUMENT(std::list<tstringq> *o_arg); /// <ARGUMENT>
void load_ARGUMENT(tregex *o_arg); /// <ARGUMENT>
void load_ARGUMENT(VKey *o_arg); /// <ARGUMENT_VK>
void load_ARGUMENT(ToWindowType *o_arg); /// <ARGUMENT_WINDOW>
void load_ARGUMENT(GravityType *o_arg); /// <ARGUMENT>
void load_ARGUMENT(MouseHookType *o_arg); /// <ARGUMENT>
void load_ARGUMENT(MayuDialogType *o_arg); /// <ARGUMENT>
void load_ARGUMENT(ModifierLockType *o_arg); /// <ARGUMENT_LOCK>
void load_ARGUMENT(ToggleType *o_arg); /// <ARGUMENT>
void load_ARGUMENT(ShowCommandType *o_arg); ///<ARGUMENT_SHOW_WINDOW>
void load_ARGUMENT(TargetWindowType *o_arg);
/// <ARGUMENT_TARGET_WINDOW_TYPE>
void load_ARGUMENT(BooleanType *o_arg); /// <bool>
void load_ARGUMENT(LogicalOperatorType *o_arg);/// <ARGUMENT>
void load_ARGUMENT(Modifier *o_arg); /// <ARGUMENT>
void load_ARGUMENT(const Keymap **o_arg); /// <ARGUMENT>
void load_ARGUMENT(const KeySeq **o_arg); /// <ARGUMENT>
void load_ARGUMENT(StrExprArg *o_arg); /// <ARGUMENT>
void load_ARGUMENT(WindowMonitorFromType *o_arg); /// <ARGUMENT>
KeySeq *load_KEY_SEQUENCE(
const tstringi &i_name = _T(""), bool i_isInParen = false,
Modifier::Type i_mode = Modifier::Type_KEYSEQ); /// <KEY_SEQUENCE>
void load_KEY_ASSIGN(); /// <KEY_ASSIGN>
void load_EVENT_ASSIGN(); /// <EVENT_ASSIGN>
void load_MODIFIER_ASSIGNMENT(); /// <MODIFIER_ASSIGN>
void load_LOCK_ASSIGNMENT(); /// <LOCK_ASSIGN>
void load_KEYSEQ_DEFINITION(); /// <KEYSEQ_DEFINITION>
/// load
void load(const tstringi &i_filename);
/// is the filename readable ?
bool isReadable(const tstringi &i_filename, int i_debugLevel = 1) const;
/// get filename
bool getFilename(const tstringi &i_name,
tstringi *o_path, int i_debugLevel = 1) const;
public:
///
SettingLoader(SyncObject *i_soLog, tostream *i_log);
/// load setting
bool load(Setting *o_setting, const tstringi &i_filename = _T(""));
};
/// get home directory path
typedef std::list<tstringi> HomeDirectories;
extern void getHomeDirectories(HomeDirectories *o_path);
#endif // !_SETTING_H
<file_sep>///////////////////////////////////////////////////////////////////////////////
// keyque.c
///////////////////////////////////////////////////////////////////////////////
// Definitions
typedef struct KeyQue {
ULONG count; // Number of keys in the que
ULONG lengthof_que; // Length of que
KEYBOARD_INPUT_DATA *insert; // Insertion pointer for que
KEYBOARD_INPUT_DATA *remove; // Removal pointer for que
KEYBOARD_INPUT_DATA *que;
} KeyQue;
#define KeyQueSize 100
///////////////////////////////////////////////////////////////////////////////
// Prototypes
NTSTATUS KqInitialize(KeyQue *kq);
void KqClear(KeyQue *kq);
NTSTATUS KqFinalize(KeyQue *kq);
BOOLEAN KqIsEmpty(KeyQue *kq);
ULONG KqEnque(KeyQue *kq, IN KEYBOARD_INPUT_DATA *buf, IN ULONG lengthof_buf);
ULONG KqDeque(KeyQue *kq, OUT KEYBOARD_INPUT_DATA *buf, IN ULONG lengthof_buf);
#ifdef ALLOC_PRAGMA
#pragma alloc_text( init, KqInitialize )
#pragma alloc_text( page, KqFinalize )
#endif // ALLOC_PRAGMA
///////////////////////////////////////////////////////////////////////////////
// Functions
NTSTATUS KqInitialize(KeyQue *kq)
{
kq->count = 0;
kq->lengthof_que = KeyQueSize;
kq->que = ExAllocatePool(NonPagedPool,
kq->lengthof_que * sizeof(KEYBOARD_INPUT_DATA));
kq->insert = kq->que;
kq->remove = kq->que;
if (kq->que == NULL)
return STATUS_INSUFFICIENT_RESOURCES;
else
return STATUS_SUCCESS;
}
void KqClear(KeyQue *kq)
{
kq->count = 0;
kq->insert = kq->que;
kq->remove = kq->que;
}
NTSTATUS KqFinalize(KeyQue *kq)
{
if (kq->que)
ExFreePool(kq->que);
return STATUS_SUCCESS;
}
BOOLEAN KqIsEmpty(KeyQue *kq)
{
return 0 == kq->count;
}
// return: lengthof copied data
ULONG KqEnque(KeyQue *kq, IN KEYBOARD_INPUT_DATA *buf, IN ULONG lengthof_buf)
{
ULONG rest;
if (kq->lengthof_que - kq->count < lengthof_buf) // overflow
lengthof_buf = kq->lengthof_que - kq->count; // chop overflowed datum
if (lengthof_buf <= 0)
return 0;
rest = kq->lengthof_que - (kq->insert - kq->que);
if (rest < lengthof_buf) {
ULONG copy = rest;
if (0 < copy) {
RtlMoveMemory((PCHAR)kq->insert, (PCHAR)buf,
sizeof(KEYBOARD_INPUT_DATA) * copy);
buf += copy;
}
copy = lengthof_buf - copy;
if (0 < copy)
RtlMoveMemory((PCHAR)kq->que, (PCHAR)buf,
sizeof(KEYBOARD_INPUT_DATA) * copy);
kq->insert = kq->que + copy;
} else {
RtlMoveMemory((PCHAR)kq->insert, (PCHAR)buf,
sizeof(KEYBOARD_INPUT_DATA) * lengthof_buf);
kq->insert += lengthof_buf;
}
kq->count += lengthof_buf;
return lengthof_buf;
}
// return: lengthof copied data
ULONG KqDeque(KeyQue *kq, OUT KEYBOARD_INPUT_DATA *buf, IN ULONG lengthof_buf)
{
ULONG rest;
if (kq->count < lengthof_buf)
lengthof_buf = kq->count;
if (lengthof_buf <= 0)
return 0;
rest = kq->lengthof_que - (kq->remove - kq->que);
if (rest < lengthof_buf) {
ULONG copy = rest;
if (0 < copy) {
RtlMoveMemory((PCHAR)buf, (PCHAR)kq->remove,
sizeof(KEYBOARD_INPUT_DATA) * copy);
buf += copy;
}
copy = lengthof_buf - copy;
if (0 < copy)
RtlMoveMemory((PCHAR)buf, (PCHAR)kq->que,
sizeof(KEYBOARD_INPUT_DATA) * copy);
kq->remove = kq->que + copy;
} else {
RtlMoveMemory((PCHAR)buf, (PCHAR)kq->remove,
sizeof(KEYBOARD_INPUT_DATA) * lengthof_buf);
kq->remove += lengthof_buf;
}
kq->count -= lengthof_buf;
return lengthof_buf;
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// dlginvestigate.h
#ifndef _DLGINVESTIGATE_H
# define _DLGINVESTIGATE_H
# include <windows.h>
/// dialog procedure of "Investigate" dialog box
#ifdef MAYU64
INT_PTR CALLBACK dlgInvestigate_dlgProc(
#else
BOOL CALLBACK dlgInvestigate_dlgProc(
#endif
HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam);
class Engine;
/// parameters for "Investigate" dialog box
class DlgInvestigateData {
public:
Engine *m_engine; /// engine
HWND m_hwndLog; /// log
};
#endif // !_DLGINVESTIGATE_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// misc.h
#ifndef _MISC_H
# define _MISC_H
# include "compiler_specific.h"
# include <windows.h>
# include <cassert>
#define YAMY_SUCCESS 0
#define YAMY_ERROR_ON_GET_USERNAME 1001
#define YAMY_ERROR_INSUFFICIENT_BUFFER 1002
#define YAMY_ERROR_NO_MEMORY 1003
#define YAMY_ERROR_ON_GET_LOGONUSERNAME 1004
#define YAMY_ERROR_ON_GET_SECURITYINFO 1005
#define YAMY_ERROR_ON_GET_DACL 1006
#define YAMY_ERROR_ON_INITIALIZE_ACL 1007
#define YAMY_ERROR_ON_GET_ACE 1008
#define YAMY_ERROR_ON_ADD_ACE 1009
#define YAMY_ERROR_ON_ADD_ALLOWED_ACE 1010
#define YAMY_ERROR_ON_SET_SECURITYINFO 1011
#define YAMY_ERROR_ON_OPEN_YAMY_PROCESS 1012
#define YAMY_ERROR_ON_OPEN_YAMY_TOKEN 1013
#define YAMY_ERROR_ON_IMPERSONATE 1014
#define YAMY_ERROR_ON_REVERT_TO_SELF 1015
#define YAMY_ERROR_ON_OPEN_CURRENT_PROCESS 1016
#define YAMY_ERROR_ON_LOOKUP_PRIVILEGE 1017
#define YAMY_ERROR_ON_ADJUST_PRIVILEGE 1018
#define YAMY_ERROR_ON_OPEN_WINLOGON_PROCESS 1019
#define YAMY_ERROR_ON_VIRTUALALLOCEX 1020
#define YAMY_ERROR_ON_WRITEPROCESSMEMORY 1021
#define YAMY_ERROR_ON_CREATEREMOTETHREAD 1022
#define YAMY_ERROR_TIMEOUT_INJECTION 1023
#define YAMY_ERROR_RETRY_INJECTION_SUCCESS 1024
#define YAMY_ERROR_ON_READ_SCANCODE_MAP 1025
#define YAMY_ERROR_ON_WRITE_SCANCODE_MAP 1026
#define YAMY_ERROR_ON_GET_WINLOGON_PID 1027
typedef unsigned char u_char; /// unsigned char
typedef unsigned short u_short; /// unsigned short
typedef unsigned long u_long; /// unsigned long
typedef char int8; /// signed 8bit
typedef short int16; /// signed 16bit
typedef long int32; /// signed 32bit
typedef unsigned char u_int8; /// unsigned 8bit
typedef unsigned short u_int16; /// unsigned 16bit
typedef unsigned long u_int32; /// unsigned 32bit
#if defined(__BORLANDC__)
typedef unsigned __int64 u_int64; /// unsigned 64bit
#elif _MSC_VER <= 1300
typedef unsigned _int64 u_int64; /// unsigned 64bit
#else
typedef unsigned long long u_int64; /// unsigned 64bit
#endif
# ifdef NDEBUG
# define ASSERT(i_exp)
# define CHECK(i_cond, i_exp) i_exp
# define CHECK_TRUE(i_exp) i_exp
# define CHECK_FALSE(i_exp) i_exp
# else // NDEBUG
/// assertion. i_exp is evaluated only in debug build
# define ASSERT(i_exp) assert(i_exp)
/// assertion, but i_exp is always evaluated
# define CHECK(i_cond, i_exp) assert(i_cond (i_exp))
/// identical to CHECK(!!, i_exp)
# define CHECK_TRUE(i_exp) assert(!!(i_exp))
/// identical to CHECK(!, i_exp)
# define CHECK_FALSE(i_exp) assert(!(i_exp))
# endif // NDEBUG
/// get number of array elements
# define NUMBER_OF(i_array) (sizeof(i_array) / sizeof((i_array)[0]))
/// max path length
# define GANA_MAX_PATH (MAX_PATH * 4)
/// max length of global atom
# define GANA_MAX_ATOM_LENGTH 256
# undef MAX
/// redefine MAX macro
# define MAX(a, b) (((b) < (a)) ? (a) : (b))
# undef MIN
/// redefine MIN macro
# define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif // !_MISC_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// dlglog.h
#ifndef _DLGLOG_H
# define _DLGLOG_H
# include <windows.h>
# include "msgstream.h"
//
#ifdef MAYU64
INT_PTR CALLBACK dlgLog_dlgProc(
#else
BOOL CALLBACK dlgLog_dlgProc(
#endif
HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam);
enum {
///
WM_APP_dlglogNotify = WM_APP + 115,
};
enum DlgLogNotify {
DlgLogNotify_logCleared, ///
};
/// parameters for "Investigate" dialog box
class DlgLogData {
public:
tomsgstream *m_log; /// log stream
HWND m_hwndTaskTray; /// tasktray window
};
#endif // !_DLGLOG_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// vkeytable.cpp
#include "vkeytable.h"
#include <ime.h>
// Vkey table (terminated by NULL)
const VKeyTable g_vkeyTable[] = {
#define VK(name) { VK_##name, _T(#name) }
/*
* from WinUser.h
*/
VK(LBUTTON), // 0x01
VK(RBUTTON), // 0x02
VK(CANCEL), // 0x03
VK(MBUTTON), // 0x04 /* NOT contiguous with L & RBUTTON */
VK(XBUTTON1), // 0x05 /* NOT contiguous with L & RBUTTON */
VK(XBUTTON2), // 0x06 /* NOT contiguous with L & RBUTTON */
/*
* 0x07 : unassigned
*/
VK(BACK), // 0x08
VK(TAB), // 0x09
/*
* 0x0A - 0x0B : reserved
*/
VK(CLEAR), // 0x0C
VK(RETURN), // 0x0D
VK(SHIFT), // 0x10
VK(CONTROL), // 0x11
VK(MENU), // 0x12
VK(PAUSE), // 0x13
VK(CAPITAL), // 0x14
VK(KANA), // 0x15
VK(HANGEUL), // 0x15 /* old name - should be here for compatibility */
VK(HANGUL), // 0x15
VK(JUNJA), // 0x17
VK(FINAL), // 0x18
VK(HANJA), // 0x19
VK(KANJI), // 0x19
VK(ESCAPE), // 0x1B
VK(CONVERT), // 0x1C
VK(NONCONVERT), // 0x1D
VK(ACCEPT), // 0x1E
VK(MODECHANGE), // 0x1F
VK(SPACE), // 0x20
VK(PRIOR), // 0x21
VK(NEXT), // 0x22
VK(END), // 0x23
VK(HOME), // 0x24
VK(LEFT), // 0x25
VK(UP), // 0x26
VK(RIGHT), // 0x27
VK(DOWN), // 0x28
VK(SELECT), // 0x29
VK(PRINT), // 0x2A
VK(EXECUTE), // 0x2B
VK(SNAPSHOT), // 0x2C
VK(INSERT), // 0x2D
VK(DELETE), // 0x2E
VK(HELP), // 0x2F
/*
* VK_0 - VK_9 are the same as ASCII '0' - '9' (0x30 - 0x39)
* 0x40 : unassigned
* VK_A - VK_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A)
*/
{ _T('0'), _T("_0") }, // 30 0
{ _T('1'), _T("_1") }, // 31 1
{ _T('2'), _T("_2") }, // 32 2
{ _T('3'), _T("_3") }, // 33 3
{ _T('4'), _T("_4") }, // 34 4
{ _T('5'), _T("_5") }, // 35 5
{ _T('6'), _T("_6") }, // 36 6
{ _T('7'), _T("_7") }, // 37 7
{ _T('8'), _T("_8") }, // 38 8
{ _T('9'), _T("_9") }, // 39 9
{ _T('A'), _T("A") }, // 41 A
{ _T('B'), _T("B") }, // 42 B
{ _T('C'), _T("C") }, // 43 C
{ _T('D'), _T("D") }, // 44 D
{ _T('E'), _T("E") }, // 45 E
{ _T('F'), _T("F") }, // 46 F
{ _T('G'), _T("G") }, // 47 G
{ _T('H'), _T("H") }, // 48 H
{ _T('I'), _T("I") }, // 49 I
{ _T('J'), _T("J") }, // 4A J
{ _T('K'), _T("K") }, // 4B K
{ _T('L'), _T("L") }, // 4C L
{ _T('M'), _T("M") }, // 4D M
{ _T('N'), _T("N") }, // 4E N
{ _T('O'), _T("O") }, // 4F O
{ _T('P'), _T("P") }, // 50 P
{ _T('Q'), _T("Q") }, // 51 Q
{ _T('R'), _T("R") }, // 52 R
{ _T('S'), _T("S") }, // 53 S
{ _T('T'), _T("T") }, // 54 T
{ _T('U'), _T("U") }, // 55 U
{ _T('V'), _T("V") }, // 56 V
{ _T('W'), _T("W") }, // 57 W
{ _T('X'), _T("X") }, // 58 X
{ _T('Y'), _T("Y") }, // 59 Y
{ _T('Z'), _T("Z") }, // 5A Z
VK(LWIN), // 0x5B
VK(RWIN), // 0x5C
VK(APPS), // 0x5D
/*
* 0x5E : reserved
*/
VK(SLEEP), // 0x5F
VK(NUMPAD0), // 0x60
VK(NUMPAD1), // 0x61
VK(NUMPAD2), // 0x62
VK(NUMPAD3), // 0x63
VK(NUMPAD4), // 0x64
VK(NUMPAD5), // 0x65
VK(NUMPAD6), // 0x66
VK(NUMPAD7), // 0x67
VK(NUMPAD8), // 0x68
VK(NUMPAD9), // 0x69
VK(MULTIPLY), // 0x6A
VK(ADD), // 0x6B
VK(SEPARATOR), // 0x6C
VK(SUBTRACT), // 0x6D
VK(DECIMAL), // 0x6E
VK(DIVIDE), // 0x6F
VK(F1), // 0x70
VK(F2), // 0x71
VK(F3), // 0x72
VK(F4), // 0x73
VK(F5), // 0x74
VK(F6), // 0x75
VK(F7), // 0x76
VK(F8), // 0x77
VK(F9), // 0x78
VK(F10), // 0x79
VK(F11), // 0x7A
VK(F12), // 0x7B
VK(F13), // 0x7C
VK(F14), // 0x7D
VK(F15), // 0x7E
VK(F16), // 0x7F
VK(F17), // 0x80
VK(F18), // 0x81
VK(F19), // 0x82
VK(F20), // 0x83
VK(F21), // 0x84
VK(F22), // 0x85
VK(F23), // 0x86
VK(F24), // 0x87
/*
* 0x88 - 0x8F : unassigned
*/
VK(NUMLOCK), // 0x90
VK(SCROLL), // 0x91
/*
* NEC PC-9800 kbd definitions
*/
VK(OEM_NEC_EQUAL), // 0x92 // '=' key on numpad
/*
* Fujitsu/OASYS kbd definitions
*/
VK(OEM_FJ_JISHO), // 0x92 // 'Dictionary' key
VK(OEM_FJ_MASSHOU), // 0x93 // 'Unregister word' key
VK(OEM_FJ_TOUROKU), // 0x94 // 'Register word' key
VK(OEM_FJ_LOYA), // 0x95 // 'Left OYAYUBI' key
VK(OEM_FJ_ROYA), // 0x96 // 'Right OYAYUBI' key
/*
* 0x97 - 0x9F : unassigned
*/
/*
* VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys.
* Used only as parameters to GetAsyncKeyState() and GetKeyState().
* No other API or message will distinguish left and right keys in this way.
*/
VK(LSHIFT), // 0xA0
VK(RSHIFT), // 0xA1
VK(LCONTROL), // 0xA2
VK(RCONTROL), // 0xA3
VK(LMENU), // 0xA4
VK(RMENU), // 0xA5
VK(BROWSER_BACK), // 0xA6
VK(BROWSER_FORWARD), // 0xA7
VK(BROWSER_REFRESH), // 0xA8
VK(BROWSER_STOP), // 0xA9
VK(BROWSER_SEARCH), // 0xAA
VK(BROWSER_FAVORITES),// 0xAB
VK(BROWSER_HOME), // 0xAC
VK(VOLUME_MUTE), // 0xAD
VK(VOLUME_DOWN), // 0xAE
VK(VOLUME_UP), // 0xAF
VK(MEDIA_NEXT_TRACK), // 0xB0
VK(MEDIA_PREV_TRACK), // 0xB1
VK(MEDIA_STOP), // 0xB2
VK(MEDIA_PLAY_PAUSE), // 0xB3
VK(LAUNCH_MAIL), // 0xB4
VK(LAUNCH_MEDIA_SELECT), // 0xB5
VK(LAUNCH_APP1), // 0xB6
VK(LAUNCH_APP2), // 0xB7
/*
* 0xB8 - 0xB9 : reserved
*/
VK(OEM_1), // 0xBA // ';:' for US
VK(OEM_PLUS), // 0xBB // '+' any country
VK(OEM_COMMA), // 0xBC // ',' any country
VK(OEM_MINUS), // 0xBD // '-' any country
VK(OEM_PERIOD), // 0xBE // '.' any country
VK(OEM_2), // 0xBF // '/?' for US
VK(OEM_3), // 0xC0 // '`~' for US
/*
* 0xC1 - 0xD7 : reserved
*/
/*
* 0xD8 - 0xDA : unassigned
*/
VK(OEM_4), // 0xDB // '[{' for US
VK(OEM_5), // 0xDC // '\|' for US
VK(OEM_6), // 0xDD // ']}' for US
VK(OEM_7), // 0xDE // ''"' for US
VK(OEM_8), // 0xDF
/*
* 0xE0 : reserved
*/
/*
* Various extended or enhanced keyboards
*/
VK(OEM_AX), // 0xE1 // 'AX' key on Japanese AX kbd
VK(OEM_102), // 0xE2 // "<>" or "\|" on RT 102-key kbd.
VK(ICO_HELP), // 0xE3 // Help key on ICO
VK(ICO_00), // 0xE4 // 00 key on ICO
VK(PROCESSKEY), // 0xE5
VK(ICO_CLEAR), // 0xE6
VK(PACKET), // 0xE7
/*
* 0xE8 : unassigned
*/
/*
* Nokia/Ericsson definitions
*/
VK(OEM_RESET), // 0xE9
VK(OEM_JUMP), // 0xEA
VK(OEM_PA1), // 0xEB
VK(OEM_PA2), // 0xEC
VK(OEM_PA3), // 0xED
VK(OEM_WSCTRL), // 0xEE
VK(OEM_CUSEL), // 0xEF
VK(OEM_ATTN), // 0xF0
VK(OEM_FINISH), // 0xF1
VK(OEM_COPY), // 0xF2
VK(OEM_AUTO), // 0xF3
VK(OEM_ENLW), // 0xF4
VK(OEM_BACKTAB), // 0xF5
VK(ATTN), // 0xF6
VK(CRSEL), // 0xF7
VK(EXSEL), // 0xF8
VK(EREOF), // 0xF9
VK(PLAY), // 0xFA
VK(ZOOM), // 0xFB
VK(NONAME), // 0xFC
VK(PA1), // 0xFD
VK(OEM_CLEAR), // 0xFE
/*
* from Ime.h
*/
#if !defined(VK_DBE_ALPHANUMERIC)
VK(DBE_ALPHANUMERIC), // 0x0f0
VK(DBE_KATAKANA), // 0x0f1
VK(DBE_HIRAGANA), // 0x0f2
VK(DBE_SBCSCHAR), // 0x0f3
VK(DBE_DBCSCHAR), // 0x0f4
VK(DBE_ROMAN), // 0x0f5
VK(DBE_NOROMAN), // 0x0f6
VK(DBE_ENTERWORDREGISTERMODE), // 0x0f7
VK(DBE_ENTERIMECONFIGMODE), // 0x0f8
VK(DBE_FLUSHSTRING), // 0x0f9
VK(DBE_CODEINPUT), // 0x0fa
VK(DBE_NOCODEINPUT), // 0x0fb
VK(DBE_DETERMINESTRING), // 0x0fc
VK(DBE_ENTERDLGCONVERSIONMODE), // 0x0fd
#endif
{ 0, NULL },
#undef VK
};
<file_sep>
窓使いの憂鬱ドライバ
1. コンパイル方法
Windows 200 DDK と Visual C++ 6.0 で build ユーティリティを利
用してコンパイルします。
> cd mayu\d
> build
> cd nt4
> build
mayud.sys を %windir%\system32\drivers\ へコピーし test.reg を
入力すれば、手動でデバイスを on/off できます。(又は Windows
NT4.0 の場合は mayudnt4.sys を mayud.sys という名前でコピー)
2. 使い方
mayud を動作させると
\\.\MayuDetour1
というデバイスができます。このデバイスを GENERIC_READ |
GENERIC_WRITE で開きます。
ReadFile / WriteFile では、以下の構造体を使います。デバイスを
開いたあとに、ReadFile するとユーザーが入力したキーを取得でき
ます。WriteFile するとユーザがあたかもキーを入力したかのように
Windows を操作することができます。
struct KEYBOARD_INPUT_DATA
{
enum { BREAK = 1,
E0 = 2, E1 = 4,
TERMSRV_SET_LED = 8 };
enum { KEYBOARD_OVERRUN_MAKE_CODE = 0xFF };
USHORT UnitId;
USHORT MakeCode;
USHORT Flags;
USHORT Reserved;
ULONG ExtraInformation;
};
UnitId と Reserved は常に 0 です。ExtraInformation に値を設定
すると、WM_KEYDOWN などのメッセージが来た時に
GetMessageExtraInfo() API でその値を取得することができます。
MakeCode はキーボードのスキャンコードです。Flags は BREAK, E0,
E1, TERMSRV_SET_LED が組み合わさっています。BREAK はキーを離し
たとき、E0 と E1 は拡張キーを押したときに設定されます。
3. バグ
* ReadFile が ERROR_OPERATION_ABORTED で失敗した場合もう一度
ReadFile する必要があります。
* 複数のスレッドから mayud デバイスを read すると
MULTIPLE_IRP_COMPLETE_REQUESTS (0x44) で落ちることがあるよう
です。再現性は不明。
* ReadFile するとユーザーが入力するまで永遠に帰ってきません。
NT4.0 ならば別スレッドで CancelIo することで ReadFile をキャ
ンセルすることができますが、Windows 2000 では方法がありませ
ん。
* PnP は考慮していません。つまり、キーボードをつけたり離したり
するとどうなるかわかりません。
* キーボードが二つ以上あるときでも、デバイスは一つしかできませ
ん。
<file_sep>############################################################## -*- Makefile -*-
#
# Makefile (Visual C++)
#
# make release version: nmake nodebug=1
# make debug version: nmake
#
###############################################################################
# VC++ rules ###############################################################
!if "$(TARGETOS)" == ""
TARGETOS = WINNT
!endif # TARGETOS
!if "$(TARGETOS)" == "WINNT"
APPVER = 5.0
!ifdef nodebug
OUT_DIR_EXE = out$(MAYU_VC)_winnt
!else # nodebug
OUT_DIR_EXE = out$(MAYU_VC)_winnt_debug
!endif # nodebug
!if "$(CPU)" == "AMD64"
MAYU_ARCH = 64
!else
MAYU_ARCH = 32
!endif
OUT_DIR = $(OUT_DIR_EXE)_$(MAYU_ARCH)
!endif # TARGETOS
!if "$(TARGETOS)" == "WIN95"
APPVER = 4.0
!ifdef nodebug
OUT_DIR = out$(MAYU_VC)_win9x
!else # nodebug
OUT_DIR = out$(MAYU_VC)_win9x_debug
!endif # nodebug
!endif # TARGETOS
!if "$(TARGETOS)" == "BOTH"
!error Must specify TARGETOS=WIN95 or TARGETOS=WINNT
!endif # TARGETOS
#_WIN32_IE = 0x0500
!include <win32.mak>
#NMAKE_WINVER = 0x0500 # trick for WS_EX_LAYERED
!ifdef nodebug
DEBUG_FLAG = -DNDEBUG
!else # nodebug
DEBUG_FLAG = $(cdebug)
!endif # nodebug
{}.cpp{$(OUT_DIR)}.obj:
$(cc) -EHsc $(cflags) $(cvarsmt) $(DEFINES) $(INCLUDES) \
$(DEBUG_FLAG) -Fo$@ $(*B).cpp
{}.rc{$(OUT_DIR)}.res:
$(rc) $(rcflags) $(rcvars) /fo$@ $(*B).rc
!ifdef nodebug
conxlibsmt = $(conlibsmt) libcpmt.lib libcmt.lib
guixlibsmt = $(guilibsmt) libcpmt.lib libcmt.lib
!else # nodebug
conxlibsmt = $(conlibsmt) libcpmtd.lib libcmtd.lib
guixlibsmt = $(guilibsmt) libcpmtd.lib libcmtd.lib
!endif # nodebug
DEPENDFLAGS = --cpp=vc --ignore='$(INCLUDE)' -p"$$(OUT_DIR)\\" \
--path-delimiter=dos --newline=unix \
$(DEPENDIGNORE) -EHsc $(cflags) $(cvarsmt) \
$(DEFINES) $(INCLUDES) $(DEBUG_FLAG)
CLEAN = $(OUT_DIR)\*.pdb
# tools ###############################################################
RM = del
COPY = copy
ECHO = echo
MKDIR = mkdir
RMDIR = rmdir
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// setting.cpp
#include "misc.h"
#include "dlgsetting.h"
#include "errormessage.h"
#include "mayu.h"
#include "mayurc.h"
#include "registry.h"
#include "setting.h"
#include "windowstool.h"
#include "vkeytable.h"
#include "array.h"
#include <algorithm>
#include <fstream>
#include <iomanip>
#include <sys/stat.h>
namespace Event
{
Key prefixed(_T("prefixed"));
Key before_key_down(_T("before-key-down"));
Key after_key_up(_T("after-key-up"));
Key *events[] = {
&prefixed,
&before_key_down,
&after_key_up,
NULL,
};
}
// get mayu filename
static bool getFilenameFromRegistry(
tstringi *o_name, tstringi *o_filename, Setting::Symbols *o_symbols)
{
Registry reg(MAYU_REGISTRY_ROOT);
int index;
reg.read(_T(".mayuIndex"), &index, 0);
_TCHAR buf[100];
_sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index);
tstringi entry;
if (!reg.read(buf, &entry))
return false;
tregex getFilename(_T("^([^;]*);([^;]*);(.*)$"));
tsmatch getFilenameResult;
if (!boost::regex_match(entry, getFilenameResult, getFilename))
return false;
if (o_name)
*o_name = getFilenameResult.str(1);
if (o_filename)
*o_filename = getFilenameResult.str(2);
if (o_symbols) {
tstringi symbols = getFilenameResult.str(3);
tregex symbol(_T("-D([^;]*)(.*)$"));
tsmatch symbolResult;
while (boost::regex_search(symbols, symbolResult, symbol)) {
o_symbols->insert(symbolResult.str(1));
symbols = symbolResult.str(2);
}
}
return true;
}
// get home directory path
void getHomeDirectories(HomeDirectories *o_pathes)
{
tstringi filename;
#ifndef USE_INI
if (getFilenameFromRegistry(NULL, &filename, NULL) &&
!filename.empty()) {
tregex getPath(_T("^(.*[/\\\\])[^/\\\\]*$"));
tsmatch getPathResult;
if (boost::regex_match(filename, getPathResult, getPath))
o_pathes->push_back(getPathResult.str(1));
}
const _TCHAR *home = _tgetenv(_T("HOME"));
if (home)
o_pathes->push_back(home);
const _TCHAR *homedrive = _tgetenv(_T("HOMEDRIVE"));
const _TCHAR *homepath = _tgetenv(_T("HOMEPATH"));
if (homedrive && homepath)
o_pathes->push_back(tstringi(homedrive) + homepath);
const _TCHAR *userprofile = _tgetenv(_T("USERPROFILE"));
if (userprofile)
o_pathes->push_back(userprofile);
_TCHAR buf[GANA_MAX_PATH];
DWORD len = GetCurrentDirectory(NUMBER_OF(buf), buf);
if (0 < len && len < NUMBER_OF(buf))
o_pathes->push_back(buf);
#else //USE_INI
_TCHAR buf[GANA_MAX_PATH];
#endif //USE_INI
if (GetModuleFileName(GetModuleHandle(NULL), buf, NUMBER_OF(buf)))
o_pathes->push_back(pathRemoveFileSpec(buf));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SettingLoader
// is there no more tokens ?
bool SettingLoader::isEOL()
{
return m_ti == m_tokens.end();
}
// get next token
Token *SettingLoader::getToken()
{
if (isEOL())
throw ErrorMessage() << _T("too few words.");
return &*(m_ti ++);
}
// look next token
Token *SettingLoader::lookToken()
{
if (isEOL())
throw ErrorMessage() << _T("too few words.");
return &*m_ti;
}
// argument "("
bool SettingLoader::getOpenParen(bool i_doesThrow, const _TCHAR *i_name)
{
if (!isEOL() && lookToken()->isOpenParen()) {
getToken();
return true;
}
if (i_doesThrow)
throw ErrorMessage() << _T("there must be `(' after `&")
<< i_name << _T("'.");
return false;
}
// argument ")"
bool SettingLoader::getCloseParen(bool i_doesThrow, const _TCHAR *i_name)
{
if (!isEOL() && lookToken()->isCloseParen()) {
getToken();
return true;
}
if (i_doesThrow)
throw ErrorMessage() << _T("`&") << i_name
<< _T("': too many arguments.");
return false;
}
// argument ","
bool SettingLoader::getComma(bool i_doesThrow, const _TCHAR *i_name)
{
if (!isEOL() && lookToken()->isComma()) {
getToken();
return true;
}
if (i_doesThrow)
throw ErrorMessage() << _T("`&") << i_name
<< _T("': comma expected.");
return false;
}
// <INCLUDE>
void SettingLoader::load_INCLUDE()
{
SettingLoader loader(m_soLog, m_log);
loader.m_defaultAssignModifier = m_defaultAssignModifier;
loader.m_defaultKeySeqModifier = m_defaultKeySeqModifier;
if (!loader.load(m_setting, (*getToken()).getString()))
m_isThereAnyError = true;
}
// <SCAN_CODES>
void SettingLoader::load_SCAN_CODES(Key *o_key)
{
for (int j = 0; j < Key::MAX_SCAN_CODES_SIZE && !isEOL(); ++ j) {
ScanCode sc;
sc.m_flags = 0;
while (true) {
Token *t = getToken();
if (t->isNumber()) {
sc.m_scan = (u_char)t->getNumber();
o_key->addScanCode(sc);
break;
}
if (*t == _T("E0-")) sc.m_flags |= ScanCode::E0;
else if (*t == _T("E1-")) sc.m_flags |= ScanCode::E1;
else throw ErrorMessage() << _T("`") << *t
<< _T("': invalid modifier.");
}
}
}
// <DEFINE_KEY>
void SettingLoader::load_DEFINE_KEY()
{
Token *t = getToken();
Key key;
// <KEY_NAMES>
if (*t == _T('(')) {
key.addName(getToken()->getString());
while (t = getToken(), *t != _T(')'))
key.addName(t->getString());
if (*getToken() != _T("="))
throw ErrorMessage() << _T("there must be `=' after `)'.");
} else {
key.addName(t->getString());
while (t = getToken(), *t != _T("="))
key.addName(t->getString());
}
load_SCAN_CODES(&key);
m_setting->m_keyboard.addKey(key);
}
// <DEFINE_MODIFIER>
void SettingLoader::load_DEFINE_MODIFIER()
{
Token *t = getToken();
Modifier::Type mt;
if (*t == _T("shift") ) mt = Modifier::Type_Shift;
else if (*t == _T("alt") ||
*t == _T("meta") ||
*t == _T("menu") ) mt = Modifier::Type_Alt;
else if (*t == _T("control") ||
*t == _T("ctrl") ) mt = Modifier::Type_Control;
else if (*t == _T("windows") ||
*t == _T("win") ) mt = Modifier::Type_Windows;
else throw ErrorMessage() << _T("`") << *t
<< _T("': invalid modifier name.");
if (*getToken() != _T("="))
throw ErrorMessage() << _T("there must be `=' after modifier name.");
while (!isEOL()) {
t = getToken();
Key *key =
m_setting->m_keyboard.searchKeyByNonAliasName(t->getString());
if (!key)
throw ErrorMessage() << _T("`") << *t << _T("': invalid key name.");
m_setting->m_keyboard.addModifier(mt, key);
}
}
// <DEFINE_SYNC_KEY>
void SettingLoader::load_DEFINE_SYNC_KEY()
{
Key *key = m_setting->m_keyboard.getSyncKey();
key->initialize();
key->addName(_T("sync"));
if (*getToken() != _T("="))
throw ErrorMessage() << _T("there must be `=' after `sync'.");
load_SCAN_CODES(key);
}
// <DEFINE_ALIAS>
void SettingLoader::load_DEFINE_ALIAS()
{
Token *name = getToken();
if (*getToken() != _T("="))
throw ErrorMessage() << _T("there must be `=' after `alias'.");
Token *t = getToken();
Key *key = m_setting->m_keyboard.searchKeyByNonAliasName(t->getString());
if (!key)
throw ErrorMessage() << _T("`") << *t << _T("': invalid key name.");
m_setting->m_keyboard.addAlias(name->getString(), key);
}
// <DEFINE_SUBSTITUTE>
void SettingLoader::load_DEFINE_SUBSTITUTE()
{
typedef std::list<ModifiedKey> AssignedKeys;
AssignedKeys assignedKeys;
do {
ModifiedKey mkey;
mkey.m_modifier =
load_MODIFIER(Modifier::Type_ASSIGN, m_defaultAssignModifier);
mkey.m_key = load_KEY_NAME();
assignedKeys.push_back(mkey);
} while (!(*lookToken() == _T("=>") || *lookToken() == _T("=")));
getToken();
KeySeq *keySeq = load_KEY_SEQUENCE(_T(""), false, Modifier::Type_ASSIGN);
ModifiedKey mkey = keySeq->getFirstModifiedKey();
if (!mkey.m_key)
throw ErrorMessage() << _T("no key is specified for substitute.");
for (AssignedKeys::iterator i = assignedKeys.begin();
i != assignedKeys.end(); ++ i)
m_setting->m_keyboard.addSubstitute(*i, mkey);
}
// <DEFINE_OPTION>
void SettingLoader::load_DEFINE_OPTION()
{
Token *t = getToken();
if (*t == _T("KL-")) {
if (*getToken() != _T("=")) {
throw ErrorMessage() << _T("there must be `=' after `def option KL-'.");
}
load_ARGUMENT(&m_setting->m_correctKanaLockHandling);
} else if (*t == _T("delay-of")) {
if (*getToken() != _T("!!!")) {
throw ErrorMessage()
<< _T("there must be `!!!' after `def option delay-of'.");
}
if (*getToken() != _T("=")) {
throw ErrorMessage()
<< _T("there must be `=' after `def option delay-of !!!'.");
}
load_ARGUMENT(&m_setting->m_oneShotRepeatableDelay);
} else if (*t == _T("sts4mayu")) {
if (*getToken() != _T("=")) {
throw ErrorMessage()
<< _T("there must be `=' after `def option sts4mayu'.");
}
load_ARGUMENT(&m_setting->m_sts4mayu);
} else if (*t == _T("cts4mayu")) {
if (*getToken() != _T("=")) {
throw ErrorMessage()
<< _T("there must be `=' after `def option cts4mayu'.");
}
load_ARGUMENT(&m_setting->m_cts4mayu);
} else if (*t == _T("mouse-event")) {
if (*getToken() != _T("=")) {
throw ErrorMessage()
<< _T("there must be `=' after `def option mouse-event'.");
}
load_ARGUMENT(&m_setting->m_mouseEvent);
} else if (*t == _T("drag-threshold")) {
if (*getToken() != _T("=")) {
throw ErrorMessage()
<< _T("there must be `=' after `def option drag-threshold'.");
}
load_ARGUMENT(&m_setting->m_dragThreshold);
} else {
throw ErrorMessage() << _T("syntax error `def option ") << *t << _T("'.");
}
}
// <KEYBOARD_DEFINITION>
void SettingLoader::load_KEYBOARD_DEFINITION()
{
Token *t = getToken();
// <DEFINE_KEY>
if (*t == _T("key")) load_DEFINE_KEY();
// <DEFINE_MODIFIER>
else if (*t == _T("mod")) load_DEFINE_MODIFIER();
// <DEFINE_SYNC_KEY>
else if (*t == _T("sync")) load_DEFINE_SYNC_KEY();
// <DEFINE_ALIAS>
else if (*t == _T("alias")) load_DEFINE_ALIAS();
// <DEFINE_SUBSTITUTE>
else if (*t == _T("subst")) load_DEFINE_SUBSTITUTE();
// <DEFINE_OPTION>
else if (*t == _T("option")) load_DEFINE_OPTION();
//
else throw ErrorMessage() << _T("syntax error `") << *t << _T("'.");
}
// <..._MODIFIER>
Modifier SettingLoader::load_MODIFIER(
Modifier::Type i_mode, Modifier i_modifier, Modifier::Type *o_mode)
{
if (o_mode)
*o_mode = Modifier::Type_begin;
Modifier isModifierSpecified;
enum { PRESS, RELEASE, DONTCARE } flag = PRESS;
int i;
for (i = i_mode; i < Modifier::Type_ASSIGN; ++ i) {
i_modifier.dontcare(Modifier::Type(i));
isModifierSpecified.on(Modifier::Type(i));
}
Token *t = NULL;
continue_loop:
while (!isEOL()) {
t = lookToken();
const static struct {
const _TCHAR *m_s;
Modifier::Type m_mt;
} map[] = {
// <BASIC_MODIFIER>
{ _T("S-"), Modifier::Type_Shift },
{ _T("A-"), Modifier::Type_Alt },
{ _T("M-"), Modifier::Type_Alt },
{ _T("C-"), Modifier::Type_Control },
{ _T("W-"), Modifier::Type_Windows },
// <KEYSEQ_MODIFIER>
{ _T("U-"), Modifier::Type_Up },
{ _T("D-"), Modifier::Type_Down },
// <ASSIGN_MODIFIER>
{ _T("R-"), Modifier::Type_Repeat },
{ _T("IL-"), Modifier::Type_ImeLock },
{ _T("IC-"), Modifier::Type_ImeComp },
{ _T("I-"), Modifier::Type_ImeComp },
{ _T("NL-"), Modifier::Type_NumLock },
{ _T("CL-"), Modifier::Type_CapsLock },
{ _T("SL-"), Modifier::Type_ScrollLock },
{ _T("KL-"), Modifier::Type_KanaLock },
{ _T("MAX-"), Modifier::Type_Maximized },
{ _T("MIN-"), Modifier::Type_Minimized },
{ _T("MMAX-"), Modifier::Type_MdiMaximized },
{ _T("MMIN-"), Modifier::Type_MdiMinimized },
{ _T("T-"), Modifier::Type_Touchpad },
{ _T("TS-"), Modifier::Type_TouchpadSticky },
{ _T("M0-"), Modifier::Type_Mod0 },
{ _T("M1-"), Modifier::Type_Mod1 },
{ _T("M2-"), Modifier::Type_Mod2 },
{ _T("M3-"), Modifier::Type_Mod3 },
{ _T("M4-"), Modifier::Type_Mod4 },
{ _T("M5-"), Modifier::Type_Mod5 },
{ _T("M6-"), Modifier::Type_Mod6 },
{ _T("M7-"), Modifier::Type_Mod7 },
{ _T("M8-"), Modifier::Type_Mod8 },
{ _T("M9-"), Modifier::Type_Mod9 },
{ _T("L0-"), Modifier::Type_Lock0 },
{ _T("L1-"), Modifier::Type_Lock1 },
{ _T("L2-"), Modifier::Type_Lock2 },
{ _T("L3-"), Modifier::Type_Lock3 },
{ _T("L4-"), Modifier::Type_Lock4 },
{ _T("L5-"), Modifier::Type_Lock5 },
{ _T("L6-"), Modifier::Type_Lock6 },
{ _T("L7-"), Modifier::Type_Lock7 },
{ _T("L8-"), Modifier::Type_Lock8 },
{ _T("L9-"), Modifier::Type_Lock9 },
};
for (int i = 0; i < NUMBER_OF(map); ++ i)
if (*t == map[i].m_s) {
getToken();
Modifier::Type mt = map[i].m_mt;
if (static_cast<int>(i_mode) <= static_cast<int>(mt))
throw ErrorMessage() << _T("`") << *t
<< _T("': invalid modifier at this context.");
switch (flag) {
case PRESS:
i_modifier.press(mt);
break;
case RELEASE:
i_modifier.release(mt);
break;
case DONTCARE:
i_modifier.dontcare(mt);
break;
}
isModifierSpecified.on(mt);
flag = PRESS;
if (o_mode && *o_mode < mt) {
if (mt < Modifier::Type_BASIC)
*o_mode = Modifier::Type_BASIC;
else if (mt < Modifier::Type_KEYSEQ)
*o_mode = Modifier::Type_KEYSEQ;
else if (mt < Modifier::Type_ASSIGN)
*o_mode = Modifier::Type_ASSIGN;
}
goto continue_loop;
}
if (*t == _T("*")) {
getToken();
flag = DONTCARE;
continue;
}
if (*t == _T("~")) {
getToken();
flag = RELEASE;
continue;
}
break;
}
for (i = Modifier::Type_begin; i != Modifier::Type_end; ++ i)
if (!isModifierSpecified.isOn(Modifier::Type(i)))
switch (flag) {
case PRESS:
break;
case RELEASE:
i_modifier.release(Modifier::Type(i));
break;
case DONTCARE:
i_modifier.dontcare(Modifier::Type(i));
break;
}
// fix up and down
bool isDontcareUp = i_modifier.isDontcare(Modifier::Type_Up);
bool isDontcareDown = i_modifier.isDontcare(Modifier::Type_Down);
bool isOnUp = i_modifier.isOn(Modifier::Type_Up);
bool isOnDown = i_modifier.isOn(Modifier::Type_Down);
if (isDontcareUp && isDontcareDown)
;
else if (isDontcareUp)
i_modifier.on(Modifier::Type_Up, !isOnDown);
else if (isDontcareDown)
i_modifier.on(Modifier::Type_Down, !isOnUp);
else if (isOnUp == isOnDown) {
i_modifier.dontcare(Modifier::Type_Up);
i_modifier.dontcare(Modifier::Type_Down);
}
// fix repeat
if (!isModifierSpecified.isOn(Modifier::Type_Repeat))
i_modifier.dontcare(Modifier::Type_Repeat);
return i_modifier;
}
// <KEY_NAME>
Key *SettingLoader::load_KEY_NAME()
{
Token *t = getToken();
Key *key = m_setting->m_keyboard.searchKey(t->getString());
if (!key)
throw ErrorMessage() << _T("`") << *t << _T("': invalid key name.");
return key;
}
// <KEYMAP_DEFINITION>
void SettingLoader::load_KEYMAP_DEFINITION(const Token *i_which)
{
Keymap::Type type = Keymap::Type_keymap;
Token *name = getToken(); // <KEYMAP_NAME>
tstringi windowClassName;
tstringi windowTitleName;
KeySeq *keySeq = NULL;
Keymap *parentKeymap = NULL;
bool isKeymap2 = false;
bool doesLoadDefaultKeySeq = false;
if (!isEOL()) {
Token *t = lookToken();
if (*i_which == _T("window")) { // <WINDOW>
if (t->isOpenParen())
// "(" <WINDOW_CLASS_NAME> "&&" <WINDOW_TITLE_NAME> ")"
// "(" <WINDOW_CLASS_NAME> "||" <WINDOW_TITLE_NAME> ")"
{
getToken();
windowClassName = getToken()->getRegexp();
t = getToken();
if (*t == _T("&&"))
type = Keymap::Type_windowAnd;
else if (*t == _T("||"))
type = Keymap::Type_windowOr;
else
throw ErrorMessage() << _T("`") << *t << _T("': unknown operator.");
windowTitleName = getToken()->getRegexp();
if (!getToken()->isCloseParen())
throw ErrorMessage() << _T("there must be `)'.");
} else if (t->isRegexp()) { // <WINDOW_CLASS_NAME>
getToken();
type = Keymap::Type_windowAnd;
windowClassName = t->getRegexp();
}
} else if (*i_which == _T("keymap"))
;
else if (*i_which == _T("keymap2"))
isKeymap2 = true;
else
ASSERT(false);
if (!isEOL())
doesLoadDefaultKeySeq = true;
}
m_currentKeymap = m_setting->m_keymaps.add(
Keymap(type, name->getString(), windowClassName, windowTitleName,
NULL, NULL));
if (doesLoadDefaultKeySeq) {
Token *t = lookToken();
// <KEYMAP_PARENT>
if (*t == _T(":")) {
getToken();
t = getToken();
parentKeymap = m_setting->m_keymaps.searchByName(t->getString());
if (!parentKeymap)
throw ErrorMessage() << _T("`") << *t
<< _T("': unknown keymap name.");
}
if (!isEOL()) {
t = getToken();
if (!(*t == _T("=>") || *t == _T("=")))
throw ErrorMessage() << _T("`") << *t << _T("': syntax error.");
keySeq = SettingLoader::load_KEY_SEQUENCE();
}
}
if (keySeq == NULL) {
FunctionData *fd;
if (type == Keymap::Type_keymap && !isKeymap2)
fd = createFunctionData(_T("KeymapParent"));
else if (type == Keymap::Type_keymap && !isKeymap2)
fd = createFunctionData(_T("Undefined"));
else // (type == Keymap::Type_windowAnd || type == Keymap::Type_windowOr)
fd = createFunctionData(_T("KeymapParent"));
ASSERT( fd );
keySeq = m_setting->m_keySeqs.add(
KeySeq(name->getString()).add(ActionFunction(fd)));
}
m_currentKeymap->setIfNotYet(keySeq, parentKeymap);
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(bool *o_arg)
{
*o_arg = !(*getToken() == _T("false"));
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(int *o_arg)
{
*o_arg = getToken()->getNumber();
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(unsigned int *o_arg)
{
*o_arg = getToken()->getNumber();
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(long *o_arg)
{
*o_arg = getToken()->getNumber();
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(unsigned __int64 *o_arg)
{
*o_arg = getToken()->getNumber();
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(__int64 *o_arg)
{
*o_arg = getToken()->getNumber();
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(tstringq *o_arg)
{
*o_arg = getToken()->getString();
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(std::list<tstringq> *o_arg)
{
while (true) {
if (!lookToken()->isString())
return;
o_arg->push_back(getToken()->getString());
if (!lookToken()->isComma())
return;
getToken();
}
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(tregex *o_arg)
{
*o_arg = getToken()->getRegexp();
}
// <ARGUMENT_VK>
void SettingLoader::load_ARGUMENT(VKey *o_arg)
{
Token *t = getToken();
int vkey = 0;
while (true) {
if (t->isNumber()) {
vkey |= static_cast<BYTE>(t->getNumber());
break;
} else if (*t == _T("E-")) vkey |= VKey_extended;
else if (*t == _T("U-")) vkey |= VKey_released;
else if (*t == _T("D-")) vkey |= VKey_pressed;
else {
const VKeyTable *vkt;
for (vkt = g_vkeyTable; vkt->m_name; ++ vkt)
if (*t == vkt->m_name)
break;
if (!vkt->m_name)
throw ErrorMessage() << _T("`") << *t
<< _T("': unknown virtual key name.");
vkey |= vkt->m_code;
break;
}
t = getToken();
}
if (!(vkey & VKey_released) && !(vkey & VKey_pressed))
vkey |= VKey_released | VKey_pressed;
*o_arg = static_cast<VKey>(vkey);
}
// <ARGUMENT_WINDOW>
void SettingLoader::load_ARGUMENT(ToWindowType *o_arg)
{
Token *t = getToken();
if (t->isNumber()) {
if (ToWindowType_toBegin <= t->getNumber()) {
*o_arg = static_cast<ToWindowType>(t->getNumber());
return;
}
} else if (getTypeValue(o_arg, t->getString()))
return;
throw ErrorMessage() << _T("`") << *t << _T("': invalid target window.");
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(GravityType *o_arg)
{
Token *t = getToken();
if (getTypeValue(o_arg, t->getString()))
return;
throw ErrorMessage() << _T("`") << *t << _T("': unknown gravity symbol.");
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(MouseHookType *o_arg)
{
Token *t = getToken();
if (getTypeValue(o_arg, t->getString()))
return;
throw ErrorMessage() << _T("`") << *t << _T("': unknown MouseHookType symbol.");
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(MayuDialogType *o_arg)
{
Token *t = getToken();
if (getTypeValue(o_arg, t->getString()))
return;
throw ErrorMessage() << _T("`") << *t << _T("': unknown dialog box.");
}
// <ARGUMENT_LOCK>
void SettingLoader::load_ARGUMENT(ModifierLockType *o_arg)
{
Token *t = getToken();
if (getTypeValue(o_arg, t->getString()))
return;
throw ErrorMessage() << _T("`") << *t << _T("': unknown lock name.");
}
// <ARGUMENT_LOCK>
void SettingLoader::load_ARGUMENT(ToggleType *o_arg)
{
Token *t = getToken();
if (getTypeValue(o_arg, t->getString()))
return;
throw ErrorMessage() << _T("`") << *t << _T("': unknown toggle name.");
}
// <ARGUMENT_SHOW_WINDOW>
void SettingLoader::load_ARGUMENT(ShowCommandType *o_arg)
{
Token *t = getToken();
if (getTypeValue(o_arg, t->getString()))
return;
throw ErrorMessage() << _T("`") << *t << _T("': unknown show command.");
}
// <ARGUMENT_TARGET_WINDOW>
void SettingLoader::load_ARGUMENT(TargetWindowType *o_arg)
{
Token *t = getToken();
if (getTypeValue(o_arg, t->getString()))
return;
throw ErrorMessage() << _T("`") << *t
<< _T("': unknown target window type.");
}
// <bool>
void SettingLoader::load_ARGUMENT(BooleanType *o_arg)
{
Token *t = getToken();
if (getTypeValue(o_arg, t->getString()))
return;
throw ErrorMessage() << _T("`") << *t << _T("': must be true or false.");
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(LogicalOperatorType *o_arg)
{
Token *t = getToken();
if (getTypeValue(o_arg, t->getString()))
return;
throw ErrorMessage() << _T("`") << *t << _T("': must be 'or' or 'and'.");
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(Modifier *o_arg)
{
Modifier modifier;
for (int i = Modifier::Type_begin; i != Modifier::Type_end; ++ i)
modifier.dontcare(static_cast<Modifier::Type>(i));
*o_arg = load_MODIFIER(Modifier::Type_ASSIGN, modifier);
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(const Keymap **o_arg)
{
Token *t = getToken();
const Keymap *&keymap = *o_arg;
keymap = m_setting->m_keymaps.searchByName(t->getString());
if (!keymap)
throw ErrorMessage() << _T("`") << *t << _T("': unknown keymap name.");
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(const KeySeq **o_arg)
{
Token *t = getToken();
const KeySeq *&keySeq = *o_arg;
if (t->isOpenParen()) {
keySeq = load_KEY_SEQUENCE(_T(""), true);
getToken(); // close paren
} else if (*t == _T("$")) {
t = getToken();
keySeq = m_setting->m_keySeqs.searchByName(t->getString());
if (!keySeq)
throw ErrorMessage() << _T("`$") << *t << _T("': unknown keyseq name.");
} else
throw ErrorMessage() << _T("`") << *t << _T("': it is not keyseq.");
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(StrExprArg *o_arg)
{
Token *t = getToken();
StrExprArg::Type type = StrExprArg::Literal;
if (*t == _T("$") && t->isQuoted() == false
&& lookToken()->getType() == Token::Type_string) {
type = StrExprArg::Builtin;
t = getToken();
}
*o_arg = StrExprArg(t->getString(), type);
}
// <ARGUMENT>
void SettingLoader::load_ARGUMENT(WindowMonitorFromType *o_arg)
{
Token *t = getToken();
if (getTypeValue(o_arg, t->getString()))
return;
throw ErrorMessage() << _T("`") << *t
<< _T("': unknown monitor from type.");
}
// <KEY_SEQUENCE>
KeySeq *SettingLoader::load_KEY_SEQUENCE(
const tstringi &i_name, bool i_isInParen, Modifier::Type i_mode)
{
KeySeq keySeq(i_name);
while (!isEOL()) {
Modifier::Type mode;
Modifier modifier = load_MODIFIER(i_mode, m_defaultKeySeqModifier, &mode);
keySeq.setMode(mode);
Token *t = lookToken();
if (t->isCloseParen() && i_isInParen)
break;
else if (t->isOpenParen()) {
getToken(); // open paren
KeySeq *ks = load_KEY_SEQUENCE(_T(""), true, i_mode);
getToken(); // close paren
keySeq.add(ActionKeySeq(ks));
} else if (*t == _T("$")) { // <KEYSEQ_NAME>
getToken();
t = getToken();
KeySeq *ks = m_setting->m_keySeqs.searchByName(t->getString());
if (ks == NULL)
throw ErrorMessage() << _T("`$") << *t
<< _T("': unknown keyseq name.");
if (!ks->isCorrectMode(i_mode))
throw ErrorMessage()
<< _T("`$") << *t
<< _T("': Some of R-, IL-, IC-, NL-, CL-, SL-, KL-, MAX-, MIN-, MMAX-, MMIN-, T-, TS-, M0...M9- and L0...L9- are used in the keyseq. They are prohibited in this context.");
keySeq.setMode(ks->getMode());
keySeq.add(ActionKeySeq(ks));
} else if (*t == _T("&")) { // <FUNCTION_NAME>
getToken();
t = getToken();
// search function
ActionFunction af(createFunctionData(t->getString()), modifier);
if (af.m_functionData == NULL)
throw ErrorMessage() << _T("`&") << *t
<< _T("': unknown function name.");
af.m_functionData->load(this);
keySeq.add(af);
} else { // <KEYSEQ_MODIFIED_KEY_NAME>
ModifiedKey mkey;
mkey.m_modifier = modifier;
mkey.m_key = load_KEY_NAME();
keySeq.add(ActionKey(mkey));
}
}
return m_setting->m_keySeqs.add(keySeq);
}
// <KEY_ASSIGN>
void SettingLoader::load_KEY_ASSIGN()
{
typedef std::list<ModifiedKey> AssignedKeys;
AssignedKeys assignedKeys;
ModifiedKey mkey;
mkey.m_modifier =
load_MODIFIER(Modifier::Type_ASSIGN, m_defaultAssignModifier);
if (*lookToken() == _T("=")) {
getToken();
m_defaultKeySeqModifier = load_MODIFIER(Modifier::Type_KEYSEQ,
m_defaultKeySeqModifier);
m_defaultAssignModifier = mkey.m_modifier;
return;
}
while (true) {
mkey.m_key = load_KEY_NAME();
assignedKeys.push_back(mkey);
if (*lookToken() == _T("=>") || *lookToken() == _T("="))
break;
mkey.m_modifier =
load_MODIFIER(Modifier::Type_ASSIGN, m_defaultAssignModifier);
}
getToken();
ASSERT(m_currentKeymap);
KeySeq *keySeq = load_KEY_SEQUENCE();
for (AssignedKeys::iterator i = assignedKeys.begin();
i != assignedKeys.end(); ++ i)
m_currentKeymap->addAssignment(*i, keySeq);
}
// <EVENT_ASSIGN>
void SettingLoader::load_EVENT_ASSIGN()
{
std::list<ModifiedKey> assignedKeys;
ModifiedKey mkey;
mkey.m_modifier.dontcare(); //set all modifiers to dontcare
Token *t = getToken();
Key **e;
for (e = Event::events; *e; ++ e)
if (*t == (*e)->getName()) {
mkey.m_key = *e;
break;
}
if (!*e)
throw ErrorMessage() << _T("`") << *t << _T("': invalid event name.");
t = getToken();
if (!(*t == _T("=>") || *t == _T("=")))
throw ErrorMessage() << _T("`=' is expected.");
ASSERT(m_currentKeymap);
KeySeq *keySeq = load_KEY_SEQUENCE();
m_currentKeymap->addAssignment(mkey, keySeq);
}
// <MODIFIER_ASSIGNMENT>
void SettingLoader::load_MODIFIER_ASSIGNMENT()
{
// <MODIFIER_NAME>
Token *t = getToken();
Modifier::Type mt;
while (true) {
Keymap::AssignMode am = Keymap::AM_notModifier;
if (*t == _T("!") ) am = Keymap::AM_true, t = getToken();
else if (*t == _T("!!") ) am = Keymap::AM_oneShot, t = getToken();
else if (*t == _T("!!!")) am = Keymap::AM_oneShotRepeatable, t = getToken();
if (*t == _T("shift")) mt = Modifier::Type_Shift;
else if (*t == _T("alt") ||
*t == _T("meta") ||
*t == _T("menu") ) mt = Modifier::Type_Alt;
else if (*t == _T("control") ||
*t == _T("ctrl") ) mt = Modifier::Type_Control;
else if (*t == _T("windows") ||
*t == _T("win") ) mt = Modifier::Type_Windows;
else if (*t == _T("mod0") ) mt = Modifier::Type_Mod0;
else if (*t == _T("mod1") ) mt = Modifier::Type_Mod1;
else if (*t == _T("mod2") ) mt = Modifier::Type_Mod2;
else if (*t == _T("mod3") ) mt = Modifier::Type_Mod3;
else if (*t == _T("mod4") ) mt = Modifier::Type_Mod4;
else if (*t == _T("mod5") ) mt = Modifier::Type_Mod5;
else if (*t == _T("mod6") ) mt = Modifier::Type_Mod6;
else if (*t == _T("mod7") ) mt = Modifier::Type_Mod7;
else if (*t == _T("mod8") ) mt = Modifier::Type_Mod8;
else if (*t == _T("mod9") ) mt = Modifier::Type_Mod9;
else throw ErrorMessage() << _T("`") << *t
<< _T("': invalid modifier name.");
if (am == Keymap::AM_notModifier)
break;
m_currentKeymap->addModifier(mt, Keymap::AO_overwrite, am, NULL);
if (isEOL())
return;
t = getToken();
}
// <ASSIGN_OP>
t = getToken();
Keymap::AssignOperator ao;
if (*t == _T("=") ) ao = Keymap::AO_new;
else if (*t == _T("+=")) ao = Keymap::AO_add;
else if (*t == _T("-=")) ao = Keymap::AO_sub;
else throw ErrorMessage() << _T("`") << *t << _T("': is unknown operator.");
// <ASSIGN_MODE>? <KEY_NAME>
while (!isEOL()) {
// <ASSIGN_MODE>?
t = getToken();
Keymap::AssignMode am = Keymap::AM_normal;
if (*t == _T("!") ) am = Keymap::AM_true, t = getToken();
else if (*t == _T("!!") ) am = Keymap::AM_oneShot, t = getToken();
else if (*t == _T("!!!")) am = Keymap::AM_oneShotRepeatable, t = getToken();
// <KEY_NAME>
Key *key = m_setting->m_keyboard.searchKey(t->getString());
if (!key)
throw ErrorMessage() << _T("`") << *t << _T("': invalid key name.");
// we can ignore warning C4701
m_currentKeymap->addModifier(mt, ao, am, key);
if (ao == Keymap::AO_new)
ao = Keymap::AO_add;
}
}
// <KEYSEQ_DEFINITION>
void SettingLoader::load_KEYSEQ_DEFINITION()
{
if (*getToken() != _T("$"))
throw ErrorMessage() << _T("there must be `$' after `keyseq'");
Token *name = getToken();
if (*getToken() != _T("="))
throw ErrorMessage() << _T("there must be `=' after keyseq naem");
load_KEY_SEQUENCE(name->getString(), false, Modifier::Type_ASSIGN);
}
// <DEFINE>
void SettingLoader::load_DEFINE()
{
m_setting->m_symbols.insert(getToken()->getString());
}
// <IF>
void SettingLoader::load_IF()
{
if (!getToken()->isOpenParen())
throw ErrorMessage() << _T("there must be `(' after `if'.");
Token *t = getToken(); // <SYMBOL> or !
bool not = false;
if (*t == _T("!")) {
not = true;
t = getToken(); // <SYMBOL>
}
bool doesSymbolExist = (m_setting->m_symbols.find(t->getString())
!= m_setting->m_symbols.end());
bool doesRead = ((doesSymbolExist && !not) ||
(!doesSymbolExist && not));
if (0 < m_canReadStack.size())
doesRead = doesRead && m_canReadStack.back();
if (!getToken()->isCloseParen())
throw ErrorMessage() << _T("there must be `)'.");
m_canReadStack.push_back(doesRead);
if (!isEOL()) {
size_t len = m_canReadStack.size();
load_LINE();
if (len < m_canReadStack.size()) {
bool r = m_canReadStack.back();
m_canReadStack.pop_back();
m_canReadStack[len - 1] = r && doesRead;
} else if (len == m_canReadStack.size())
m_canReadStack.pop_back();
else
; // `end' found
}
}
// <ELSE> <ELSEIF>
void SettingLoader::load_ELSE(bool i_isElseIf, const tstringi &i_token)
{
bool doesRead = !load_ENDIF(i_token);
if (0 < m_canReadStack.size())
doesRead = doesRead && m_canReadStack.back();
m_canReadStack.push_back(doesRead);
if (!isEOL()) {
size_t len = m_canReadStack.size();
if (i_isElseIf)
load_IF();
else
load_LINE();
if (len < m_canReadStack.size()) {
bool r = m_canReadStack.back();
m_canReadStack.pop_back();
m_canReadStack[len - 1] = doesRead && r;
} else if (len == m_canReadStack.size())
m_canReadStack.pop_back();
else
; // `end' found
}
}
// <ENDIF>
bool SettingLoader::load_ENDIF(const tstringi &i_token)
{
if (m_canReadStack.size() == 0)
throw ErrorMessage() << _T("unbalanced `") << i_token << _T("'");
bool r = m_canReadStack.back();
m_canReadStack.pop_back();
return r;
}
// <LINE>
void SettingLoader::load_LINE()
{
Token *i_token = getToken();
// <COND_SYMBOL>
if (*i_token == _T("if") ||
*i_token == _T("and")) load_IF();
else if (*i_token == _T("else")) load_ELSE(false, i_token->getString());
else if (*i_token == _T("elseif") ||
*i_token == _T("elsif") ||
*i_token == _T("elif") ||
*i_token == _T("or")) load_ELSE(true, i_token->getString());
else if (*i_token == _T("endif")) load_ENDIF(_T("endif"));
else if (0 < m_canReadStack.size() && !m_canReadStack.back()) {
while (!isEOL())
getToken();
} else if (*i_token == _T("define")) load_DEFINE();
// <INCLUDE>
else if (*i_token == _T("include")) load_INCLUDE();
// <KEYBOARD_DEFINITION>
else if (*i_token == _T("def")) load_KEYBOARD_DEFINITION();
// <KEYMAP_DEFINITION>
else if (*i_token == _T("keymap") ||
*i_token == _T("keymap2") ||
*i_token == _T("window")) load_KEYMAP_DEFINITION(i_token);
// <KEY_ASSIGN>
else if (*i_token == _T("key")) load_KEY_ASSIGN();
// <EVENT_ASSIGN>
else if (*i_token == _T("event")) load_EVENT_ASSIGN();
// <MODIFIER_ASSIGNMENT>
else if (*i_token == _T("mod")) load_MODIFIER_ASSIGNMENT();
// <KEYSEQ_DEFINITION>
else if (*i_token == _T("keyseq")) load_KEYSEQ_DEFINITION();
else
throw ErrorMessage() << _T("syntax error `") << *i_token << _T("'.");
}
// prefix sort predicate used in load(const string &)
static bool prefixSortPred(const tstringi &i_a, const tstringi &i_b)
{
return i_b.size() < i_a.size();
}
/*
_UNICODE: read file (UTF-16 LE/BE, UTF-8, locale specific multibyte encoding)
_MBCS: read file
*/
bool readFile(tstring *o_data, const tstringi &i_filename)
{
// get size of file
#if 0
// bcc's _wstat cannot obtain file size
struct _stat sbuf;
if (_tstat(i_filename.c_str(), &sbuf) < 0 || sbuf.st_size == 0)
return false;
#else
// so, we use _wstati64 for bcc
struct stati64_t sbuf;
if (_tstati64(i_filename.c_str(), &sbuf) < 0 || sbuf.st_size == 0)
return false;
// following check is needed to cast sbuf.st_size to size_t safely
// this cast occurs because of above workaround for bcc
if (sbuf.st_size > UINT_MAX)
return false;
#endif
// open
FILE *fp = _tfopen(i_filename.c_str(), _T("rb"));
if (!fp)
return false;
// read file
Array<BYTE> buf(static_cast<size_t>(sbuf.st_size) + 1);
if (fread(buf.get(), static_cast<size_t>(sbuf.st_size), 1, fp) != 1) {
fclose(fp);
return false;
}
buf.get()[sbuf.st_size] = 0; // mbstowcs() requires null
// terminated string
#ifdef _UNICODE
//
if (buf.get()[0] == 0xffU && buf.get()[1] == 0xfeU &&
sbuf.st_size % 2 == 0)
// UTF-16 Little Endien
{
size_t size = static_cast<size_t>(sbuf.st_size) / 2;
o_data->resize(size);
BYTE *p = buf.get();
for (size_t i = 0; i < size; ++ i) {
wchar_t c = static_cast<wchar_t>(*p ++);
c |= static_cast<wchar_t>(*p ++) << 8;
(*o_data)[i] = c;
}
fclose(fp);
return true;
}
//
if (buf.get()[0] == 0xfeU && buf.get()[1] == 0xffU &&
sbuf.st_size % 2 == 0)
// UTF-16 Big Endien
{
size_t size = static_cast<size_t>(sbuf.st_size) / 2;
o_data->resize(size);
BYTE *p = buf.get();
for (size_t i = 0; i < size; ++ i) {
wchar_t c = static_cast<wchar_t>(*p ++) << 8;
c |= static_cast<wchar_t>(*p ++);
(*o_data)[i] = c;
}
fclose(fp);
return true;
}
// try multibyte charset
size_t wsize = mbstowcs(NULL, reinterpret_cast<char *>(buf.get()), 0);
if (wsize != size_t(-1)) {
Array<wchar_t> wbuf(wsize);
mbstowcs(wbuf.get(), reinterpret_cast<char *>(buf.get()), wsize);
o_data->assign(wbuf.get(), wbuf.get() + wsize);
fclose(fp);
return true;
}
// try UTF-8
{
Array<wchar_t> wbuf(static_cast<size_t>(sbuf.st_size));
BYTE *f = buf.get();
BYTE *end = buf.get() + sbuf.st_size;
wchar_t *d = wbuf.get();
enum { STATE_1, STATE_2of2, STATE_2of3, STATE_3of3 } state = STATE_1;
while (f != end) {
switch (state) {
case STATE_1:
if (!(*f & 0x80)) // 0xxxxxxx: 00-7F
*d++ = static_cast<wchar_t>(*f++);
else if ((*f & 0xe0) == 0xc0) { // 110xxxxx 10xxxxxx: 0080-07FF
*d = ((static_cast<wchar_t>(*f++) & 0x1f) << 6);
state = STATE_2of2;
} else if ((*f & 0xf0) == 0xe0) // 1110xxxx 10xxxxxx 10xxxxxx:
// 0800 - FFFF
{
*d = ((static_cast<wchar_t>(*f++) & 0x0f) << 12);
state = STATE_2of3;
} else
goto not_UTF_8;
break;
case STATE_2of2:
case STATE_3of3:
if ((*f & 0xc0) != 0x80)
goto not_UTF_8;
*d++ |= (static_cast<wchar_t>(*f++) & 0x3f);
state = STATE_1;
break;
case STATE_2of3:
if ((*f & 0xc0) != 0x80)
goto not_UTF_8;
*d |= ((static_cast<wchar_t>(*f++) & 0x3f) << 6);
state = STATE_3of3;
break;
}
}
o_data->assign(wbuf.get(), d);
fclose(fp);
return true;
not_UTF_8:
;
}
#endif // _UNICODE
// assume ascii
o_data->resize(static_cast<size_t>(sbuf.st_size));
for (off_t i = 0; i < sbuf.st_size; ++ i)
(*o_data)[i] = buf.get()[i];
fclose(fp);
return true;
}
// load (called from load(Setting *, const tstringi &) only)
void SettingLoader::load(const tstringi &i_filename)
{
m_currentFilename = i_filename;
tstring data;
if (!readFile(&data, m_currentFilename)) {
Acquire a(m_soLog);
*m_log << m_currentFilename << _T(" : error: file not found") << std::endl;
#if 1
*m_log << data << std::endl;
#endif
m_isThereAnyError = true;
return;
}
// prefix
if (m_prefixesRefCcount == 0) {
static const _TCHAR *prefixes[] = {
_T("="), _T("=>"), _T("&&"), _T("||"), _T(":"), _T("$"), _T("&"),
_T("-="), _T("+="), _T("!!!"), _T("!!"), _T("!"),
_T("E0-"), _T("E1-"), // <SCAN_CODE_EXTENTION>
_T("S-"), _T("A-"), _T("M-"), _T("C-"), // <BASIC_MODIFIER>
_T("W-"), _T("*"), _T("~"),
_T("U-"), _T("D-"), // <KEYSEQ_MODIFIER>
_T("R-"), _T("IL-"), _T("IC-"), _T("I-"), // <ASSIGN_MODIFIER>
_T("NL-"), _T("CL-"), _T("SL-"), _T("KL-"),
_T("MAX-"), _T("MIN-"), _T("MMAX-"), _T("MMIN-"),
_T("T-"), _T("TS-"),
_T("M0-"), _T("M1-"), _T("M2-"), _T("M3-"), _T("M4-"),
_T("M5-"), _T("M6-"), _T("M7-"), _T("M8-"), _T("M9-"),
_T("L0-"), _T("L1-"), _T("L2-"), _T("L3-"), _T("L4-"),
_T("L5-"), _T("L6-"), _T("L7-"), _T("L8-"), _T("L9-"),
};
m_prefixes = new std::vector<tstringi>;
for (size_t i = 0; i < NUMBER_OF(prefixes); ++ i)
m_prefixes->push_back(prefixes[i]);
std::sort(m_prefixes->begin(), m_prefixes->end(), prefixSortPred);
}
m_prefixesRefCcount ++;
// create parser
Parser parser(data.c_str(), data.size());
parser.setPrefixes(m_prefixes);
while (true) {
try {
if (!parser.getLine(&m_tokens))
break;
m_ti = m_tokens.begin();
} catch (ErrorMessage &e) {
if (m_log && m_soLog) {
Acquire a(m_soLog);
*m_log << m_currentFilename << _T("(") << parser.getLineNumber()
<< _T(") : error: ") << e << std::endl;
}
m_isThereAnyError = true;
continue;
}
try {
load_LINE();
if (!isEOL())
throw WarningMessage() << _T("back garbage is ignored.");
} catch (WarningMessage &w) {
if (m_log && m_soLog) {
Acquire a(m_soLog);
*m_log << i_filename << _T("(") << parser.getLineNumber()
<< _T(") : warning: ") << w << std::endl;
}
} catch (ErrorMessage &e) {
if (m_log && m_soLog) {
Acquire a(m_soLog);
*m_log << i_filename << _T("(") << parser.getLineNumber()
<< _T(") : error: ") << e << std::endl;
}
m_isThereAnyError = true;
}
}
// m_prefixes
-- m_prefixesRefCcount;
if (m_prefixesRefCcount == 0)
delete m_prefixes;
if (0 < m_canReadStack.size()) {
Acquire a(m_soLog);
*m_log << m_currentFilename << _T("(") << parser.getLineNumber()
<< _T(") : error: unbalanced `if'. ")
<< _T("you forget `endif', didn'i_token you?")
<< std::endl;
m_isThereAnyError = true;
}
}
// is the filename readable ?
bool SettingLoader::isReadable(const tstringi &i_filename,
int i_debugLevel) const
{
if (i_filename.empty())
return false;
#ifdef UNICODE
tifstream ist(to_string(i_filename).c_str());
#else
tifstream ist(i_filename.c_str());
#endif
if (ist.good()) {
if (m_log && m_soLog) {
Acquire a(m_soLog, 0);
*m_log << _T(" loading: ") << i_filename << std::endl;
}
return true;
} else {
if (m_log && m_soLog) {
Acquire a(m_soLog, i_debugLevel);
*m_log << _T("not found: ") << i_filename << std::endl;
}
return false;
}
}
#if 0
// get filename from registry
bool SettingLoader::getFilenameFromRegistry(tstringi *o_path) const
{
// get from registry
Registry reg(MAYU_REGISTRY_ROOT);
int index;
reg.read(_T(".mayuIndex"), &index, 0);
char buf[100];
snprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index);
if (!reg.read(buf, o_path))
return false;
// parse registry entry
Regexp getFilename(_T("^[^;]*;([^;]*);(.*)$"));
if (!getFilename.doesMatch(*o_path))
return false;
tstringi path = getFilename[1];
tstringi options = getFilename[2];
if (!(0 < path.size() && isReadable(path)))
return false;
*o_path = path;
// set symbols
Regexp symbol(_T("-D([^;]*)"));
while (symbol.doesMatch(options)) {
m_setting->symbols.insert(symbol[1]);
options = options.substr(symbol.subBegin(1));
}
return true;
}
#endif
// get filename
bool SettingLoader::getFilename(const tstringi &i_name, tstringi *o_path,
int i_debugLevel) const
{
// the default filename is ".mayu"
const tstringi &name = i_name.empty() ? tstringi(_T(".mayu")) : i_name;
bool isFirstTime = true;
while (true) {
// find file from registry
if (i_name.empty()) { // called not from 'include'
Setting::Symbols symbols;
if (getFilenameFromRegistry(NULL, o_path, &symbols)) {
if (o_path->empty())
// find file from home directory
{
HomeDirectories pathes;
getHomeDirectories(&pathes);
for (HomeDirectories::iterator
i = pathes.begin(); i != pathes.end(); ++ i) {
*o_path = *i + _T("\\") + name;
if (isReadable(*o_path, i_debugLevel))
goto add_symbols;
}
return false;
} else {
if (!isReadable(*o_path, i_debugLevel))
return false;
}
add_symbols:
for (Setting::Symbols::iterator
i = symbols.begin(); i != symbols.end(); ++ i)
m_setting->m_symbols.insert(*i);
return true;
}
}
if (!isFirstTime)
return false;
// find file from home directory
HomeDirectories pathes;
getHomeDirectories(&pathes);
for (HomeDirectories::iterator i = pathes.begin(); i != pathes.end(); ++ i) {
*o_path = *i + _T("\\") + name;
if (isReadable(*o_path, i_debugLevel))
return true;
}
if (!i_name.empty())
return false; // called by 'include'
if (!DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_setting),
NULL, dlgSetting_dlgProc))
return false;
}
}
// constructor
SettingLoader::SettingLoader(SyncObject *i_soLog, tostream *i_log)
: m_setting(NULL),
m_isThereAnyError(false),
m_soLog(i_soLog),
m_log(i_log),
m_currentKeymap(NULL)
{
m_defaultKeySeqModifier =
m_defaultAssignModifier.release(Modifier::Type_ImeComp);
}
/* load m_setting
If called by "include", 'filename' describes filename.
Otherwise the 'filename' is empty.
*/
bool SettingLoader::load(Setting *i_setting, const tstringi &i_filename)
{
m_setting = i_setting;
m_isThereAnyError = false;
tstringi path;
if (!getFilename(i_filename, &path)) {
if (i_filename.empty()) {
Acquire a(m_soLog);
getFilename(i_filename, &path, 0); // show filenames
return false;
} else
throw ErrorMessage() << _T("`") << i_filename
<< _T("': no such file or other error.");
}
// create global keymap's default keySeq
ActionFunction af(createFunctionData(_T("OtherWindowClass")));
KeySeq *globalDefault = m_setting->m_keySeqs.add(KeySeq(_T("")).add(af));
// add default keymap
m_currentKeymap = m_setting->m_keymaps.add(
Keymap(Keymap::Type_windowOr, _T("Global"), _T(""), _T(""),
globalDefault, NULL));
/*
// add keyboard layout name
if (filename.empty())
{
char keyboardLayoutName[KL_NAMELENGTH];
if (GetKeyboardLayoutName(keyboardLayoutName))
{
tstringi kl = tstringi(_T("KeyboardLayout/")) + keyboardLayoutName;
m_setting->symbols.insert(kl);
Acquire a(m_soLog);
*m_log << _T("KeyboardLayout: ") << kl << std::endl;
}
}
*/
// load
load(path);
// finalize
if (i_filename.empty())
m_setting->m_keymaps.adjustModifier(m_setting->m_keyboard);
return !m_isThereAnyError;
}
std::vector<tstringi> *SettingLoader::m_prefixes; // m_prefixes terminal symbol
size_t SettingLoader::m_prefixesRefCcount; /* reference count of
m_prefixes */
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// keyboard.h
#ifndef _KEYBOARD_H
# define _KEYBOARD_H
# include "misc.h"
# include "driver.h"
# include "stringtool.h"
# include <vector>
# include <list>
# include <map>
/// a scan code with flags
class ScanCode
{
public:
///
enum {
BREAK = KEYBOARD_INPUT_DATA::BREAK, /// key release flag
E0 = KEYBOARD_INPUT_DATA::E0, /// extended key flag
E1 = KEYBOARD_INPUT_DATA::E1, /// extended key flag
E0E1 = KEYBOARD_INPUT_DATA::E0E1, /// extended key flag
};
public:
USHORT m_scan; ///
USHORT m_flags; ///
public:
///
ScanCode() : m_scan(0), m_flags(0) { }
///
ScanCode(USHORT i_scan, USHORT i_flags)
: m_scan(i_scan), m_flags(i_flags) { }
///
bool operator==(const ScanCode &i_sc) const {
return (m_scan == i_sc.m_scan &&
(E0E1 & m_flags) == (E0E1 & i_sc.m_flags));
}
///
bool operator!=(const ScanCode &i_sc) const {
return !(*this == i_sc);
}
};
/// a key
class Key
{
public:
enum {
///
MAX_SCAN_CODES_SIZE = 4,
};
private:
///
typedef std::vector<tstringi> Names;
public:
/// if this key pressed physically
bool m_isPressed;
/// if this key pressed on Win32
bool m_isPressedOnWin32;
/// if this key pressed by assign
bool m_isPressedByAssign;
private:
/// key name
Names m_names;
/// key scan code length
size_t m_scanCodesSize;
/// key scan code
ScanCode m_scanCodes[MAX_SCAN_CODES_SIZE];
public:
///
Key()
: m_isPressed(false),
m_isPressedOnWin32(false),
m_isPressedByAssign(false),
m_scanCodesSize(0) { }
/// for Event::* only
Key(const tstringi &i_name)
: m_isPressed(false),
m_isPressedOnWin32(false),
m_isPressedByAssign(false),
m_scanCodesSize(0) {
addName(i_name);
addScanCode(ScanCode());
}
/// get key name (first name)
const tstringi &getName() const {
return m_names.front();
}
/// get scan codes
const ScanCode *getScanCodes() const {
return m_scanCodes;
}
///
size_t getScanCodesSize() const {
return m_scanCodesSize;
}
/// add a name of key
void addName(const tstringi &i_name);
/// add a scan code
void addScanCode(const ScanCode &i_sc);
/// initializer
Key &initialize();
/// equation by name
bool operator==(const tstringi &i_name) const;
///
bool operator!=(const tstringi &i_name) const {
return !(*this == i_name);
}
/// is the scan code of this key ?
bool isSameScanCode(const Key &i_key) const;
/// is the i_key's scan code the prefix of this key's scan code ?
bool isPrefixScanCode(const Key &i_key) const;
/// stream output
friend tostream &operator<<(tostream &i_ost, const Key &i_key);
/// <
bool operator<(const Key &i_key) const {
return getName() < i_key.getName();
}
};
///
class Modifier
{
///
typedef u_int64 MODIFIERS;
///
MODIFIERS m_modifiers;
///
MODIFIERS m_dontcares;
public:
///
enum Type {
Type_begin = 0, ///
Type_Shift = Type_begin, /// <BASIC_MODIFIER>
Type_Alt, /// <BASIC_MODIFIER>
Type_Control, /// <BASIC_MODIFIER>
Type_Windows, /// <BASIC_MODIFIER>
Type_BASIC, ///
Type_Up = Type_BASIC, /// <KEYSEQ_MODIFIER>
Type_Down, /// <KEYSEQ_MODIFIER>
Type_KEYSEQ, ///
Type_Repeat = Type_KEYSEQ, /// <ASSIGN_MODIFIER>
Type_ImeLock, /// <ASSIGN_MODIFIER>
Type_ImeComp, /// <ASSIGN_MODIFIER>
Type_NumLock, /// <ASSIGN_MODIFIER>
Type_CapsLock, /// <ASSIGN_MODIFIER>
Type_ScrollLock, /// <ASSIGN_MODIFIER>
Type_KanaLock, /// <ASSIGN_MODIFIER>
Type_Maximized, /// <ASSIGN_MODIFIER>
Type_Minimized, /// <ASSIGN_MODIFIER>
Type_MdiMaximized, /// <ASSIGN_MODIFIER>
Type_MdiMinimized, /// <ASSIGN_MODIFIER>
Type_Touchpad, /// <ASSIGN_MODIFIER>
Type_TouchpadSticky, /// <ASSIGN_MODIFIER>
Type_Mod0, /// <ASSIGN_MODIFIER>
Type_Mod1, /// <ASSIGN_MODIFIER>
Type_Mod2, /// <ASSIGN_MODIFIER>
Type_Mod3, /// <ASSIGN_MODIFIER>
Type_Mod4, /// <ASSIGN_MODIFIER>
Type_Mod5, /// <ASSIGN_MODIFIER>
Type_Mod6, /// <ASSIGN_MODIFIER>
Type_Mod7, /// <ASSIGN_MODIFIER>
Type_Mod8, /// <ASSIGN_MODIFIER>
Type_Mod9, /// <ASSIGN_MODIFIER>
Type_Lock0, /// <ASSIGN_MODIFIER>
Type_Lock1, /// <ASSIGN_MODIFIER>
Type_Lock2, /// <ASSIGN_MODIFIER>
Type_Lock3, /// <ASSIGN_MODIFIER>
Type_Lock4, /// <ASSIGN_MODIFIER>
Type_Lock5, /// <ASSIGN_MODIFIER>
Type_Lock6, /// <ASSIGN_MODIFIER>
Type_Lock7, /// <ASSIGN_MODIFIER>
Type_Lock8, /// <ASSIGN_MODIFIER>
Type_Lock9, /// <ASSIGN_MODIFIER>
Type_ASSIGN, ///
Type_end = Type_ASSIGN ///
};
public:
///
Modifier();
///
Modifier &on(Type i_type) {
return press(i_type);
}
///
Modifier &off(Type i_type) {
return release(i_type);
}
///
Modifier &press(Type i_type) {
m_modifiers |= ((MODIFIERS(1)) << i_type);
return care(i_type);
}
///
Modifier &release(Type i_type) {
m_modifiers &= ~((MODIFIERS(1)) << i_type);
return care(i_type);
}
///
Modifier &care(Type i_type) {
m_dontcares &= ~((MODIFIERS(1)) << i_type);
return *this;
}
///
Modifier &dontcare(Type i_type) {
m_dontcares |= ((MODIFIERS(1)) << i_type);
return *this;
}
/// set all modifiers to dontcare
Modifier &dontcare() {
m_dontcares = ~MODIFIERS(0);
return *this;
}
///
Modifier &on(Type i_type, bool i_isOn) {
return press(i_type, i_isOn);
}
///
Modifier &press(Type i_type, bool i_isPressed) {
return i_isPressed ? press(i_type) : release(i_type);
}
///
Modifier &care(Type i_type, bool i_doCare) {
return i_doCare ? care(i_type) : dontcare(i_type);
}
///
bool operator==(const Modifier &i_m) const {
return m_modifiers == i_m.m_modifiers && m_dontcares == i_m.m_dontcares;
}
/// add m's modifiers where this dontcare
void add(const Modifier &i_m);
//Modifier &operator+=(const Modifier &i_m);
/** does match. (except dontcare modifiers) (is the m included in the *this
set ?) */
bool doesMatch(const Modifier &i_m) const {
return ((m_modifiers | m_dontcares) == (i_m.m_modifiers | m_dontcares));
}
///
bool isOn(Type i_type) const {
return isPressed(i_type);
}
///
bool isPressed(Type i_type) const {
return !!(m_modifiers & ((MODIFIERS(1)) << i_type));
}
///
bool isDontcare(Type i_type) const {
return !!(m_dontcares & ((MODIFIERS(1)) << i_type));
}
/// stream output
friend tostream &operator<<(tostream &i_ost, const Modifier &i_m);
/// <
bool operator<(const Modifier &i_m) const {
return m_modifiers < i_m.m_modifiers ||
(m_modifiers == i_m.m_modifiers && m_dontcares < i_m.m_dontcares);
}
};
/// stream output
tostream &operator<<(tostream &i_ost, Modifier::Type i_type);
///
class ModifiedKey
{
public:
Modifier m_modifier; ///
Key *m_key; ///
public:
///
ModifiedKey() : m_key(NULL) { }
///
ModifiedKey(Key *i_key) : m_key(i_key) { }
///
ModifiedKey(const Modifier &i_modifier, Key *i_key)
: m_modifier(i_modifier), m_key(i_key) { }
///
bool operator==(const ModifiedKey &i_mk) const {
return m_modifier == i_mk.m_modifier && m_key == i_mk.m_key;
}
///
bool operator!=(const ModifiedKey &i_mk) const {
return !operator==(i_mk);
}
/// stream output
friend tostream &operator<<(tostream &i_ost, const ModifiedKey &i_mk);
/// <
bool operator<(const ModifiedKey &i_mk) const {
return *m_key < *i_mk.m_key ||
(!(*i_mk.m_key < *m_key) && m_modifier < i_mk.m_modifier);
}
};
///
class Keyboard
{
public:
/// keyboard modifiers (pointer into Keys)
typedef std::list<Key *> Mods;
private:
/** keyboard keys (hashed by first scan code).
Keys must be *list* of Key.
Because *pointers* into Keys exist anywhere in this program, the address
of Key's elements must be fixed. */
enum {
HASHED_KEYS_SIZE = 128, ///
};
typedef std::list<Key> Keys; ///
typedef std::map<tstringi, Key *> Aliases; /// key name aliases
///
class Substitute
{
public:
ModifiedKey m_mkeyFrom;
ModifiedKey m_mkeyTo;
public:
Substitute(const ModifiedKey &i_mkeyFrom,
const ModifiedKey &i_mkeyTo)
: m_mkeyFrom(i_mkeyFrom), m_mkeyTo(i_mkeyTo) {
}
};
typedef std::list<Substitute> Substitutes; /// substitutes
private:
Keys m_hashedKeys[HASHED_KEYS_SIZE]; ///
Aliases m_aliases; ///
Substitutes m_substitutes; ///
Key m_syncKey; /// key used to synchronize
private:
///
Mods m_mods[Modifier::Type_BASIC];
public:
///
class KeyIterator
{
///
Keys *m_hashedKeys;
///
size_t m_hashedKeysSize;
///
Keys::iterator m_i;
///
void next();
public:
///
KeyIterator(Keys *i_hashedKeys, size_t i_hashedKeysSize);
///
Key *operator *();
///
void operator++() {
next();
}
};
private:
///
Keys &getKeys(const Key &i_key);
public:
/// add a key
void addKey(const Key &i_key);
/// add a key name alias
void addAlias(const tstringi &i_aliasName, Key *i_key);
/// add substitute
void addSubstitute(const ModifiedKey &i_mkeyFrom,
const ModifiedKey &i_mkeyTo);
/// get a sync key
Key *getSyncKey() {
return &m_syncKey;
}
/// add a modifier key
void addModifier(Modifier::Type i_mt, Key * i_key);
/// search a key
Key *searchKey(const Key &i_key);
/// search a key (of which the key's scan code is the prefix)
Key *searchPrefixKey(const Key &i_key);
/// search a key by name
Key *searchKey(const tstringi &i_name);
/// search a key by non-alias name
Key *searchKeyByNonAliasName(const tstringi &i_name);
/// search a substitute
ModifiedKey searchSubstitute(const ModifiedKey &i_mkey);
/// get modifiers
Mods &getModifiers(Modifier::Type i_mt) {
return m_mods[i_mt];
}
/// get key iterator
KeyIterator getKeyIterator() {
return KeyIterator(&m_hashedKeys[0], HASHED_KEYS_SIZE);
}
};
#endif // !_KEYBOARD_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// engine.h
#ifndef _ENGINE_H
# define _ENGINE_H
# include "multithread.h"
# include "setting.h"
# include "msgstream.h"
# include "hook.h"
# include <set>
# include <queue>
enum {
///
WM_APP_engineNotify = WM_APP + 110,
};
///
enum EngineNotify {
EngineNotify_shellExecute, ///
EngineNotify_loadSetting, ///
EngineNotify_showDlg, ///
EngineNotify_helpMessage, ///
EngineNotify_setForegroundWindow, ///
EngineNotify_clearLog, ///
};
///
class Engine
{
private:
enum {
MAX_GENERATE_KEYBOARD_EVENTS_RECURSION_COUNT = 64, ///
MAX_KEYMAP_PREFIX_HISTORY = 64, ///
};
typedef Keymaps::KeymapPtrList KeymapPtrList; ///
/// focus of a thread
class FocusOfThread
{
public:
DWORD m_threadId; /// thread id
HWND m_hwndFocus; /** window that has focus on
the thread */
tstringi m_className; /// class name of hwndFocus
tstringi m_titleName; /// title name of hwndFocus
bool m_isConsole; /// is hwndFocus console ?
KeymapPtrList m_keymaps; /// keymaps
public:
///
FocusOfThread() : m_threadId(0), m_hwndFocus(NULL), m_isConsole(false) { }
};
typedef std::map<DWORD /*ThreadId*/, FocusOfThread> FocusOfThreads; ///
typedef std::list<DWORD /*ThreadId*/> ThreadIds; ///
/// current status in generateKeyboardEvents
class Current
{
public:
const Keymap *m_keymap; /// current keymap
ModifiedKey m_mkey; /// current processing key that user inputed
/// index in currentFocusOfThread->keymaps
Keymaps::KeymapPtrList::iterator m_i;
public:
///
bool isPressed() const {
return m_mkey.m_modifier.isOn(Modifier::Type_Down);
}
};
friend class FunctionParam;
/// part of keySeq
enum Part {
Part_all, ///
Part_up, ///
Part_down, ///
};
///
class EmacsEditKillLine
{
tstring m_buf; /// previous kill-line contents
public:
bool m_doForceReset; ///
private:
///
HGLOBAL makeNewKillLineBuf(const _TCHAR *i_data, int *i_retval);
public:
///
void reset() {
m_buf.resize(0);
}
/** EmacsEditKillLineFunc.
clear the contents of the clopboard
at that time, confirm if it is the result of the previous kill-line
*/
void func();
/// EmacsEditKillLinePred
int pred();
};
/// window positon for &WindowHMaximize, &WindowVMaximize
class WindowPosition
{
public:
///
enum Mode {
Mode_normal, ///
Mode_H, ///
Mode_V, ///
Mode_HV, ///
};
public:
HWND m_hwnd; ///
RECT m_rc; ///
Mode m_mode; ///
public:
///
WindowPosition(HWND i_hwnd, const RECT &i_rc, Mode i_mode)
: m_hwnd(i_hwnd), m_rc(i_rc), m_mode(i_mode) { }
};
typedef std::list<WindowPosition> WindowPositions;
typedef std::list<HWND> WindowsWithAlpha; /// windows for &WindowSetAlpha
enum InterruptThreadReason {
InterruptThreadReason_Terminate,
InterruptThreadReason_Pause,
InterruptThreadReason_Resume,
};
///
class InputHandler {
public:
typedef int (*INSTALL_HOOK)(INPUT_DETOUR i_keyboardDetour, Engine *i_engine, bool i_install);
static unsigned int WINAPI run(void *i_this);
InputHandler(INSTALL_HOOK i_installHook, INPUT_DETOUR i_inputDetour);
~InputHandler();
void run();
int start(Engine *i_engine);
int stop();
private:
unsigned m_threadId;
HANDLE m_hThread;
HANDLE m_hEvent;
INSTALL_HOOK m_installHook;
INPUT_DETOUR m_inputDetour;
Engine *m_engine;
};
private:
CriticalSection m_cs; /// criticalSection
// setting
HWND m_hwndAssocWindow; /** associated window (we post
message to it) */
Setting * volatile m_setting; /// setting
// engine thread state
HANDLE m_threadHandle;
unsigned m_threadId;
std::deque<KEYBOARD_INPUT_DATA> *m_inputQueue;
HANDLE m_queueMutex;
MSLLHOOKSTRUCT m_msllHookCurrent;
bool m_buttonPressed;
bool m_dragging;
InputHandler m_keyboardHandler;
InputHandler m_mouseHandler;
HANDLE m_readEvent; /** reading from mayu device
has been completed */
OVERLAPPED m_ol; /** for async read/write of
mayu device */
HANDLE m_hookPipe; /// named pipe for &SetImeString
HMODULE m_sts4mayu; /// DLL module for ThumbSense
HMODULE m_cts4mayu; /// DLL module for ThumbSense
bool volatile m_isLogMode; /// is logging mode ?
bool volatile m_isEnabled; /// is enabled ?
bool volatile m_isSynchronizing; /// is synchronizing ?
HANDLE m_eSync; /// event for synchronization
int m_generateKeyboardEventsRecursionGuard; /** guard against too many
recursion */
// current key state
Modifier m_currentLock; /// current lock key's state
int m_currentKeyPressCount; /** how many keys are pressed
phisically ? */
int m_currentKeyPressCountOnWin32; /** how many keys are pressed
on win32 ? */
Key *m_lastGeneratedKey; /// last generated key
Key *m_lastPressedKey[2]; /// last pressed key
ModifiedKey m_oneShotKey; /// one shot key
unsigned int m_oneShotRepeatableRepeatCount; /// repeat count of one shot key
bool m_isPrefix; /// is prefix ?
bool m_doesIgnoreModifierForPrefix; /** does ignore modifier key
when prefixed ? */
bool m_doesEditNextModifier; /** does edit next user input
key's modifier ? */
Modifier m_modifierForNextKey; /** modifier for next key if
above is true */
/** current keymaps.
<dl>
<dt>when &OtherWindowClass
<dd>currentKeymap becoms currentKeymaps[++ Current::i]
<dt>when &KeymapParent
<dd>currentKeymap becoms currentKeyamp->parentKeymap
<dt>other
<dd>currentKeyamp becoms *Current::i
</dl>
*/
const Keymap * volatile m_currentKeymap; /// current keymap
FocusOfThreads /*volatile*/ m_focusOfThreads; ///
FocusOfThread * volatile m_currentFocusOfThread; ///
FocusOfThread m_globalFocus; ///
HWND m_hwndFocus; /// current focus window
ThreadIds m_attachedThreadIds; ///
ThreadIds m_detachedThreadIds; ///
// for functions
KeymapPtrList m_keymapPrefixHistory; /// for &KeymapPrevPrefix
EmacsEditKillLine m_emacsEditKillLine; /// for &EmacsEditKillLine
const ActionFunction *m_afShellExecute; /// for &ShellExecute
WindowPositions m_windowPositions; ///
WindowsWithAlpha m_windowsWithAlpha; ///
tstring m_helpMessage; /// for &HelpMessage
tstring m_helpTitle; /// for &HelpMessage
int m_variable; /// for &Variable,
/// &Repeat
public:
tomsgstream &m_log; /** log stream (output to log
dialog's edit) */
public:
/// keyboard handler thread
static unsigned int WINAPI keyboardDetour(Engine *i_this, WPARAM i_wParam, LPARAM i_lParam);
/// mouse handler thread
static unsigned int WINAPI mouseDetour(Engine *i_this, WPARAM i_wParam, LPARAM i_lParam);
private:
///
unsigned int keyboardDetour(KBDLLHOOKSTRUCT *i_kid);
///
unsigned int mouseDetour(WPARAM i_message, MSLLHOOKSTRUCT *i_mid);
///
unsigned int injectInput(const KEYBOARD_INPUT_DATA *i_kid, const KBDLLHOOKSTRUCT *i_kidRaw);
private:
/// keyboard handler thread
static unsigned int WINAPI keyboardHandler(void *i_this);
///
void keyboardHandler();
/// check focus window
void checkFocusWindow();
/// is modifier pressed ?
bool isPressed(Modifier::Type i_mt);
/// fix modifier key
bool fixModifierKey(ModifiedKey *io_mkey, Keymap::AssignMode *o_am);
/// output to log
void outputToLog(const Key *i_key, const ModifiedKey &i_mkey,
int i_debugLevel);
/// genete modifier events
void generateModifierEvents(const Modifier &i_mod);
/// genete event
void generateEvents(Current i_c, const Keymap *i_keymap, Key *i_event);
/// generate keyboard event
void generateKeyEvent(Key *i_key, bool i_doPress, bool i_isByAssign);
///
void generateActionEvents(const Current &i_c, const Action *i_a,
bool i_doPress);
///
void generateKeySeqEvents(const Current &i_c, const KeySeq *i_keySeq,
Part i_part);
///
void generateKeyboardEvents(const Current &i_c);
///
void beginGeneratingKeyboardEvents(const Current &i_c, bool i_isModifier);
/// pop all pressed key on win32
void keyboardResetOnWin32();
/// get current modifiers
Modifier getCurrentModifiers(Key *i_key, bool i_isPressed);
/// describe bindings
void describeBindings();
/// update m_lastPressedKey
void updateLastPressedKey(Key *i_key);
/// set current keymap
void setCurrentKeymap(const Keymap *i_keymap,
bool i_doesAddToHistory = false);
/** open mayu device
@return true if mayu device successfully is opened
*/
bool open();
/// close mayu device
void close();
/// load/unload [sc]ts4mayu.dll
void manageTs4mayu(TCHAR *i_ts4mayuDllName, TCHAR *i_dependDllName,
bool i_load, HMODULE *i_pTs4mayu);
private:
// BEGINING OF FUNCTION DEFINITION
/// send a default key to Windows
void funcDefault(FunctionParam *i_param);
/// use a corresponding key of a parent keymap
void funcKeymapParent(FunctionParam *i_param);
/// use a corresponding key of a current window
void funcKeymapWindow(FunctionParam *i_param);
/// use a corresponding key of the previous prefixed keymap
void funcKeymapPrevPrefix(FunctionParam *i_param, int i_previous);
/// use a corresponding key of an other window class, or use a default key
void funcOtherWindowClass(FunctionParam *i_param);
/// prefix key
void funcPrefix(FunctionParam *i_param, const Keymap *i_keymap,
BooleanType i_doesIgnoreModifiers = BooleanType_true);
/// other keymap's key
void funcKeymap(FunctionParam *i_param, const Keymap *i_keymap);
/// sync
void funcSync(FunctionParam *i_param);
/// toggle lock
void funcToggle(FunctionParam *i_param, ModifierLockType i_lock,
ToggleType i_toggle = ToggleType_toggle);
/// edit next user input key's modifier
void funcEditNextModifier(FunctionParam *i_param,
const Modifier &i_modifier);
/// variable
void funcVariable(FunctionParam *i_param, int i_mag, int i_inc);
/// repeat N times
void funcRepeat(FunctionParam *i_param, const KeySeq *i_keySeq,
int i_max = 10);
/// undefined (bell)
void funcUndefined(FunctionParam *i_param);
/// ignore
void funcIgnore(FunctionParam *i_param);
/// post message
void funcPostMessage(FunctionParam *i_param, ToWindowType i_window,
UINT i_message, WPARAM i_wParam, LPARAM i_lParam);
/// ShellExecute
void funcShellExecute(FunctionParam *i_param, const StrExprArg &i_operation,
const StrExprArg &i_file, const StrExprArg &i_parameters,
const StrExprArg &i_directory,
ShowCommandType i_showCommand);
/// SetForegroundWindow
void funcSetForegroundWindow(FunctionParam *i_param,
const tregex &i_windowClassName,
LogicalOperatorType i_logicalOp
= LogicalOperatorType_and,
const tregex &i_windowTitleName
= tregex(_T(".*")));
/// load setting
void funcLoadSetting(FunctionParam *i_param,
const StrExprArg &i_name = StrExprArg());
/// virtual key
void funcVK(FunctionParam *i_param, VKey i_vkey);
/// wait
void funcWait(FunctionParam *i_param, int i_milliSecond);
/// investigate WM_COMMAND, WM_SYSCOMMAND
void funcInvestigateCommand(FunctionParam *i_param);
/// show mayu dialog box
void funcMayuDialog(FunctionParam *i_param, MayuDialogType i_dialog,
ShowCommandType i_showCommand);
/// describe bindings
void funcDescribeBindings(FunctionParam *i_param);
/// show help message
void funcHelpMessage(FunctionParam *i_param,
const StrExprArg &i_title = StrExprArg(),
const StrExprArg &i_message = StrExprArg());
/// show variable
void funcHelpVariable(FunctionParam *i_param, const StrExprArg &i_title);
/// raise window
void funcWindowRaise(FunctionParam *i_param,
TargetWindowType i_twt = TargetWindowType_overlapped);
/// lower window
void funcWindowLower(FunctionParam *i_param,
TargetWindowType i_twt = TargetWindowType_overlapped);
/// minimize window
void funcWindowMinimize(FunctionParam *i_param, TargetWindowType i_twt
= TargetWindowType_overlapped);
/// maximize window
void funcWindowMaximize(FunctionParam *i_param, TargetWindowType i_twt
= TargetWindowType_overlapped);
/// maximize window horizontally
void funcWindowHMaximize(FunctionParam *i_param, TargetWindowType i_twt
= TargetWindowType_overlapped);
/// maximize window virtically
void funcWindowVMaximize(FunctionParam *i_param, TargetWindowType i_twt
= TargetWindowType_overlapped);
/// maximize window virtically or horizontally
void funcWindowHVMaximize(FunctionParam *i_param, BooleanType i_isHorizontal,
TargetWindowType i_twt
= TargetWindowType_overlapped);
/// move window
void funcWindowMove(FunctionParam *i_param, int i_dx, int i_dy,
TargetWindowType i_twt
= TargetWindowType_overlapped);
/// move window to ...
void funcWindowMoveTo(FunctionParam *i_param, GravityType i_gravityType,
int i_dx, int i_dy, TargetWindowType i_twt
= TargetWindowType_overlapped);
/// move window visibly
void funcWindowMoveVisibly(FunctionParam *i_param,
TargetWindowType i_twt
= TargetWindowType_overlapped);
/// move window to other monitor
void funcWindowMonitorTo(FunctionParam *i_param,
WindowMonitorFromType i_fromType, int i_monitor,
BooleanType i_adjustPos = BooleanType_true,
BooleanType i_adjustSize = BooleanType_false);
/// move window to other monitor
void funcWindowMonitor(FunctionParam *i_param, int i_monitor,
BooleanType i_adjustPos = BooleanType_true,
BooleanType i_adjustSize = BooleanType_false);
///
void funcWindowClingToLeft(FunctionParam *i_param,
TargetWindowType i_twt
= TargetWindowType_overlapped);
///
void funcWindowClingToRight(FunctionParam *i_param,
TargetWindowType i_twt
= TargetWindowType_overlapped);
///
void funcWindowClingToTop(FunctionParam *i_param,
TargetWindowType i_twt
= TargetWindowType_overlapped);
///
void funcWindowClingToBottom(FunctionParam *i_param,
TargetWindowType i_twt
= TargetWindowType_overlapped);
/// close window
void funcWindowClose(FunctionParam *i_param,
TargetWindowType i_twt = TargetWindowType_overlapped);
/// toggle top-most flag of the window
void funcWindowToggleTopMost(FunctionParam *i_param);
/// identify the window
void funcWindowIdentify(FunctionParam *i_param);
/// set alpha blending parameter to the window
void funcWindowSetAlpha(FunctionParam *i_param, int i_alpha);
/// redraw the window
void funcWindowRedraw(FunctionParam *i_param);
/// resize window to
void funcWindowResizeTo(FunctionParam *i_param, int i_width, int i_height,
TargetWindowType i_twt
= TargetWindowType_overlapped);
/// move the mouse cursor
void funcMouseMove(FunctionParam *i_param, int i_dx, int i_dy);
/// send a mouse-wheel-message to Windows
void funcMouseWheel(FunctionParam *i_param, int i_delta);
/// convert the contents of the Clipboard to upper case or lower case
void funcClipboardChangeCase(FunctionParam *i_param,
BooleanType i_doesConvertToUpperCase);
/// convert the contents of the Clipboard to upper case
void funcClipboardUpcaseWord(FunctionParam *i_param);
/// convert the contents of the Clipboard to lower case
void funcClipboardDowncaseWord(FunctionParam *i_param);
/// set the contents of the Clipboard to the string
void funcClipboardCopy(FunctionParam *i_param, const StrExprArg &i_text);
///
void funcEmacsEditKillLinePred(FunctionParam *i_param,
const KeySeq *i_keySeq1,
const KeySeq *i_keySeq2);
///
void funcEmacsEditKillLineFunc(FunctionParam *i_param);
/// clear log
void funcLogClear(FunctionParam *i_param);
/// recenter
void funcRecenter(FunctionParam *i_param);
/// Direct SSTP
void funcDirectSSTP(FunctionParam *i_param,
const tregex &i_name,
const StrExprArg &i_protocol,
const std::list<tstringq> &i_headers);
/// PlugIn
void funcPlugIn(FunctionParam *i_param,
const StrExprArg &i_dllName,
const StrExprArg &i_funcName = StrExprArg(),
const StrExprArg &i_funcParam = StrExprArg(),
BooleanType i_doesCreateThread = BooleanType_false);
/// set IME open status
void funcSetImeStatus(FunctionParam *i_param, ToggleType i_toggle = ToggleType_toggle);
/// set string to IME
void funcSetImeString(FunctionParam *i_param, const StrExprArg &i_data);
/// enter to mouse event hook mode
void funcMouseHook(FunctionParam *i_param, MouseHookType i_hookType, int i_hookParam);
/// cancel prefix
void funcCancelPrefix(FunctionParam *i_param);
// END OF FUNCTION DEFINITION
# define FUNCTION_FRIEND
# include "functions.h"
# undef FUNCTION_FRIEND
public:
///
Engine(tomsgstream &i_log);
///
~Engine();
/// start/stop keyboard handler thread
void start();
///
void stop();
/// pause keyboard handler thread and close device
bool pause();
/// resume keyboard handler thread and re-open device
bool resume();
/// do some procedure before quit which must be done synchronously
/// (i.e. not on WM_QUIT)
bool prepairQuit();
/// logging mode
void enableLogMode(bool i_isLogMode = true) {
m_isLogMode = i_isLogMode;
}
///
void disableLogMode() {
m_isLogMode = false;
}
/// enable/disable engine
void enable(bool i_isEnabled = true) {
m_isEnabled = i_isEnabled;
}
///
void disable() {
m_isEnabled = false;
}
///
bool getIsEnabled() const {
return m_isEnabled;
}
/// associated window
void setAssociatedWndow(HWND i_hwnd) {
m_hwndAssocWindow = i_hwnd;
}
/// associated window
HWND getAssociatedWndow() const {
return m_hwndAssocWindow;
}
/// setting
bool setSetting(Setting *i_setting);
/// focus
bool setFocus(HWND i_hwndFocus, DWORD i_threadId,
const tstringi &i_className,
const tstringi &i_titleName, bool i_isConsole);
/// lock state
bool setLockState(bool i_isNumLockToggled, bool i_isCapsLockToggled,
bool i_isScrollLockToggled, bool i_isKanaLockToggled,
bool i_isImeLockToggled, bool i_isImeCompToggled);
/// show
void checkShow(HWND i_hwnd);
bool setShow(bool i_isMaximized, bool i_isMinimized, bool i_isMDI);
/// sync
bool syncNotify();
/// thread attach notify
bool threadAttachNotify(DWORD i_threadId);
/// thread detach notify
bool threadDetachNotify(DWORD i_threadId);
/// shell execute
void shellExecute();
/// get help message
void getHelpMessages(tstring *o_helpMessage, tstring *o_helpTitle);
/// command notify
template <typename WPARAM_T, typename LPARAM_T>
void commandNotify(HWND i_hwnd, UINT i_message, WPARAM_T i_wParam,
LPARAM_T i_lParam)
{
Acquire b(&m_log, 0);
HWND hf = m_hwndFocus;
if (!hf)
return;
if (GetWindowThreadProcessId(hf, NULL) ==
GetWindowThreadProcessId(m_hwndAssocWindow, NULL))
return; // inhibit the investigation of MADO TSUKAI NO YUUTSU
const _TCHAR *target = NULL;
int number_target = 0;
if (i_hwnd == hf)
target = _T("ToItself");
else if (i_hwnd == GetParent(hf))
target = _T("ToParentWindow");
else {
// Function::toMainWindow
HWND h = hf;
while (true) {
HWND p = GetParent(h);
if (!p)
break;
h = p;
}
if (i_hwnd == h)
target = _T("ToMainWindow");
else {
// Function::toOverlappedWindow
HWND h = hf;
while (h) {
#ifdef MAYU64
LONG_PTR style = GetWindowLongPtr(h, GWL_STYLE);
#else
LONG style = GetWindowLong(h, GWL_STYLE);
#endif
if ((style & WS_CHILD) == 0)
break;
h = GetParent(h);
}
if (i_hwnd == h)
target = _T("ToOverlappedWindow");
else {
// number
HWND h = hf;
for (number_target = 0; h; number_target ++, h = GetParent(h))
if (i_hwnd == h)
break;
return;
}
}
}
m_log << _T("&PostMessage(");
if (target)
m_log << target;
else
m_log << number_target;
m_log << _T(", ") << i_message
<< _T(", 0x") << std::hex << i_wParam
<< _T(", 0x") << i_lParam << _T(") # hwnd = ")
<< reinterpret_cast<int>(i_hwnd) << _T(", ")
<< _T("message = ") << std::dec;
if (i_message == WM_COMMAND)
m_log << _T("WM_COMMAND, ");
else if (i_message == WM_SYSCOMMAND)
m_log << _T("WM_SYSCOMMAND, ");
else
m_log << i_message << _T(", ");
m_log << _T("wNotifyCode = ") << HIWORD(i_wParam) << _T(", ")
<< _T("wID = ") << LOWORD(i_wParam) << _T(", ")
<< _T("hwndCtrl = 0x") << std::hex << i_lParam << std::dec << std::endl;
}
/// get current window class name
const tstringi &getCurrentWindowClassName() const {
return m_currentFocusOfThread->m_className;
}
/// get current window title name
const tstringi &getCurrentWindowTitleName() const {
return m_currentFocusOfThread->m_titleName;
}
};
///
class FunctionParam
{
public:
bool m_isPressed; /// is key pressed ?
HWND m_hwnd; ///
Engine::Current m_c; /// new context
bool m_doesNeedEndl; /// need endl ?
const ActionFunction *m_af; ///
};
#endif // !_ENGINE_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// driver.h
#ifndef _DRIVER_H
# define _DRIVER_H
# include <winioctl.h>
/// mayu device file name
# define MAYU_DEVICE_FILE_NAME _T("\\\\.\\MayuDetour1")
///
# define MAYU_DRIVER_NAME _T("mayud")
/// Ioctl value
#include "d/ioctl.h"
/// derived from w2kddk/inc/ntddkbd.h
class KEYBOARD_INPUT_DATA
{
public:
///
enum {
/// key release flag
BREAK = 1,
/// extended key flag
E0 = 2,
/// extended key flag
E1 = 4,
/// extended key flag (E0 | E1)
E0E1 = 6,
///
TERMSRV_SET_LED = 8,
/// Define the keyboard overrun MakeCode.
KEYBOARD_OVERRUN_MAKE_CODE_ = 0xFF,
};
public:
/** Unit number. E.g., for \Device\KeyboardPort0 the unit is '0', for
\Device\KeyboardPort1 the unit is '1', and so on. */
USHORT UnitId;
/** The "make" scan code (key depression). */
USHORT MakeCode;
/** The flags field indicates a "break" (key release) and other miscellaneous
scan code information defined above. */
USHORT Flags;
///
USHORT Reserved;
/** Device-specific additional information for the event. */
ULONG ExtraInformation;
};
#endif // !_DRIVER_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// compiler_specific.h
#ifndef _COMPILER_SPECIFIC_H
# define _COMPILER_SPECIFIC_H
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Microsoft Visual C++ 6.0
# if defined(_MSC_VER)
// C4061 enum 'identifier' is not handled by case label
// C4100 argument 'identifier' is not used
// C4132 const 'object' must be initialized
// C4552 'operator' : operator has no effect
// C4701 local variable 'name' may be uninitialized
// C4706 condition is a result of a assign
// C4786 identifier is truncated into 255 chars (in debug information)
# pragma warning(disable : 4061 4100 4132 4552 4701 4706 4786)
# define setmode _setmode
# define for if (false) ; else for
# define stati64_t _stati64
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Borland C++ 5.5.1
# elif defined(__BORLANDC__)
// W8004 'identifier' is assigned a value that is never used in function
// W8022 'identifier' hides virtual function 'function'
// W8027 Functions containing ... are not expanded inline
// W8030 Temporary used for parameter 'identifier'
// in call to 'function' in function
// W8060 Possibly incorrect assignment in function
// W8070 Function should return a value in function
// W8084 Suggest parentheses to clarify precedence in function
# pragma warn -8004
# pragma warn -8022
# pragma warn -8027
# pragma warn -8030
# pragma warn -8060
# pragma warn -8070
# pragma warn -8084
# ifdef _UNICODE
extern wchar_t **_wargv;
# endif
# ifdef _MBCS
# define _istcntrl iscntrl
# endif
# include <windows.h>
# include <tchar.h>
extern "C"
{
int WINAPI _tWinMain(HINSTANCE i_hInstance, HINSTANCE i_hPrevInstance,
LPTSTR i_lpszCmdLine, int i_nCmdShow);
}
# define stati64_t stati64
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Cygwin 1.1 (gcc 2.95.2)
# elif defined(__CYGWIN__)
# error "I don't know the details of this compiler... Plz hack."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Watcom C++
# elif defined(__WATCOMC__)
# error "I don't know the details of this compiler... Plz hack."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// unknown
# else
# error "I don't know the details of this compiler... Plz hack."
# endif
#endif // _COMPILER_SPECIFIC_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// hook.cpp
#define _HOOK_CPP
#include "misc.h"
#include "hook.h"
#include "stringtool.h"
#include <locale.h>
#include <imm.h>
#include <richedit.h>
///
#define HOOK_DATA_NAME _T("{08D6E55C-5103-4e00-8209-A1C4AB13BBEF}") _T(VERSION)
#ifdef _WIN64
#define HOOK_DATA_NAME_ARCH _T("{290C0D51-8AEE-403d-9172-E43D46270996}") _T(VERSION)
#else // !_WIN64
#define HOOK_DATA_NAME_ARCH _T("{716A5DEB-CB02-4438-ABC8-D00E48673E45}") _T(VERSION)
#endif // !_WIN64
// Some applications use different values for below messages
// when double click of title bar.
#define SC_MAXIMIZE2 (SC_MAXIMIZE + 2)
#define SC_MINIMIZE2 (SC_MINIMIZE + 2)
#define SC_RESTORE2 (SC_RESTORE + 2)
// Debug Macros
#ifdef NDEBUG
#define HOOK_RPT0(msg)
#define HOOK_RPT1(msg, arg1)
#define HOOK_RPT2(msg, arg1, arg2)
#define HOOK_RPT3(msg, arg1, arg2, arg3)
#define HOOK_RPT4(msg, arg1, arg2, arg3, arg4)
#define HOOK_RPT5(msg, arg1, arg2, arg3, arg4, arg5)
#else
#define HOOK_RPT0(msg) if (g.m_isLogging) { _RPT0(_CRT_WARN, msg); }
#define HOOK_RPT1(msg, arg1) if (g.m_isLogging) { _RPT1(_CRT_WARN, msg, arg1); }
#define HOOK_RPT2(msg, arg1, arg2) if (g.m_isLogging) { _RPT2(_CRT_WARN, msg, arg1, arg2); }
#define HOOK_RPT3(msg, arg1, arg2, arg3) if (g.m_isLogging) { _RPT3(_CRT_WARN, msg, arg1, arg2, arg3); }
#define HOOK_RPT4(msg, arg1, arg2, arg3, arg4) if (g.m_isLogging) { _RPT4(_CRT_WARN, msg, arg1, arg2, arg3, arg4); }
#define HOOK_RPT5(msg, arg1, arg2, arg3, arg4, arg5) if (g.m_isLogging) { _RPT5(_CRT_WARN, msg, arg1, arg2, arg3, arg4, arg5); }
#endif
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Global Variables
DllExport HookData *g_hookData; ///
///
class HookDataArch
{
public:
HHOOK m_hHookGetMessage; ///
HHOOK m_hHookCallWndProc; ///
};
static HookDataArch *s_hookDataArch;
struct Globals {
HANDLE m_hHookData; ///
HANDLE m_hHookDataArch; ///
HWND m_hwndFocus; ///
HINSTANCE m_hInstDLL; ///
bool m_isInMenu; ///
UINT m_WM_MAYU_MESSAGE; ///
bool m_isImeLock; ///
bool m_isImeCompositioning; ///
HHOOK m_hHookMouseProc; ///
HHOOK m_hHookKeyboardProc; ///
INPUT_DETOUR m_keyboardDetour;
INPUT_DETOUR m_mouseDetour;
Engine *m_engine;
DWORD m_hwndTaskTray; ///
HANDLE m_hMailslot;
bool m_isInitialized;
#ifdef HOOK_LOG_TO_FILE
HANDLE m_logFile;
#endif // HOOK_LOG_TO_FILE
#ifndef NDEBUG
bool m_isLogging;
_TCHAR m_moduleName[GANA_MAX_PATH];
#endif // !NDEBUG
};
static Globals g;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Prototypes
static void notifyThreadDetach();
static void notifyShow(NotifyShow::Show i_show, bool i_isMDI);
static void notifyLog(_TCHAR *i_msg);
static bool mapHookData(bool i_isYamy);
static void unmapHookData();
static bool initialize(bool i_isYamy);
static bool notify(void *i_data, size_t i_dataSize);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Functions
#ifdef HOOK_LOG_TO_FILE
static void WriteToLog(const char *data)
{
char buf[1024];
DWORD count;
WideCharToMultiByte(CP_THREAD_ACP, 0, g.m_moduleName, -1, buf, NUMBER_OF(buf), NULL, NULL);
strcat(buf, ": ");
strcat(buf, data);
SetFilePointer(g.m_logFile, 0, NULL, FILE_END);
WriteFile(g.m_logFile, buf, strlen(buf), &count, NULL);
FlushFileBuffers(g.m_logFile);
}
#else // !HOOK_LOG_TO_FILE
#define WriteToLog(data)
#endif // !HOOK_LOG_TO_FILE
bool initialize(bool i_isYamy)
{
#ifndef NDEBUG
_TCHAR path[GANA_MAX_PATH];
GetModuleFileName(NULL, path, GANA_MAX_PATH);
_tsplitpath_s(path, NULL, 0, NULL, 0, g.m_moduleName, GANA_MAX_PATH, NULL, 0);
if (_tcsnicmp(g.m_moduleName, _T("Dbgview"), sizeof(_T("Dbgview"))/sizeof(_TCHAR)) != 0 &&
_tcsnicmp(g.m_moduleName, _T("windbg"), sizeof(_T("windbg"))/sizeof(_TCHAR)) != 0) {
g.m_isLogging = true;
}
#endif // !NDEBUG
#ifdef HOOK_LOG_TO_FILE
_TCHAR logFileName[GANA_MAX_PATH];
GetEnvironmentVariable(_T("USERPROFILE"), logFileName, NUMBER_OF(logFileName));
_tcsncat(logFileName, _T("\\AppData\\LocalLow\\yamydll.txt"), _tcslen(_T("\\AppData\\LocalLow\\yamydll.log")));
g.m_logFile = CreateFile(logFileName, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
#endif // HOOK_LOG_TO_FILE
WriteToLog("try to open mailslot\r\n");
g.m_hMailslot =
CreateFile(NOTIFY_MAILSLOT_NAME, GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
(SECURITY_ATTRIBUTES *)NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL);
if (g.m_hMailslot == INVALID_HANDLE_VALUE) {
HOOK_RPT2("MAYU: %S create mailslot failed(0x%08x)\r\n", g.m_moduleName, GetLastError());
WriteToLog("open mailslot NG\r\n");
} else {
HOOK_RPT1("MAYU: %S create mailslot successed\r\n", g.m_moduleName);
WriteToLog("open mailslot OK\r\n");
}
if (!mapHookData(i_isYamy))
return false;
_tsetlocale(LC_ALL, _T(""));
g.m_WM_MAYU_MESSAGE =
RegisterWindowMessage(addSessionId(WM_MAYU_MESSAGE_NAME).c_str());
g.m_hwndTaskTray = g_hookData->m_hwndTaskTray;
if (!i_isYamy) {
NotifyThreadAttach ntd;
ntd.m_type = Notify::Type_threadAttach;
ntd.m_threadId = GetCurrentThreadId();
notify(&ntd, sizeof(ntd));
}
g.m_isInitialized = true;
return true;
}
/// EntryPoint
BOOL WINAPI DllMain(HINSTANCE i_hInstDLL, DWORD i_fdwReason,
LPVOID /* i_lpvReserved */)
{
switch (i_fdwReason) {
case DLL_PROCESS_ATTACH: {
#ifndef NDEBUG
g.m_isLogging = false;
#endif // !NDEBUG
g.m_isInitialized = false;
g.m_hInstDLL = i_hInstDLL;
break;
}
case DLL_THREAD_ATTACH:
break;
case DLL_PROCESS_DETACH:
notifyThreadDetach();
unmapHookData();
if (g.m_hMailslot != INVALID_HANDLE_VALUE) {
CloseHandle(g.m_hMailslot);
g.m_hMailslot = INVALID_HANDLE_VALUE;
}
#ifdef HOOK_LOG_TO_FILE
if (g.m_logFile != INVALID_HANDLE_VALUE) {
CloseHandle(g.m_logFile);
g.m_logFile = INVALID_HANDLE_VALUE;
}
#endif // HOOK_LOG_TO_FILE
break;
case DLL_THREAD_DETACH:
notifyThreadDetach();
break;
default:
break;
}
return TRUE;
}
/// map hook data
static bool mapHookData(bool i_isYamy)
{
DWORD access = FILE_MAP_READ;
if (i_isYamy) {
access |= FILE_MAP_WRITE;
g.m_hHookData = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(HookData), addSessionId(HOOK_DATA_NAME).c_str());
g.m_hHookDataArch = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(HookDataArch), addSessionId(HOOK_DATA_NAME_ARCH).c_str());
} else {
g.m_hHookData = OpenFileMapping(access, FALSE, addSessionId(HOOK_DATA_NAME).c_str());
g.m_hHookDataArch = OpenFileMapping(access, FALSE, addSessionId(HOOK_DATA_NAME_ARCH).c_str());
}
if (g.m_hHookData == NULL || g.m_hHookDataArch == NULL) {
unmapHookData();
return false;
}
g_hookData = (HookData *)MapViewOfFile(g.m_hHookData, access, 0, 0, sizeof(HookData));
s_hookDataArch = (HookDataArch *)MapViewOfFile(g.m_hHookDataArch, access, 0, 0, sizeof(HookDataArch));
if (g_hookData == NULL || s_hookDataArch == NULL) {
unmapHookData();
return false;
}
return true;
}
/// unmap hook data
static void unmapHookData()
{
if (g_hookData)
UnmapViewOfFile(g_hookData);
g_hookData = NULL;
if (g.m_hHookData)
CloseHandle(g.m_hHookData);
g.m_hHookData = NULL;
if (s_hookDataArch)
UnmapViewOfFile(s_hookDataArch);
s_hookDataArch = NULL;
if (g.m_hHookDataArch)
CloseHandle(g.m_hHookDataArch);
g.m_hHookDataArch = NULL;
}
/// notify
bool notify(void *i_data, size_t i_dataSize)
{
COPYDATASTRUCT cd;
#ifdef MAYU64
DWORD_PTR result;
#else // MAYU64
DWORD result;
#endif // MAYU64
DWORD len;
if (g.m_hMailslot != INVALID_HANDLE_VALUE) {
BOOL ret;
ret = WriteFile(g.m_hMailslot, i_data, i_dataSize, &len, NULL);
#ifndef NDEBUG
if (ret == 0) {
HOOK_RPT2("MAYU: %S WriteFile to mailslot failed(0x%08x)\r\n", g.m_moduleName, GetLastError());
} else {
HOOK_RPT1("MAYU: %S WriteFile to mailslot successed\r\n", g.m_moduleName);
}
#endif // !NDEBUG
} else {
cd.dwData = reinterpret_cast<Notify *>(i_data)->m_type;
cd.cbData = i_dataSize;
cd.lpData = i_data;
if (g.m_hwndTaskTray == 0 || cd.dwData == Notify::Type_threadDetach)
return false;
if (!SendMessageTimeout(reinterpret_cast<HWND>(g.m_hwndTaskTray),
WM_COPYDATA, NULL, reinterpret_cast<LPARAM>(&cd),
SMTO_ABORTIFHUNG | SMTO_NORMAL, 5000, &result)) {
_RPT0(_CRT_WARN, "MAYU: SendMessageTimeout() timeouted\r\n");
return false;
}
}
return true;
}
/// get class name and title name
static void getClassNameTitleName(HWND i_hwnd, bool i_isInMenu,
tstringi *o_className,
tstring *o_titleName)
{
tstringi &className = *o_className;
tstring &titleName = *o_titleName;
bool isTheFirstTime = true;
if (i_isInMenu) {
className = titleName = _T("MENU");
isTheFirstTime = false;
}
while (true) {
_TCHAR buf[MAX(GANA_MAX_PATH, GANA_MAX_ATOM_LENGTH)];
// get class name
if (i_hwnd)
GetClassName(i_hwnd, buf, NUMBER_OF(buf));
else
GetModuleFileName(GetModuleHandle(NULL), buf, NUMBER_OF(buf));
buf[NUMBER_OF(buf) - 1] = _T('\0');
if (isTheFirstTime)
className = buf;
else
className = tstringi(buf) + _T(":") + className;
// get title name
if (i_hwnd) {
GetWindowText(i_hwnd, buf, NUMBER_OF(buf));
buf[NUMBER_OF(buf) - 1] = _T('\0');
for (_TCHAR *b = buf; *b; ++ b)
if (_istlead(*b) && b[1])
b ++;
else if (_istcntrl(*b))
*b = _T('?');
}
if (isTheFirstTime)
titleName = buf;
else
titleName = tstring(buf) + _T(":") + titleName;
// next loop or exit
if (!i_hwnd)
break;
i_hwnd = GetParent(i_hwnd);
isTheFirstTime = false;
}
}
/// update show
static void updateShow(HWND i_hwnd, NotifyShow::Show i_show)
{
bool isMDI = false;
if (!i_hwnd)
return;
#ifdef MAYU64
LONG_PTR style = GetWindowLongPtr(i_hwnd, GWL_STYLE);
#else
LONG style = GetWindowLong(i_hwnd, GWL_STYLE);
#endif
if (!(style & WS_MAXIMIZEBOX) && !(style & WS_MAXIMIZEBOX))
return; // ignore window that has neither maximize or minimize button
if (style & WS_CHILD) {
#ifdef MAYU64
LONG_PTR exStyle = GetWindowLongPtr(i_hwnd, GWL_EXSTYLE);
#else
LONG exStyle = GetWindowLong(i_hwnd, GWL_EXSTYLE);
#endif
if (exStyle & WS_EX_MDICHILD) {
isMDI = true;
} else
return; // ignore non-MDI child window case
}
notifyShow(i_show, isMDI);
}
/// notify WM_Targetted
static void notifyName(HWND i_hwnd, Notify::Type i_type = Notify::Type_name)
{
tstringi className;
tstring titleName;
getClassNameTitleName(i_hwnd, g.m_isInMenu, &className, &titleName);
NotifySetFocus *nfc = new NotifySetFocus;
nfc->m_type = i_type;
nfc->m_threadId = GetCurrentThreadId();
nfc->m_hwnd = reinterpret_cast<DWORD>(i_hwnd);
tcslcpy(nfc->m_className, className.c_str(), NUMBER_OF(nfc->m_className));
tcslcpy(nfc->m_titleName, titleName.c_str(), NUMBER_OF(nfc->m_titleName));
notify(nfc, sizeof(*nfc));
delete nfc;
}
/// notify WM_SETFOCUS
static void notifySetFocus(bool i_doesForce = false)
{
HWND hwnd = GetFocus();
if (i_doesForce || hwnd != g.m_hwndFocus) {
g.m_hwndFocus = hwnd;
notifyName(hwnd, Notify::Type_setFocus);
}
}
/// notify sync
static void notifySync()
{
Notify n;
n.m_type = Notify::Type_sync;
notify(&n, sizeof(n));
}
/// notify DLL_THREAD_DETACH
static void notifyThreadDetach()
{
NotifyThreadDetach ntd;
ntd.m_type = Notify::Type_threadDetach;
ntd.m_threadId = GetCurrentThreadId();
notify(&ntd, sizeof(ntd));
}
/// notify WM_COMMAND, WM_SYSCOMMAND
static void notifyCommand(
HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam)
{
if (g_hookData->m_doesNotifyCommand) {
#ifdef _WIN64
NotifyCommand64 ntc;
ntc.m_type = Notify::Type_command64;
#else // !_WIN64
NotifyCommand32 ntc;
ntc.m_type = Notify::Type_command32;
#endif // !_WIN64
ntc.m_hwnd = i_hwnd;
ntc.m_message = i_message;
ntc.m_wParam = i_wParam;
ntc.m_lParam = i_lParam;
notify(&ntc, sizeof(ntc));
}
}
/// notify show of current window
static void notifyShow(NotifyShow::Show i_show, bool i_isMDI)
{
NotifyShow ns;
ns.m_type = Notify::Type_show;
ns.m_show = i_show;
ns.m_isMDI = i_isMDI;
notify(&ns, sizeof(ns));
}
/// notify log
static void notifyLog(_TCHAR *i_msg)
{
NotifyLog nl;
nl.m_type = Notify::Type_log;
tcslcpy(nl.m_msg, i_msg, NUMBER_OF(nl.m_msg));
notify(&nl, sizeof(nl));
}
/// &Recenter
static void funcRecenter(HWND i_hwnd)
{
_TCHAR buf[MAX(GANA_MAX_PATH, GANA_MAX_ATOM_LENGTH)];
GetClassName(i_hwnd, buf, NUMBER_OF(buf));
bool isEdit;
if (_tcsicmp(buf, _T("Edit")) == 0)
isEdit = true;
else if (_tcsnicmp(buf, _T("RichEdit"), 8) == 0)
isEdit = false;
else
return; // this function only works for Edit control
#ifdef MAYU64
LONG_PTR style = GetWindowLongPtr(i_hwnd, GWL_STYLE);
#else
LONG style = GetWindowLong(i_hwnd, GWL_STYLE);
#endif
if (!(style & ES_MULTILINE))
return; // this function only works for multi line Edit control
RECT rc;
GetClientRect(i_hwnd, &rc);
POINTL p = { (rc.right + rc.left) / 2, (rc.top + rc.bottom) / 2 };
int line;
if (isEdit) {
line = SendMessage(i_hwnd, EM_CHARFROMPOS, 0, MAKELPARAM(p.x, p.y));
line = HIWORD(line);
} else {
int ci = SendMessage(i_hwnd, EM_CHARFROMPOS, 0, (LPARAM)&p);
line = SendMessage(i_hwnd, EM_EXLINEFROMCHAR, 0, ci);
}
int caretLine = SendMessage(i_hwnd, EM_LINEFROMCHAR, -1, 0);
SendMessage(i_hwnd, EM_LINESCROLL, 0, caretLine - line);
}
// &SetImeStatus
static void funcSetImeStatus(HWND i_hwnd, int i_status)
{
HIMC hIMC;
hIMC = ImmGetContext(i_hwnd);
if (hIMC == INVALID_HANDLE_VALUE)
return;
if (i_status < 0)
i_status = !ImmGetOpenStatus(hIMC);
ImmSetOpenStatus(hIMC, i_status);
ImmReleaseContext(i_hwnd, hIMC);
}
// &SetImeString
static void funcSetImeString(HWND i_hwnd, int i_size)
{
_TCHAR *buf = new _TCHAR(i_size);
DWORD len = 0;
_TCHAR ImeDesc[GANA_MAX_ATOM_LENGTH];
UINT ImeDescLen;
DWORD error;
DWORD denom = 1;
HANDLE hPipe
= CreateFile(addSessionId(HOOK_PIPE_NAME).c_str(), GENERIC_READ,
FILE_SHARE_READ, (SECURITY_ATTRIBUTES *)NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL);
error = ReadFile(hPipe, buf, i_size, &len, NULL);
CloseHandle(hPipe);
ImeDescLen = ImmGetDescription(GetKeyboardLayout(0),
ImeDesc, sizeof(ImeDesc));
if (_tcsncmp(ImeDesc, _T("SKKIME"), ImeDescLen) > 0)
denom = sizeof(_TCHAR);
HIMC hIMC = ImmGetContext(i_hwnd);
if (hIMC == INVALID_HANDLE_VALUE)
return;
int status = ImmGetOpenStatus(hIMC);
ImmSetCompositionString(hIMC, SCS_SETSTR, buf, len / denom, NULL, 0);
delete buf;
ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
if (!status)
ImmSetOpenStatus(hIMC, status);
ImmReleaseContext(i_hwnd, hIMC);
}
/// notify lock state
/*DllExport*/
void notifyLockState(int i_cause)
{
NotifyLockState n;
n.m_type = Notify::Type_lockState;
n.m_isNumLockToggled = !!(GetKeyState(VK_NUMLOCK) & 1);
n.m_isCapsLockToggled = !!(GetKeyState(VK_CAPITAL) & 1);
n.m_isScrollLockToggled = !!(GetKeyState(VK_SCROLL) & 1);
n.m_isKanaLockToggled = !!(GetKeyState(VK_KANA) & 1);
n.m_isImeLockToggled = g.m_isImeLock;
n.m_isImeCompToggled = g.m_isImeCompositioning;
n.m_debugParam = i_cause;
notify(&n, sizeof(n));
}
DllExport void notifyLockState()
{
notifyLockState(9);
}
/// hook of GetMessage
LRESULT CALLBACK getMessageProc(int i_nCode, WPARAM i_wParam, LPARAM i_lParam)
{
if (!g.m_isInitialized)
initialize(false);
if (!g_hookData)
return 0;
MSG &msg = (*(MSG *)i_lParam);
if (i_wParam != PM_REMOVE)
goto finally;
switch (msg.message) {
case WM_COMMAND:
case WM_SYSCOMMAND:
notifyCommand(msg.hwnd, msg.message, msg.wParam, msg.lParam);
break;
case WM_KEYDOWN:
case WM_KEYUP:
case WM_SYSKEYDOWN:
case WM_SYSKEYUP: {
if (HIMC hIMC = ImmGetContext(msg.hwnd)) {
bool prev = g.m_isImeLock;
g.m_isImeLock = !!ImmGetOpenStatus(hIMC);
ImmReleaseContext(msg.hwnd, hIMC);
if (prev != g.m_isImeLock) {
notifyLockState(1);
}
}
int nVirtKey = (int)msg.wParam;
// int repeatCount = (msg.lParam & 0xffff);
BYTE scanCode = (BYTE)((msg.lParam >> 16) & 0xff);
bool isExtended = !!(msg.lParam & (1 << 24));
// bool isAltDown = !!(msg.lParam & (1 << 29));
// bool isKeyup = !!(msg.lParam & (1 << 31));
if (nVirtKey == VK_CAPITAL ||
nVirtKey == VK_NUMLOCK ||
nVirtKey == VK_KANA ||
nVirtKey == VK_SCROLL)
notifyLockState(2);
else if (scanCode == g_hookData->m_syncKey &&
isExtended == g_hookData->m_syncKeyIsExtended)
notifySync();
break;
}
case WM_IME_STARTCOMPOSITION:
g.m_isImeCompositioning = true;
notifyLockState(3);
break;
case WM_IME_ENDCOMPOSITION:
g.m_isImeCompositioning = false;
notifyLockState(4);
break;
default:
if (i_wParam == PM_REMOVE && msg.message == g.m_WM_MAYU_MESSAGE) {
switch (msg.wParam) {
case MayuMessage_notifyName:
notifyName(msg.hwnd);
break;
case MayuMessage_funcRecenter:
funcRecenter(msg.hwnd);
break;
case MayuMessage_funcSetImeStatus:
funcSetImeStatus(msg.hwnd, msg.lParam);
break;
case MayuMessage_funcSetImeString:
funcSetImeString(msg.hwnd, msg.lParam);
break;
}
}
break;
}
finally:
return CallNextHookEx(s_hookDataArch->m_hHookGetMessage,
i_nCode, i_wParam, i_lParam);
}
/// hook of SendMessage
LRESULT CALLBACK callWndProc(int i_nCode, WPARAM i_wParam, LPARAM i_lParam)
{
if (!g.m_isInitialized)
initialize(false);
if (!g_hookData)
return 0;
CWPSTRUCT &cwps = *(CWPSTRUCT *)i_lParam;
if (0 <= i_nCode) {
switch (cwps.message) {
case WM_ACTIVATEAPP:
case WM_NCACTIVATE:
if (i_wParam)
notifySetFocus();
break;
case WM_SYSCOMMAND:
switch (cwps.wParam) {
case SC_MAXIMIZE:
case SC_MAXIMIZE2:
updateShow(cwps.hwnd, NotifyShow::Show_Maximized);
break;
case SC_MINIMIZE:
case SC_MINIMIZE2:
updateShow(cwps.hwnd, NotifyShow::Show_Minimized);
break;
case SC_RESTORE:
case SC_RESTORE2:
updateShow(cwps.hwnd, NotifyShow::Show_Normal);
break;
default:
break;
}
/* through below */
case WM_COMMAND:
notifyCommand(cwps.hwnd, cwps.message, cwps.wParam, cwps.lParam);
break;
case WM_SIZE:
switch (cwps.wParam) {
case SIZE_MAXIMIZED:
updateShow(cwps.hwnd, NotifyShow::Show_Maximized);
break;
case SIZE_MINIMIZED:
updateShow(cwps.hwnd, NotifyShow::Show_Minimized);
break;
case SIZE_RESTORED:
updateShow(cwps.hwnd, NotifyShow::Show_Normal);
break;
default:
break;
}
break;
case WM_MOUSEACTIVATE:
notifySetFocus();
break;
case WM_ACTIVATE:
if (LOWORD(cwps.wParam) != WA_INACTIVE) {
notifySetFocus();
if (HIWORD(cwps.wParam)) { // check minimized flag
// minimized flag on
notifyShow(NotifyShow::Show_Minimized, false);
//notifyShow(NotifyShow::Show_Normal, true);
}
}
break;
case WM_ENTERMENULOOP:
g.m_isInMenu = true;
notifySetFocus(true);
break;
case WM_EXITMENULOOP:
g.m_isInMenu = false;
notifySetFocus(true);
break;
case WM_SETFOCUS:
g.m_isInMenu = false;
// for kana
if (g_hookData->m_correctKanaLockHandling) {
if (HIMC hIMC = ImmGetContext(cwps.hwnd)) {
bool status = !!ImmGetOpenStatus(hIMC);
// this code set the VK_KANA state correctly.
ImmSetOpenStatus(hIMC, !status);
ImmSetOpenStatus(hIMC, status);
ImmReleaseContext(cwps.hwnd, hIMC);
}
}
notifySetFocus();
notifyLockState(5);
break;
case WM_IME_STARTCOMPOSITION:
g.m_isImeCompositioning = true;
notifyLockState(6);
break;
case WM_IME_ENDCOMPOSITION:
g.m_isImeCompositioning = false;
notifyLockState(7);
break;
case WM_IME_NOTIFY:
if (cwps.wParam == IMN_SETOPENSTATUS)
if (HIMC hIMC = ImmGetContext(cwps.hwnd)) {
g.m_isImeLock = !!ImmGetOpenStatus(hIMC);
ImmReleaseContext(cwps.hwnd, hIMC);
notifyLockState(8);
}
break;
}
}
return CallNextHookEx(s_hookDataArch->m_hHookCallWndProc, i_nCode,
i_wParam, i_lParam);
}
static LRESULT CALLBACK lowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (!g.m_isInitialized)
initialize(false);
if (!g_hookData || nCode < 0)
goto through;
if (g.m_mouseDetour && g.m_engine) {
unsigned int result;
result = g.m_mouseDetour(g.m_engine, wParam, lParam);
if (result) {
return 1;
}
}
through:
return CallNextHookEx(g.m_hHookMouseProc,
nCode, wParam, lParam);
}
static LRESULT CALLBACK lowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
KBDLLHOOKSTRUCT *pKbll = (KBDLLHOOKSTRUCT*)lParam;
if (!g.m_isInitialized)
initialize(false);
if (!g_hookData || nCode < 0)
goto through;
if (g.m_keyboardDetour && g.m_engine) {
unsigned int result;
result = g.m_keyboardDetour(g.m_engine, wParam, lParam);
if (result) {
return 1;
}
}
through:
return CallNextHookEx(g.m_hHookKeyboardProc,
nCode, wParam, lParam);
}
/// install message hook
DllExport int installMessageHook(DWORD i_hwndTaskTray)
{
if (!g.m_isInitialized)
initialize(true);
if (i_hwndTaskTray) {
g_hookData->m_hwndTaskTray = i_hwndTaskTray;
}
g.m_hwndTaskTray = g_hookData->m_hwndTaskTray;
s_hookDataArch->m_hHookGetMessage =
SetWindowsHookEx(WH_GETMESSAGE, (HOOKPROC)getMessageProc,
g.m_hInstDLL, 0);
s_hookDataArch->m_hHookCallWndProc =
SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)callWndProc, g.m_hInstDLL, 0);
return 0;
}
/// uninstall message hook
DllExport int uninstallMessageHook()
{
if (s_hookDataArch->m_hHookGetMessage)
UnhookWindowsHookEx(s_hookDataArch->m_hHookGetMessage);
s_hookDataArch->m_hHookGetMessage = NULL;
if (s_hookDataArch->m_hHookCallWndProc)
UnhookWindowsHookEx(s_hookDataArch->m_hHookCallWndProc);
s_hookDataArch->m_hHookCallWndProc = NULL;
g.m_hwndTaskTray = 0;
return 0;
}
/// install keyboard hook
DllExport int installKeyboardHook(INPUT_DETOUR i_keyboardDetour, Engine *i_engine, bool i_install)
{
if (i_install) {
if (!g.m_isInitialized)
initialize(true);
g.m_keyboardDetour = i_keyboardDetour;
g.m_engine = i_engine;
g.m_hHookKeyboardProc =
SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)lowLevelKeyboardProc,
g.m_hInstDLL, 0);
} else {
if (g.m_hHookKeyboardProc)
UnhookWindowsHookEx(g.m_hHookKeyboardProc);
g.m_hHookKeyboardProc = NULL;
}
return 0;
}
/// install mouse hook
DllExport int installMouseHook(INPUT_DETOUR i_mouseDetour, Engine *i_engine, bool i_install)
{
if (i_install) {
if (!g.m_isInitialized)
initialize(true);
g.m_mouseDetour = i_mouseDetour;
g.m_engine = i_engine;
g_hookData->m_mouseHookType = MouseHookType_None;
g.m_hHookMouseProc =
SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)lowLevelMouseProc,
g.m_hInstDLL, 0);
} else {
if (g.m_hHookMouseProc)
UnhookWindowsHookEx(g.m_hHookMouseProc);
g.m_hHookMouseProc = NULL;
}
return 0;
}
<file_sep>#
# Makefile for VC
#
!include <win32.mak>
!if "$(TS4MAYU)" == "STS4MAYU"
TARGET_NAME = sts4mayu
!elseif "$(TS4MAYU)" == "CTS4MAYU"
TARGET_NAME = cts4mayu
!else
TARGET_NAME = dummy
!endif
SRCS = ts4mayu.cpp
HEADERS =
OBJS = $(TARGET_NAME)/ts4mayu.obj
DEFS = ts4mayu.def
TARGET = $(TARGET_NAME)/$(TARGET_NAME).dll
CFLAGS = -DUNICODE -D_UNICODE -D_MT -MT
INCLUDES = -I../../SynCOMAPIv1_0/Include -I"$(PROGRAMFILES)"/Touchpad
LDFLAGS = $(dlllflags) /libpath:../../SynCOMAPIv1_0/Lib /libpath:"$(PROGRAMFILES)"/Touchpad
LDLIBS = user32.lib
RM = rd
MKDIR = md
all:
$(MAKE) /$(MAKEFLAGS) TS4MAYU=STS4MAYU sts4mayu/sts4mayu.dll
$(MAKE) /$(MAKEFLAGS) TS4MAYU=CTS4MAYU cts4mayu/cts4mayu.dll
$(TARGET_NAME):
if not exist "$(TARGET_NAME)" $(MKDIR) $(TARGET_NAME)
$(TARGET): $(TARGET_NAME) $(OBJS) $(DEFS)
$(link) $(LDFLAGS) $(OBJS) -def:$(DEFS) $(LDLIBS) -out:$@
{}.cpp.obj:
$(cc) -D$(TS4MAYU) -GX $(cdebug) $(cflags) $(cvarsmt) $(DEFINES) $(INCLUDES) \
$(DEBUG_FLAG) -Fo$@ $(*B).cpp
clean:
-$(RM) /Q /S sts4mayu cts4mayu
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// compiler_specific_func.cpp
#include "compiler_specific_func.h"
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Microsoft Visual C++ 6.0
#if defined(_MSC_VER)
// get compiler version string
tstring getCompilerVersionString()
{
TCHAR buf[200];
_sntprintf(buf, NUMBER_OF(buf),
_T("Microsoft (R) 32-bit C/C++ Optimizing Compiler Version %d.%02d"),
_MSC_VER / 100,
_MSC_VER % 100);
return tstring(buf);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Borland C++ 5.5.1
#elif defined(__BORLANDC__)
// get compiler version string
tstring getCompilerVersionString()
{
TCHAR buf[100];
_sntprintf(buf, NUMBER_OF(buf), _T("Borland C++ %d.%d.%d"),
__BORLANDC__ / 0x100,
__BORLANDC__ / 0x10 % 0x10,
__BORLANDC__ % 0x10);
return tstring(buf);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// unknown
#else
# error "I don't know the details of this compiler... Plz hack."
#endif
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// parser.cpp
#include "misc.h"
#include "errormessage.h"
#include "parser.h"
#include <cassert>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Token
Token::Token(const Token &i_token)
: m_type(i_token.m_type),
m_isValueQuoted(i_token.m_isValueQuoted),
m_numericValue(i_token.m_numericValue),
m_stringValue(i_token.m_stringValue),
m_data(i_token.m_data)
{
}
Token::Token(int i_value, const tstringi &i_display)
: m_type(Type_number),
m_isValueQuoted(false),
m_numericValue(i_value),
m_stringValue(i_display),
m_data(NULL)
{
}
Token::Token(const tstringi &i_value, bool i_isValueQuoted, bool i_isRegexp)
: m_type(i_isRegexp ? Type_regexp : Type_string),
m_isValueQuoted(i_isValueQuoted),
m_numericValue(0),
m_stringValue(i_value),
m_data(NULL)
{
}
Token::Token(Type i_m_type)
: m_type(i_m_type),
m_isValueQuoted(false),
m_numericValue(0),
m_stringValue(_T("")),
m_data(NULL)
{
ASSERT(m_type == Type_openParen || m_type == Type_closeParen ||
m_type == Type_comma);
}
// get numeric value
int Token::getNumber() const
{
if (m_type == Type_number)
return m_numericValue;
if (m_stringValue.empty())
return 0;
else
throw ErrorMessage() << _T("`") << *this << _T("' is not a Type_number.");
}
// get string value
tstringi Token::getString() const
{
if (m_type == Type_string)
return m_stringValue;
throw ErrorMessage() << _T("`") << *this << _T("' is not a string.");
}
// get regexp value
tstringi Token::getRegexp() const
{
if (m_type == Type_regexp)
return m_stringValue;
throw ErrorMessage() << _T("`") << *this << _T("' is not a regexp.");
}
// case insensitive equal
bool Token::operator==(const _TCHAR *i_str) const
{
if (m_type == Type_string)
return m_stringValue == i_str;
return false;
}
// paren equal
bool Token::operator==(const _TCHAR i_c) const
{
if (i_c == _T('(')) return m_type == Type_openParen;
if (i_c == _T(')')) return m_type == Type_openParen;
return false;
}
// add string
void Token::add(const tstringi &i_str)
{
m_stringValue += i_str;
}
// stream output
tostream &operator<<(tostream &i_ost, const Token &i_token)
{
switch (i_token.m_type) {
case Token::Type_string:
i_ost << i_token.m_stringValue;
break;
case Token::Type_number:
i_ost << i_token.m_stringValue;
break;
case Token::Type_regexp:
i_ost << i_token.m_stringValue;
break;
case Token::Type_openParen:
i_ost << _T("(");
break;
case Token::Type_closeParen:
i_ost << _T(")");
break;
case Token::Type_comma:
i_ost << _T(", ");
break;
}
return i_ost;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Parser
Parser::Parser(const _TCHAR *i_str, size_t i_length)
: m_lineNumber(1),
m_prefixes(NULL),
m_internalLineNumber(1),
m_ptr(i_str),
m_end(i_str + i_length)
{
}
// set string that may be prefix of a token.
// prefix_ is not copied, so it must be preserved after setPrefix()
void Parser::setPrefixes(const Prefixes *i_prefixes)
{
m_prefixes = i_prefixes;
}
// get a line
bool Parser::getLine(tstringi *o_line)
{
o_line->resize(0);
if (m_ptr == m_end)
return false;
const _TCHAR *begin = m_ptr;
const _TCHAR *end = m_end;
// lines are separated by: "\r\n", "\n", "\x2028" (Unicode Line Separator)
while (m_ptr != m_end)
switch (*m_ptr) {
case _T('\n'):
#ifdef UNICODE
case 0x2028:
//case _T('\x2028'): // (U+2028)
#endif
end = m_ptr;
++ m_ptr;
goto got_line_end;
case _T('\r'):
if (m_ptr + 1 != m_end && m_ptr[1] == _T('\n')) {
end = m_ptr;
m_ptr += 2;
goto got_line_end;
}
// fall through
default:
++ m_ptr;
break;
}
got_line_end:
++ m_internalLineNumber;
// o_line->assign(begin, end); // why bcc cannot link this ?
o_line->assign(begin, end - begin); // workarond for bcc
return true;
}
// symbol test
static bool isSymbolChar(_TCHAR i_c)
{
if (i_c == _T('\0'))
return false;
if (_istlead(i_c) ||
_istalpha(i_c) ||
_istdigit(i_c) ||
_istlead(i_c))
return true;
#ifdef UNICODE
if (0x80 <= i_c && _istgraph(i_c))
return true;
#endif // UNICODE
if (_istpunct(i_c))
return !!_tcschr(_T("-+/?_\\"), i_c);
#ifdef UNICODE
// check arrows
if (_tcschr(_T("\x2190\x2191\x2192\x2193"), i_c)) {
return true;
}
#endif // UNICODE
return _istgraph(i_c);
}
// get a parsed line.
// if no more lines exist, returns false
bool Parser::getLine(std::vector<Token> *o_tokens)
{
o_tokens->clear();
m_lineNumber = m_internalLineNumber;
tstringi line;
bool isTokenExist = false;
continue_getLineLoop:
while (getLine(&line)) {
const _TCHAR *t = line.c_str();
continue_getTokenLoop:
while (true) {
// skip white space
while (*t != _T('\0') && _istspace(*t))
t ++;
if (*t == _T('\0') || *t == _T('#'))
goto break_getTokenLoop; // no more tokens exist
if (*t == _T('\\') && *(t + 1) == _T('\0'))
goto continue_getLineLoop; // continue to next line
const _TCHAR *tokenStart = t;
// comma or empty token
if (*t == _T(',')) {
if (!isTokenExist)
o_tokens->push_back(Token(_T(""), false));
isTokenExist = false;
o_tokens->push_back(Token(Token::Type_comma));
t ++;
goto continue_getTokenLoop;
}
// paren
if (*t == _T('(')) {
o_tokens->push_back(Token(Token::Type_openParen));
isTokenExist = false;
t ++;
goto continue_getTokenLoop;
}
if (*t == _T(')')) {
if (!isTokenExist)
o_tokens->push_back(Token(_T(""), false));
isTokenExist = true;
o_tokens->push_back(Token(Token::Type_closeParen));
t ++;
goto continue_getTokenLoop;
}
isTokenExist = true;
// prefix
if (m_prefixes)
for (size_t i = 0; i < m_prefixes->size(); i ++)
if (_tcsnicmp(tokenStart, m_prefixes->at(i).c_str(),
m_prefixes->at(i).size()) == 0) {
o_tokens->push_back(Token(m_prefixes->at(i), false));
t += m_prefixes->at(i).size();
goto continue_getTokenLoop;
}
// quoted or regexp
if (*t == _T('"') || *t == _T('\'') ||
*t == _T('/') || (*t == _T('\\') && *(t + 1) == _T('m') &&
*(t + 2) != _T('\0'))) {
bool isRegexp = !(*t == _T('"') || *t == _T('\''));
_TCHAR q[2] = { *t++, _T('\0') }; // quote character
if (q[0] == _T('\\')) {
t++;
q[0] = *t++;
}
tokenStart = t;
while (*t != _T('\0') && *t != q[0]) {
if (*t == _T('\\') && *(t + 1))
t ++;
if (_istlead(*t) && *(t + 1))
t ++;
t ++;
}
tstring str =
interpretMetaCharacters(tokenStart, t - tokenStart, q, isRegexp);
#ifdef _MBCS
if (isRegexp)
str = guardRegexpFromMbcs(str.c_str());
#endif
// concatinate continuous string
if (!isRegexp &&
0 < o_tokens->size() && o_tokens->back().isString() &&
o_tokens->back().isQuoted())
o_tokens->back().add(str);
else
o_tokens->push_back(Token(str, true, isRegexp));
if (*t != _T('\0'))
t ++;
goto continue_getTokenLoop;
}
// not quoted
{
while (isSymbolChar(*t)) {
if (*t == _T('\\'))
if (*(t + 1))
t ++;
else
break;
if (_istlead(*t) && *(t + 1))
t ++;
t ++;
}
if (t == tokenStart) {
ErrorMessage e;
e << _T("invalid character ");
#ifdef UNICODE
e << _T("U+");
e << std::hex; // << std::setw(4) << std::setfill(_T('0'));
e << (int)(wchar_t)*t;
#else
e << _T("\\x");
e << std::hex; // << std::setw(2) << std::setfill(_T('0'));
e << (int)(u_char)*t;
#endif
e << std::dec;
if (_istprint(*t))
e << _T("(") << *t << _T(")");
throw e;
}
_TCHAR *numEnd = NULL;
long value = _tcstol(tokenStart, &numEnd, 0);
if (tokenStart == numEnd) {
tstring str = interpretMetaCharacters(tokenStart, t - tokenStart);
o_tokens->push_back(Token(str, false));
} else {
o_tokens->push_back(
Token(value, tstringi(tokenStart, numEnd - tokenStart)));
t = numEnd;
}
goto continue_getTokenLoop;
}
}
break_getTokenLoop:
if (0 < o_tokens->size())
break;
m_lineNumber = m_internalLineNumber;
isTokenExist = false;
}
return 0 < o_tokens->size();
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// hook.h
#ifndef _HOOK_H
# define _HOOK_H
# include "misc.h"
# include <tchar.h>
# include <windef.h>
///
# define HOOK_PIPE_NAME \
_T("\\\\.\\pipe\\GANAware\\mayu\\{4B22D464-7A4E-494b-982A-C2B2BBAAF9F3}") _T(VERSION)
///
# define NOTIFY_MAILSLOT_NAME \
_T("\\\\.\\mailslot\\GANAware\\mayu\\{330F7914-EB5B-49be-ACCE-D2B8DF585B32}") _T(VERSION)
///
# define WM_MAYU_MESSAGE_NAME _T("GANAware\\mayu\\WM_MAYU_MESSAGE")
///
enum MayuMessage {
MayuMessage_notifyName,
MayuMessage_funcRecenter,
MayuMessage_funcSetImeStatus,
MayuMessage_funcSetImeString,
};
///
struct Notify {
///
enum Type {
Type_setFocus, /// NotifySetFocus
Type_name, /// NotifySetFocus
Type_lockState, /// NotifyLockState
Type_sync, /// Notify
Type_threadAttach, /// NotifyThreadAttach
Type_threadDetach, /// NotifyThreadDetach
Type_command64, /// NotifyCommand64
Type_command32, /// NotifyCommand32
Type_show, /// NotifyShow
Type_log, /// NotifyLog
};
Type m_type; ///
DWORD m_debugParam; /// (for debug)
};
///
struct NotifySetFocus : public Notify {
DWORD m_threadId; ///
DWORD m_hwnd; ///
_TCHAR m_className[GANA_MAX_PATH]; ///
_TCHAR m_titleName[GANA_MAX_PATH]; ///
};
///
struct NotifyLockState : public Notify {
bool m_isNumLockToggled; ///
bool m_isCapsLockToggled; ///
bool m_isScrollLockToggled; ///
bool m_isKanaLockToggled; ///
bool m_isImeLockToggled; ///
bool m_isImeCompToggled; ///
};
///
struct NotifyThreadAttach : public Notify {
DWORD m_threadId; ///
};
///
struct NotifyThreadDetach : public Notify {
DWORD m_threadId; ///
};
///
struct NotifyCommand32 : public Notify {
HWND m_hwnd; ///
UINT m_message; ///
unsigned int m_wParam; ///
long m_lParam; ///
};
///
struct NotifyCommand64 : public Notify {
HWND m_hwnd; ///
UINT m_message; ///
unsigned __int64 m_wParam; ///
__int64 m_lParam; ///
};
enum {
NOTIFY_MESSAGE_SIZE = sizeof(NotifySetFocus), ///
};
///
struct NotifyShow : public Notify {
///
enum Show {
Show_Normal,
Show_Maximized,
Show_Minimized,
};
Show m_show; ///
bool m_isMDI; ///
};
///
struct NotifyLog : public Notify {
_TCHAR m_msg[GANA_MAX_PATH]; ///
};
///
enum MouseHookType {
MouseHookType_None = 0, /// none
MouseHookType_Wheel = 1 << 0, /// wheel
MouseHookType_WindowMove = 1 << 1, /// window move
};
class Engine;
typedef unsigned int (WINAPI *INPUT_DETOUR)(Engine *i_engine, WPARAM i_wParam, LPARAM i_lParam);
///
class HookData
{
public:
USHORT m_syncKey; ///
bool m_syncKeyIsExtended; ///
bool m_doesNotifyCommand; ///
DWORD m_hwndTaskTray; ///
bool m_correctKanaLockHandling; /// does use KL- ?
MouseHookType m_mouseHookType; ///
int m_mouseHookParam; ///
DWORD m_hwndMouseHookTarget; ///
POINT m_mousePos; ///
};
///
# define DllExport __declspec(dllexport)
///
# define DllImport __declspec(dllimport)
# ifndef _HOOK_CPP
extern DllImport HookData *g_hookData;
extern DllImport int installMessageHook(DWORD i_hwndTaskTray);
extern DllImport int uninstallMessageHook();
extern DllImport int installKeyboardHook(INPUT_DETOUR i_keyboardDetour, Engine *i_engine, bool i_install);
extern DllImport int installMouseHook(INPUT_DETOUR i_mouseDetour, Engine *i_engine, bool i_install);
extern DllImport bool notify(void *data, size_t sizeof_data);
extern DllImport void notifyLockState();
# endif // !_HOOK_CPP
#endif // !_HOOK_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// layoutmanager.cpp
#include "layoutmanager.h"
#include "windowstool.h"
#include <windowsx.h>
//
LayoutManager::LayoutManager(HWND i_hwnd)
: m_hwnd(i_hwnd),
m_smallestRestriction(RESTRICT_NONE),
m_largestRestriction(RESTRICT_NONE)
{
}
// restrict the smallest size of the window to the current size of it or
// specified by i_size
void LayoutManager::restrictSmallestSize(Restrict i_restrict, SIZE *i_size)
{
m_smallestRestriction = i_restrict;
if (i_size)
m_smallestSize = *i_size;
else {
RECT rc;
GetWindowRect(m_hwnd, &rc);
m_smallestSize.cx = rc.right - rc.left;
m_smallestSize.cy = rc.bottom - rc.top;
}
}
// restrict the largest size of the window to the current size of it or
// specified by i_size
void LayoutManager::restrictLargestSize(Restrict i_restrict, SIZE *i_size)
{
m_largestRestriction = i_restrict;
if (i_size)
m_largestSize = *i_size;
else {
RECT rc;
GetWindowRect(m_hwnd, &rc);
m_largestSize.cx = rc.right - rc.left;
m_largestSize.cy = rc.bottom - rc.top;
}
}
//
bool LayoutManager::addItem(HWND i_hwnd, Origin i_originLeft,
Origin i_originTop,
Origin i_originRight, Origin i_originBottom)
{
Item item;
if (!i_hwnd)
return false;
item.m_hwnd = i_hwnd;
#ifdef MAYU64
if (!(GetWindowLongPtr(i_hwnd, GWL_STYLE) & WS_CHILD))
#else
if (!(GetWindowLong(i_hwnd, GWL_STYLE) & WS_CHILD))
#endif
return false;
item.m_hwndParent = GetParent(i_hwnd);
if (!item.m_hwndParent)
return false;
getChildWindowRect(item.m_hwnd, &item.m_rc);
GetWindowRect(item.m_hwndParent, &item.m_rcParent);
item.m_origin[0] = i_originLeft;
item.m_origin[1] = i_originTop;
item.m_origin[2] = i_originRight;
item.m_origin[3] = i_originBottom;
m_items.push_back(item);
return true;
}
//
void LayoutManager::adjust() const
{
for (Items::const_iterator i = m_items.begin(); i != m_items.end(); ++ i) {
RECT rc;
GetWindowRect(i->m_hwndParent, &rc);
struct {
int m_width, m_pos;
int m_curWidth;
LONG *m_out;
}
pos[4] = {
{ rcWidth(&i->m_rcParent), i->m_rc.left, rcWidth(&rc), &rc.left },
{ rcHeight(&i->m_rcParent), i->m_rc.top, rcHeight(&rc), &rc.top },
{ rcWidth(&i->m_rcParent), i->m_rc.right, rcWidth(&rc), &rc.right },
{ rcHeight(&i->m_rcParent), i->m_rc.bottom, rcHeight(&rc), &rc.bottom }
};
for (int j = 0; j < 4; ++ j) {
switch (i->m_origin[j]) {
case ORIGIN_LEFT_EDGE:
*pos[j].m_out = pos[j].m_pos;
break;
case ORIGIN_CENTER:
*pos[j].m_out = pos[j].m_curWidth / 2
- (pos[j].m_width / 2 - pos[j].m_pos);
break;
case ORIGIN_RIGHT_EDGE:
*pos[j].m_out = pos[j].m_curWidth
- (pos[j].m_width - pos[j].m_pos);
break;
}
}
MoveWindow(i->m_hwnd, rc.left, rc.top,
rcWidth(&rc), rcHeight(&rc), FALSE);
}
}
// draw size box
BOOL LayoutManager::wmPaint()
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(m_hwnd, &ps);
RECT rc;
GetClientRect(m_hwnd, &rc);
rc.left = rc.right - GetSystemMetrics(SM_CXHTHUMB);
rc.top = rc.bottom - GetSystemMetrics(SM_CYVTHUMB);
DrawFrameControl(hdc, &rc, DFC_SCROLL, DFCS_SCROLLSIZEGRIP);
EndPaint(m_hwnd, &ps);
return TRUE;
}
// size restriction
BOOL LayoutManager::wmSizing(int i_edge, RECT *io_rc)
{
switch (i_edge) {
case WMSZ_TOPLEFT:
case WMSZ_LEFT:
case WMSZ_BOTTOMLEFT:
if (m_smallestRestriction & RESTRICT_HORIZONTALLY)
if (io_rc->right - io_rc->left < m_smallestSize.cx)
io_rc->left = io_rc->right - m_smallestSize.cx;
if (m_largestRestriction & RESTRICT_HORIZONTALLY)
if (m_largestSize.cx < io_rc->right - io_rc->left)
io_rc->left = io_rc->right - m_largestSize.cx;
break;
}
switch (i_edge) {
case WMSZ_TOPRIGHT:
case WMSZ_RIGHT:
case WMSZ_BOTTOMRIGHT:
if (m_smallestRestriction & RESTRICT_HORIZONTALLY)
if (io_rc->right - io_rc->left < m_smallestSize.cx)
io_rc->right = io_rc->left + m_smallestSize.cx;
if (m_largestRestriction & RESTRICT_HORIZONTALLY)
if (m_largestSize.cx < io_rc->right - io_rc->left)
io_rc->right = io_rc->left + m_largestSize.cx;
break;
}
switch (i_edge) {
case WMSZ_TOP:
case WMSZ_TOPLEFT:
case WMSZ_TOPRIGHT:
if (m_smallestRestriction & RESTRICT_VERTICALLY)
if (io_rc->bottom - io_rc->top < m_smallestSize.cy)
io_rc->top = io_rc->bottom - m_smallestSize.cy;
if (m_largestRestriction & RESTRICT_VERTICALLY)
if (m_largestSize.cy < io_rc->bottom - io_rc->top)
io_rc->top = io_rc->bottom - m_largestSize.cy;
break;
}
switch (i_edge) {
case WMSZ_BOTTOM:
case WMSZ_BOTTOMLEFT:
case WMSZ_BOTTOMRIGHT:
if (m_smallestRestriction & RESTRICT_VERTICALLY)
if (io_rc->bottom - io_rc->top < m_smallestSize.cy)
io_rc->bottom = io_rc->top + m_smallestSize.cy;
if (m_largestRestriction & RESTRICT_VERTICALLY)
if (m_largestSize.cy < io_rc->bottom - io_rc->top)
io_rc->bottom = io_rc->top + m_largestSize.cy;
break;
}
return TRUE;
}
// hittest for size box
BOOL LayoutManager::wmNcHitTest(int i_x, int i_y)
{
POINT p = { i_x, i_y };
ScreenToClient(m_hwnd, &p);
RECT rc;
GetClientRect(m_hwnd, &rc);
if (rc.right - GetSystemMetrics(SM_CXHTHUMB) <= p.x &&
rc.bottom - GetSystemMetrics(SM_CYVTHUMB) <= p.y) {
#ifdef MAYU64
SetWindowLongPtr(m_hwnd, DWLP_MSGRESULT, HTBOTTOMRIGHT);
#else
SetWindowLong(m_hwnd, DWL_MSGRESULT, HTBOTTOMRIGHT);
#endif
return TRUE;
}
return FALSE;
}
// WM_SIZE
BOOL LayoutManager::wmSize(DWORD /* i_fwSizeType */, short /* i_nWidth */,
short /* i_nHeight */)
{
adjust();
RedrawWindow(m_hwnd, NULL, NULL,
RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
return TRUE;
}
// forward message
BOOL LayoutManager::defaultWMHandler(UINT i_message,
WPARAM i_wParam, LPARAM i_lParam)
{
switch (i_message) {
case WM_SIZE:
return wmSize(i_wParam, LOWORD(i_lParam), HIWORD(i_lParam));
case WM_PAINT:
return wmPaint();
case WM_SIZING:
return wmSizing(i_wParam, reinterpret_cast<RECT *>(i_lParam));
case WM_NCHITTEST:
return wmNcHitTest(GET_X_LPARAM(i_lParam), GET_Y_LPARAM(i_lParam));
}
return FALSE;
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// focus.h
#ifndef _FOCUS_H
# define _FOCUS_H
# include <windows.h>
///
extern ATOM Register_focus();
enum {
WM_APP_notifyFocus = WM_APP + 103,
WM_APP_notifyVKey = WM_APP + 104,
};
#endif // !_FOCUS_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// msgstream.h
#ifndef _MSGSTREAM_H
# define _MSGSTREAM_H
# include "misc.h"
# include "stringtool.h"
# include "multithread.h"
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// msgstream
/** msgstream.
<p>Before writing to omsgstream, you must acquire lock by calling
<code>acquire()</code>. Then after completion of writing, you
must call <code>release()</code>.</p>
<p>Omsgbuf calls <code>PostMessage(hwnd, messageid, 0,
(LPARAM)omsgbuf)</code> to notify that string is ready to get.
When the window (<code>hwnd</code>) get the message, you can get
the string containd in the omsgbuf by calling
<code>acquireString()</code>. After calling
<code>acquireString()</code>, you must / call releaseString().</p>
*/
template<class T, size_t SIZE = 1024,
class TR = std::char_traits<T>, class A = std::allocator<T> >
class basic_msgbuf : public std::basic_streambuf<T, TR>, public SyncObject
{
public:
typedef std::basic_string<T, TR, A> String; ///
typedef std::basic_streambuf<T, TR> Super; ///
private:
HWND m_hwnd; /** window handle for
notification */
UINT m_messageId; /// messageid for notification
T *m_buf; /// for streambuf
String m_str; /// for notification
CriticalSection m_cs; /// lock
A m_allocator; /// allocator
/** debug level.
if ( m_msgDebugLevel <= m_debugLevel ), message is displayed
*/
int m_debugLevel;
int m_msgDebugLevel; ///
private:
basic_msgbuf(const basic_msgbuf &); /// disable copy constructor
public:
///
basic_msgbuf(UINT i_messageId, HWND i_hwnd = 0)
: m_hwnd(i_hwnd),
m_messageId(i_messageId),
m_buf(m_allocator.allocate(SIZE, 0)),
m_debugLevel(0),
m_msgDebugLevel(0) {
ASSERT(m_buf);
setp(m_buf, m_buf + SIZE);
}
///
~basic_msgbuf() {
sync();
m_allocator.deallocate(m_buf, SIZE);
}
/// attach/detach a window
basic_msgbuf* attach(HWND i_hwnd) {
Acquire a(&m_cs);
ASSERT( !m_hwnd && i_hwnd );
m_hwnd = i_hwnd;
if (!m_str.empty())
PostMessage(m_hwnd, m_messageId, 0, (LPARAM)this);
return this;
}
///
basic_msgbuf* detach() {
Acquire a(&m_cs);
sync();
m_hwnd = 0;
return this;
}
/// get window handle
HWND getHwnd() const {
return m_hwnd;
}
/// is a window attached ?
int is_open() const {
return !!m_hwnd;
}
/// acquire string and release the string
const String &acquireString() {
m_cs.acquire();
return m_str;
}
///
void releaseString() {
m_str.resize(0);
m_cs.release();
}
/// set debug level
void setDebugLevel(int i_debugLevel) {
m_debugLevel = i_debugLevel;
}
///
int getDebugLevel() const {
return m_debugLevel;
}
// for stream
typename Super::int_type overflow(typename Super::int_type i_c = TR::eof()) {
if (sync() == TR::eof()) // sync before new buffer created below
return TR::eof();
if (i_c != TR::eof()) {
*pptr() = TR::to_char_type(i_c);
pbump(1);
sync();
}
return TR::not_eof(i_c); // return something other than EOF if successful
}
// for stream
int sync() {
T *begin = pbase();
T *end = pptr();
T *i;
for (i = begin; i < end; ++ i)
if (_istlead(*i))
++ i;
if (i == end) {
if (m_msgDebugLevel <= m_debugLevel)
m_str += String(begin, end - begin);
setp(m_buf, m_buf + SIZE);
} else { // end < i
if (m_msgDebugLevel <= m_debugLevel)
m_str += String(begin, end - begin - 1);
m_buf[0] = end[-1];
setp(m_buf, m_buf + SIZE);
pbump(1);
}
return TR::not_eof(0);
}
// sync object
/// begin writing
virtual void acquire() {
m_cs.acquire();
}
/// begin writing
virtual void acquire(int i_msgDebugLevel) {
m_cs.acquire();
m_msgDebugLevel = i_msgDebugLevel;
}
/// end writing
virtual void release() {
if (!m_str.empty())
PostMessage(m_hwnd, m_messageId, 0, reinterpret_cast<LPARAM>(this));
m_msgDebugLevel = m_debugLevel;
m_cs.release();
}
};
///
template<class T, size_t SIZE = 1024,
class TR = std::char_traits<T>, class A = std::allocator<T> >
class basic_omsgstream : public std::basic_ostream<T, TR>, public SyncObject
{
public:
typedef std::basic_ostream<T, TR> Super; ///
typedef basic_msgbuf<T, SIZE, TR, A> StreamBuf; ///
typedef std::basic_string<T, TR, A> String; ///
private:
StreamBuf m_streamBuf; ///
public:
///
explicit basic_omsgstream(UINT i_messageId, HWND i_hwnd = 0)
: Super(&m_streamBuf), m_streamBuf(i_messageId, i_hwnd) {
}
///
virtual ~basic_omsgstream() {
}
///
StreamBuf *rdbuf() const {
return const_cast<StreamBuf *>(&m_streamBuf);
}
/// attach a msg control
void attach(HWND i_hwnd) {
m_streamBuf.attach(i_hwnd);
}
/// detach a msg control
void detach() {
m_streamBuf.detach();
}
/// get window handle of the msg control
HWND getHwnd() const {
return m_streamBuf.getHwnd();
}
/// is the msg control attached ?
int is_open() const {
return m_streamBuf.is_open();
}
/// set debug level
void setDebugLevel(int i_debugLevel) {
m_streamBuf.setDebugLevel(i_debugLevel);
}
///
int getDebugLevel() const {
return m_streamBuf.getDebugLevel();
}
/// acquire string and release the string
const String &acquireString() {
return m_streamBuf.acquireString();
}
///
void releaseString() {
m_streamBuf->releaseString();
}
// sync object
/// begin writing
virtual void acquire() {
m_streamBuf.acquire();
}
/// begin writing
virtual void acquire(int i_msgDebugLevel) {
m_streamBuf.acquire(i_msgDebugLevel);
}
/// end writing
virtual void release() {
m_streamBuf.release();
}
};
///
typedef basic_omsgstream<_TCHAR> tomsgstream;
#endif // !_MSGSTREAM_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// errormessage.h
#ifndef _ERRORMESSAGE_H
# define _ERRORMESSAGE_H
# include "stringtool.h"
# include <sstream>
///
class ErrorMessage
{
tstringstream m_ost; ///
public:
///
ErrorMessage() { }
///
ErrorMessage(const ErrorMessage &i_em) {
m_ost << i_em.getMessage();
}
/// get error message
tstring getMessage() const {
return m_ost.str();
}
/// add message
template<class T> ErrorMessage &operator<<(const T &i_value) {
m_ost << i_value;
return *this;
}
/// ios manipulator
ErrorMessage &operator<<(
std::ios_base &(*i_manip)(std::ios_base&)) {
m_ost << i_manip;
return *this;
}
#ifdef UNICODE
/// add message
template<> ErrorMessage &operator<<(const std::string &i_value) {
m_ost << to_wstring(i_value);
return *this;
}
/// add message
typedef const char *const_char_ptr;
template<> ErrorMessage &operator<<(const const_char_ptr &i_value) {
m_ost << to_wstring(i_value);
return *this;
}
#endif
/// stream output
friend tostream &operator<<(tostream &i_ost, const ErrorMessage &i_em);
};
/// stream output
inline tostream &operator<<(tostream &i_ost, const ErrorMessage &i_em)
{
return i_ost << i_em.getMessage();
}
///
class WarningMessage : public ErrorMessage
{
public:
/// add message
template<class T> WarningMessage &operator<<(const T &i_value) {
ErrorMessage::operator<<(i_value);
return *this;
}
};
#endif // !_ERRORMESSAGE_H
<file_sep>############################################################## -*- Makefile -*-
#
# Makefile for mayu (Visual C++)
#
# make release version: nmake nodebug=1
# make debug version: nmake
#
###############################################################################
!if "$(BOOST_VER)" == ""
BOOST_VER = 1_38
!endif
INCLUDES = -I$(BOOST_DIR) # why here ?
DEPENDIGNORE = --ignore=$(BOOST_DIR)
!if "$(MAYU_VC)" == ""
MAYU_VC = vc9
!endif
!if ( "$(MAYU_VC)" == "vct" )
MAYU_REGEX_VC = vc71
!else
MAYU_REGEX_VC = $(MAYU_VC)
!endif
!include <vc.mak>
!include <mayu-common.mak>
DEFINES = $(COMMON_DEFINES) -DVERSION=""""$(VERSION)"""" \
-DLOGNAME=""""$(USERNAME)"""" \
-DCOMPUTERNAME=""""$(COMPUTERNAME)"""" -D_CRT_SECURE_NO_WARNINGS -DMAYU64 -DNO_DRIVER -DUSE_MAILSLOT -DUSE_INI
# INCLUDES = -I$(BOOST_DIR) # make -f mayu-vc.mak depend fails ...
LDFLAGS_1 = \
$(guilflags) \
/PDB:$(TARGET_1).pdb \
/LIBPATH:$(BOOST_DIR)/libs/regex/build/$(MAYU_REGEX_VC)0 \
LDFLAGS_2 = \
$(dlllflags) \
/PDB:$(TARGET_2).pdb \
/LIBPATH:$(BOOST_DIR)/libs/regex/build/$(MAYU_REGEX_VC)0 \
LDFLAGS_4 = \
$(guilflags) \
/PDB:$(TARGET_4).pdb \
LDFLAGS_5 = \
$(guilflags) \
/PDB:$(TARGET_5).pdb \
$(TARGET_1): $(OBJS_1) $(RES_1) $(EXTRADEP_1)
$(link) -out:$@ $(ldebug) $(LDFLAGS_1) $(OBJS_1) $(LIBS_1) $(RES_1)
$(TARGET_2): $(OBJS_2) $(RES_2) $(EXTRADEP_2)
$(link) -out:$@ $(ldebug) $(LDFLAGS_2) $(OBJS_2) $(LIBS_2) $(RES_2)
$(TARGET_3): $(DLL_3)
!if "$(MAYU_ARCH)" == "32"
$(TARGET_4): $(OBJS_4) $(EXTRADEP_4)
$(link) -out:$@ $(ldebug) $(LDFLAGS_4) $(OBJS_4) $(LIBS_4)
$(TARGET_5): $(OBJS_5) $(EXTRADEP_5)
$(link) -out:$@ $(ldebug) $(LDFLAGS_5) $(OBJS_5) $(LIBS_5) $(RES_5)
!endif
REGEXPP_XCFLAGS = $(REGEXPP_XCFLAGS) XCFLAGS=-D_WCTYPE_INLINE_DEFINED
clean::
-$(RM) mayu.aps mayu.opt *.pdb
boost:
cd $(BOOST_DIR)/libs/regex/build/
$(MAKE) -f $(MAYU_REGEX_VC).mak $(REGEXPP_XCFLAGS) main_dir libboost_regex-$(MAYU_REGEX_VC)0-mt-s-$(BOOST_VER)_dir ./$(MAYU_REGEX_VC)0/libboost_regex-$(MAYU_REGEX_VC)0-mt-s-$(BOOST_VER).lib libboost_regex-$(MAYU_REGEX_VC)0-mt-sgd-$(BOOST_VER)_dir ./$(MAYU_REGEX_VC)0/libboost_regex-$(MAYU_REGEX_VC)0-mt-sgd-$(BOOST_VER).lib
cd ../../../../yamy
distclean:: clean
cd $(BOOST_DIR)/libs/regex/build/
-$(MAKE) -k -f $(MAYU_REGEX_VC).mak clean
cd ../../../../yamy
batch:
!if "$(MAYU_VC)" != "vct"
-$(MAKE) -f mayu-vc.mak MAYU_VC=$(MAYU_VC) TARGETOS=WINNT
!endif
-$(MAKE) -f mayu-vc.mak MAYU_VC=$(MAYU_VC) TARGETOS=WINNT nodebug=1
# cd s
# -$(MAKE) -f setup-vc.mak MAYU_VC=$(MAYU_VC) batch
# cd ..
batch_clean:
-$(MAKE) -k -f mayu-vc.mak MAYU_VC=$(MAYU_VC) TARGETOS=WINNT nodebug=1 clean
-$(MAKE) -k -f mayu-vc.mak MAYU_VC=$(MAYU_VC) TARGETOS=WINNT clean
cd s
-$(MAKE) -k -f setup-vc.mak MAYU_VC=$(MAYU_VC) batch_clean
cd ..
batch_distclean: batch_clean
-$(MAKE) -k -f mayu-vc.mak MAYU_VC=$(MAYU_VC) TARGETOS=WINNT distclean
batch_distrib: batch
-$(MAKE) -k -f mayu-vc.mak MAYU_VC=$(MAYU_VC) TARGETOS=WINNT nodebug=1 distrib
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// mayuipc.h - mayu inter process communication
#ifndef _MAYUIPC_H
# define _MAYUIPC_H
# include <windows.h>
# ifdef __cplusplus
extern "C"
{
# endif // __cplusplus
///
# define WM_MayuIPC_NAME _T("MayuIPC{46269F4D-D560-40f9-B38B-DB5E280FEF47}")
enum MayuIPCCommand {
// enable or disable Mayu
MayuIPCCommand_Enable = 1,
};
BOOL MayuIPC_PostMessage(MayuIPCCommand i_wParam, LPARAM i_lParam);
BOOL MayuIPC_Enable(BOOL i_isEnabled);
# ifdef _MAYUIPC_H_DEFINE_FUNCTIONS
BOOL MayuIPC_PostMessage(MayuIPCCommand i_command, LPARAM i_lParam) {
static UINT WM_MayuIPC;
HWND hwnd;
if (WM_MayuIPC == 0) {
WM_MayuIPC = RegisterWindowMessage(WM_MayuIPC_NAME);
if (WM_MayuIPC == 0) {
return FALSE;
}
}
hwnd = FindWindow(_T("mayuTasktray"), NULL);
if (hwnd == NULL) {
return FALSE;
}
PostMessage(hwnd, WM_MayuIPC, i_command, i_lParam);
return TRUE;
}
BOOL MayuIPC_Enable(BOOL i_isEnabled) {
return MayuIPC_PostMessage(MayuIPCCommand_Enable, i_isEnabled);
}
# endif // _MAYUIPC_H_DEFINE_FUNCTIONS
# ifdef __cplusplus
}
# endif // __cplusplus
#endif // !_MAYUIPC_H
<file_sep>Yet Another Mado tsukai no Yuutsu(YAMY) ver.0.03
1. 概要
Windows用汎用キーバインディング変更ソフト「窓使いの憂鬱(以後mayuと表記)」
(http://mayu.sourceforge.net/)のキー入力置換をドライバベースからユーザ
モードフックベースに変更した派生ソフトウェアです。
既に開発を終了したmayuをforkすることにより、Windows Vista以降のOSのサポート
を目指しています。
オリジナルのmayuではフィルタドライバによりキーの置き換えを実現していましたが、
本プロジェクトではそれをWH_KEYBOARD_LLのフックとSendInput() APIに変更します。
これにより、mayuほどの低層での強力な
置換は期待できなくなるものの、ドライバへの署名を要することなく、
Vista以降のWindows(特に64bit版)への対応を目指します。
2. ファイル構成
yamy.exe ... yamy32/yamy64のどちらかを起動するランチャ
yamy32 ... 32bit版yamy本体
yamy64 ... 64bit版yamy本体
yamy32.dll ... 32bit版フックDLL
yamy64.dll ... 64bit版フックDLL
yamyd32 ... 64bit環境で32bitプロセスをフックするための補助プログラム
yamy.ini ... 設定ファイル(mayu でのレジストリ設定に相当)
workaround.reg ... 特定キー問題対策用Scancode Mapレジストリサンプル
readme.txt ... 本ドキュメント
*.mayu ... キーバインド設定ファイル
3. 使用方法
基本的な使用方法は「窓使いの憂鬱」と同じです。
http://mayu.sourceforge.net/mayu/doc/README-ja.html
を参照して下さい。
以下、「窓使いの憂鬱」と異なる部分について記載します。
3.1. マウスイベントの置換
いくつかのマウスイベントをキーイベントと同様に置換可能です。
各マウスイベントはE1-プレフィックスを持つ擬似的なスキャンコード
として扱われます。
# WH_KEYBOARD_LLを使うyamyではE1-プレフィックスのキーコードを
# を拾うことができないため、実際のキーコードと衝突する可能性はない。
マウスイベントの置換はデフォルトではオフです。
有効化するためには.mayu ファイルに
def option mouse-event = true
と記述します。
置換可能なマウスイベントは以下の通りです。
# ()内は使われる疑似スキャンコード
* マウスドラッグ Drag(E1-0x00)
* 左ボタン LButton(E1-0x01)
* 右ボタン RButton(E1-0x02)
* 中ボタン MButton(E1-0x03)
* ホイール前進 WheelForward(E1-0x04)
* ホイール後退 WheelBackward(E1-0x05)
* Xボタン1 XButton1(E1-0x06)
* Xボタン2 XButton1(E1-0x07)
* 横スクロール(チルト)右 TiltRight(E1-0x08) ※Vista以降
* 横スクロール(チルト)左 TiltLeft(E1-0x09) ※Vista以降
このうちDragイベントは、いずれからマウスボタンを押したままボタンを
押した場所から一定以上マウスを移動させた際にDownが発生し、Down発生後
にボタンを離すとUpが発生する疑似イベントです。
Dragイベント発生までの移動距離の閾値はピクセル単位で
def option drag-threshold = 30
のように指定します。閾値として0を指定するもしくは閾値を指定しない
場合、Dragイベントは発生しません。
※注意1※
WheelForward/WheelBackward/TiltRight/TiltLeftには物理的に"Up"
イベントがありませんので、yamy内部では押し下げ時にDown/Upの
両イベントが発生します。このためこれらのイベントをモディファイア
にすることはできません。
※注意2※
キーイベントと同様にマウスイベントも「調査」ウィンドウを使って
コードを調査することができますが、キーイベントと異なり調査時も
イベントは捨てません。これは「調査」モードから抜けられなくなら
ないための措置です。
※注意3※
Vista以降ではyamyを標準権限で起動し、option mouse-event を有効に
した場合、管理者権限のアプリに(置換の有無にかかわらず)マウス
イベントが届かなくなります。yamyを管理者権限で起動すれば標準権限
・管理者権限どちらにもマウスイベントが届きます。
3.2. NLSキーのエスケープ
日本語環境の場合、日本語処理に使われるいくつかのキーに対しては
WH_KEYBOARD_LLフック前に特殊処理が行われるため、yamyによって
正常にフックできません。
以下、便宜上これらのキーをNLSキー(National Language Support Key)
と呼びます。
キーボードレイアウトドライバとしてkbd106.dllを用いている場合は
NLSキーは以下の4つです。
# []内はスキャンコード
* 半角・全角[0x29]
* 英数(CapsLock)[0x3a]
* ひらがな[0x70]
* 無変換[0x7b]
キーボードレイアウトドライバとしてkbd101.dllを用いている場合は
NLSキーは以下の2つです。
# []内はスキャンコード
* `(~)[0x29]
* CapsLock[0x3a]
これらのNLSキーが正しくフックできないことへの対策としてはレジストリ
の Scancode Map を使ってこれらのキーを特殊扱いされない別のキーに
置き換える方法があります。Scancode Map の仕様については、
http://www.microsoft.com/whdc/archive/w2kscan-map.mspx
に情報があります。また以下のサイトの記述も参考になります。
http://www.jaist.ac.jp/~fujieda/scancode.html
http://sgry.jp/articles/scancodemap.html
尚、RC版で確認した限りでは Windows7 の場合、HKEY_LOCAL_MACHINE
の Scancode Map が有効のようです。RTM版でどうかは未確認です。
同梱している workaround.reg は具体的な置き換えのサンプルです。
このサンプルではこれらNLSキーに E0 プレフィックスを付加することにより、
別キーに変換しています。同梱の *.mayu はこの Scancode Map の下でこれら
E0を付加されたキーがあたかも本来のキーのように動作するように
設定が追加されています。
workaround.mayu にはこの対策に対応した追加部分を抽出していますので、
独自の .mayu を使っている場合はこれを参考にして下さい。
また「英数キーとCtrlキーの入れ替え」等の単純な置き換えで十分な
場合はこれらに絞った Scancode Map を作成しても良いでしょう。
workaround.reg のような「存在しないキーへの置き換え」による対策は
yamyが動作していない場合これらのキーが機能しなくなるという副作用
があります。
そこでworkaround.reg相当の置き換え(以下、これを「NLSキーのエスケープ」
と呼ぶ)をyamyの動作中のみ行う機能を実験的に実装しました。
yamy起動時にレジストリをworkaround.reg相当に書き換えてから
(ログアウトすることなく)OSにScancode Map読み込ませた後、すぐに
レジストリを元に戻します。yamy終了時には(レジストリは既に元に
戻っているので)単にOSに再読み込みのみを指示します。
これにより、yamyの動作中のみNLSのエスケープを実現します。
尚、スクリーンロック(別ユーザへの簡易ユーザ切り替えを含む)した場合
及び、yamy を「一時停止」した場合はエスケープが解除され、元に戻ったら
再度エスケープを行います。
使用するレジストリはWindows7以外の場合は、
HKEY_CURRENT_USER\KeyBoard Layout\Scancode Map
Windows7の場合は、
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\KeyBoard Layout\Scancode Map
です。
この機能はデフォルトでは無効であり、有効にするためには yamy.ini において、
escapeNLSKeys=0
を
escapeNLSKeys=1
に変更します。ただしこの機能の利用に際しては以下の点に留意して下さい。
* 実験的な機能であり十分な動作実績がなく危険が伴います。
* yamyを実行するユーザにSeDebugPrivilege特権が必要です。Administrators
グループに属するユーザは既定でこの特権を持っています。
ただしUACが有効な場合は、加えて管理者として実行する必要があります。
* 対象となるNLSキーが既にScancode Mapで置き換えられている場合は
エスケープは行われません。
* エスケープのためレジストリを書き換えている一瞬の間にyamyが
異常終了した場合、エスケープ用のScancode Mapがレジストリに
残ります。この場合、regeditを使って元に戻して下さい。
* 上記の瞬間以外にyamyが異常終了した場合、レジストリは元に戻って
いますが、OS内部のScancode Mapは残っているので、一旦ログオフ・
ログオンして元に戻すか、yamyを再起動して下さい。
* VMware に対し、Scancode Map は有効ですが、yamy によるキー置換は
は働きません。このためエスケープされた(E0-が付加された)ままで
ゲストOSに届きます。ゲストも Windows の場合はゲスト内でも yamy
を動作させれば元のキーに置換できます。また、Linux の場合は
setkeycodes コマンドを使ってエスケープされたキーを元のスキャン
コードに置換できます。例えば101キーボードを使用している場合は
以下のコマンドによってエスケープされた `(~)[0x29] と CapsLock[0x3a]
を元のコードに戻せます。
> setkeycodes e029 41 e03a 58
その他のスキャンコードの置換ができないOSがゲスト場合は yamy を
一時停止してエスケープを解除して下さい。
3.3. &CancelPrefix関数
Prefix状態を強制的に解除するための関数&CancelPrefixが追加されました。
One Shotモディファイアに指定しているキーを離した際にPrefixを解除する
ために導入しました。
3.4. その他
* インストーラはありません。yamy-0.03.zip を任意のフォルダに展開し、
yamy.exe を実行して下さい。
* レジストリではなく、yamy.exe と同じフォルダにある yamy.ini に
設定情報の保存します。
* 設定ファイルはホームディレクトリではなく、yamy.exe のあるフォルダに
.mayu というファイル名で置いて下さい。
* キーボードの種別の判定は行いませんので、初回起動時にメニューの
「選択」で適切な設定を選択して下さい。
* リモートデスクトップでのログオン時でも起動を抑制しません。
4. 制限事項・不具合
* 画面ロック時はキー置換が働きません。また、この制限により画面ロック
への遷移時に押し下げられているキーがあった場合、そのキーが押しっぱなし
になることがあります。この場合、そのキーを空押しすることによって
押しっぱなしが解消します。特に Alt キーが押しっぱなしだと、パスワード
が入力できなくなるので注意して下さい。
* ユーザモードでのフックのため、以下の場合は機能しないと思われます。
- WH_KEYBOARD_LL をフックする他アプリとの共存
- DirectInput を使ったプログラム
* Pauseキーのようにスキャンコードに E1 プレフィックスが付いたキー
は置き換えられません。そのようなキーを使用したい場合は Scancode Map
レジストリを併用して下さい。
* セキュリティソフトによってはフックDLLのインストールをブロックされる
場合がありますので、その場合は yamy32/yamy64 を例外として登録して下さい。
5. ビルド方法
Visual Studio 2008 Professional + Windows SDK v6.1で確認しています。
yamyのビルドにはx64用コンパイラが必要になりますが、Visual Studio 2008
の既定のインストールではインストールされませんので追加でインストール
する必要があります。
5.1.
yamy と boost_1_38_0 のソースを入手し、以下の配置にて展開します。
./
|
+---boost_1_38_0/ ... http://www.boost.org/ から入手したアーカイブを展開
|
+---yamy/ ... "git clone git://git.sourceforge.jp/gitroot/yamy/yamy.git"等により展開
|
+---proj/ ...
+---tools/ ...
5.2.
yamy/proj/yamy.sln を Visual Studio で開き、ソリューションをビルドします。
5.3.
yamy/{Debug,Release}/ 以下にバイナリと zip パッケージが生成されます。
6. 著作権・ライセンス
YAMYの著作権・ライセンスは以下の通りです:
Yet Another Mado tsukai no Yuutsu(YAMY)
Copyright (C) 2009, <NAME> <<EMAIL>>
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. The name of the author may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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.
YAMYの派生元である「窓使いの憂鬱」の著作権・ライセンスは以下の通りです:
窓使いの憂鬱
Copyright (C) 1999-2005, <NAME> <<EMAIL>>
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. The name of the author may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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.
YAMYが利用しているBoostライブラリのライセンスは以下の通りです:
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
7. 謝辞
言うまでもなく「窓使いの憂鬱」がなければYAMYは存在し得ませんでした。
「窓使いの憂鬱」の作者である多賀奈由太さんと開発に貢献した方々にこの
場を借りて深くお礼申し上げます。
8. 履歴
2009/09/19 ver.0.03
* マウスイベント置換有効時に固まる場合がある問題を修正
* 入力処理スレッドにおいてキューの開放と待ちを不可分に行うよう変更
* 特定操作でIEをアクティブにするとフォーム内でEmacsEditにならないことがある問題(チケット#18663)を修正
* メールスロットが使えない場合にはWM_COPYDATAを使って通知する(チケット#17769,#18662を修正)
* 一時停止中はフックしたスキャンコードをそのままスルーするように変更(チケット#18691参照)
* yamy64 で &InvestigateCommand が機能しない問題を修正
* 終了後に特定のプロセスが原因で mayu{32,64}.dll が削除できなくなる問題を修正
2009/08/30 ver.0.02
* yamy{32,64}/yamyd32 を yamy.exe と同じフォルダから探すように変更
* Vistaでの権限昇格実行時に標準権限アプリのキーマップがグローバルになる問題を修正
* NLSキーのエスケープ機能を実験的に実装
* &CancelPrefix関数を追加
* マウスイベントの置換機能を追加
* リモートデスクトップ時の起動抑制を廃止
* ビルドシステムを変更
- makefileからVC++2008のプロジェクトに移行
- makefuncとzipでのパッケージ作成をJScriptで再実装
* 不具合修正
- ハングしているプロセスがあると終了できない(チケット#17643)
- 右シフトが押されたままになることがある(チケット#17607)
- yamyのダイアログを消す際に5秒程度フリーズすることがある(チケット#17767)
- 数秒間キー入力が滞ることがある(チケット#17576)
2009/06/28 ver.0.01
初リリース
以下は「窓使いの憂鬱」の最終版からの変更点
* キー入力置換をドライバからユーザモードに変更(NO_DRIVERマクロ)
- ドライバへのアクセスを排除
- キー入力のフックに WH_KEYBOARD_LL を使う
- キーイベント生成にSendInput() APIを使う
- WM_COPYDATA での通知でストールする場合があるのでメールスロットで通知(USE_MAILSLOTマクロ)
- 多重メッセージ対策として !PM_REMOVE なメッセージをフックDLLで無視
- RShiftにE0が付加されることに対応して{104,109}.mayuにworkaroundを追加
* 64bit対応(MAYU64マクロ)
- GetWindowLong -> GetWindowLongPtr 等の使用API変更
- LONG -> LONG_PTR 等の型変更
- HWND を DWORD にキャストして 32bit<->64bit 間で共有
- 64bit 時に 32bit プロセスへのフックをインストールする yamyd.cpp を新設
- objの出力ディレクトリを32bitと64bitで分けた
- WPARAM/LPARAM の実体が 64bit では異なるので、load_ARGUMENT()のオーバーロードを追加
- INVALID_HANDLE_VALUE=0xffffffff と仮定しない
- notifyCommand()を無効化(一時的措置)
* インストール無しでの実行
- インストーラをビルド対象から外す
- レジストリの替りに yamy.ini で設定する(USE_INIマクロ)
* ログ関連
- hook.cpp にデバッグマクロ追加
- デバッガ等の特定プロセスではフックDLLのデバッグ出力を抑止
- ログをファイルに記録する機能を追加(LOG_TO_FILEマクロ:既定は無効)
- OS側のキー押し下げ状態をログ出力する「チェック」機能を追加
* バグ修正
- Engine::setFocus()でクラッシュする問題を修正
- KeyIterator::KeyIterator()で空リスト処理時にassert failする問題を修正
- デバッグビルドではデバッグ版ランタイムをリンクする
* その他
- exeやdllのベースネームを mayu から yamy に変更
- 32bit/64bit の exe を呼び分けるランチャを導入
- フックDLLの初期化処理の大半を DllMain から外した
- boost::regex の更新に伴い tregex::use_except の明示を削除
- VC++9をデフォルトのコンパイラに変更
- LOGNAME -> USERNAME
- -GX を -EHsc に変更
- nmake のオプションから -k を削除
- フックを解除するため WM_NULL をブロードキャスト
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// array.h
#ifndef _ARRAY_H
# define _ARRAY_H
# include <memory>
///
template <class T, class Allocator = std::allocator<T> >
class Array
{
public:
typedef typename Allocator::reference reference; ///
typedef typename Allocator::const_reference const_reference; ///
typedef typename Allocator::pointer iterator; ///
typedef typename Allocator::const_pointer const_iterator; ///
typedef typename Allocator::size_type size_type; ///
typedef typename Allocator::difference_type difference_type; ///
typedef T value_type; ///
typedef Allocator allocator_type; ///
typedef typename Allocator::pointer pointer; ///
typedef typename Allocator::const_pointer const_pointer; ///
#if 0
typedef std::reverse_iterator<iterator> reverse_iterator; ///
typedef std::reverse_iterator<const_iterator> const_reverse_iterator; ///
#endif
private:
Allocator m_allocator; ///
size_type m_size; ///
pointer m_buf; /// array buffer
public:
/// constructor
explicit Array(const Allocator& i_allocator = Allocator())
: m_allocator(i_allocator), m_size(0), m_buf(NULL) { }
/// constructor
explicit Array(size_type i_size, const T& i_value = T(),
const Allocator& i_allocator = Allocator())
: m_allocator(i_allocator), m_size(i_size),
m_buf(m_allocator.allocate(m_size, 0)) {
std::uninitialized_fill_n(m_buf, i_size, i_value);
}
/// constructor
template <class InputIterator>
Array(InputIterator i_begin, InputIterator i_end,
const Allocator& i_allocator = Allocator())
: m_allocator(i_allocator), m_size(distance(i_begin, i_end)),
m_buf(Allocator::allocate(m_size, 0)) {
std::uninitialized_copy(i_begin, i_end, m_buf);
}
/// copy constructor
Array(const Array& i_o) : m_size(0), m_buf(NULL) {
operator=(i_o);
}
/// destractor
~Array() {
clear();
}
///
Array& operator=(const Array& i_o) {
if (&i_o != this) {
clear();
m_size = i_o.m_size;
m_buf = m_allocator.allocate(m_size, 0);
std::uninitialized_copy(i_o.m_buf, i_o.m_buf + m_size, m_buf);
}
return *this;
}
///
allocator_type get_allocator() const {
return Allocator();
}
/// return pointer to the array buffer
typename allocator_type::pointer get() {
return m_buf;
}
/// return pointer to the array buffer
typename allocator_type::const_pointer get() const {
return m_buf;
}
///
iterator begin() {
return m_buf;
}
///
const_iterator begin() const {
return m_buf;
}
///
iterator end() {
return m_buf + m_size;
}
///
const_iterator end() const {
return m_buf + m_size;
}
#if 0
///
reverse_iterator rbegin() {
reverse_iterator(end());
}
///
const_reverse_iterator rbegin() const {
const_reverse_iterator(end());
}
///
reverse_iterator rend() {
reverse_iterator(begin());
}
///
const_reverse_iterator rend() const {
const_reverse_iterator(begin());
}
#endif
///
size_type size() const {
return m_size;
}
///
size_type max_size() const {
return -1;
}
/// resize the array buffer. NOTE: the original contents are cleared.
void resize(size_type i_size, const T& i_value = T()) {
clear();
m_size = i_size;
m_buf = m_allocator.allocate(m_size, 0);
std::uninitialized_fill_n(m_buf, i_size, i_value);
}
/// resize the array buffer.
template <class InputIterator>
void resize(InputIterator i_begin, InputIterator i_end) {
clear();
m_size = distance(i_begin, i_end);
m_buf = m_allocator.allocate(m_size, 0);
std::uninitialized_copy(i_begin, i_end, m_buf);
}
/// expand the array buffer. the contents of it are copied to the new one
void expand(size_type i_size, const T& i_value = T()) {
ASSERT( m_size <= i_size );
if (!m_buf)
resize(i_size, i_value);
else {
pointer buf = m_allocator.allocate(i_size, 0);
std::uninitialized_copy(m_buf, m_buf + m_size, buf);
std::uninitialized_fill_n(buf + m_size, i_size - m_size, i_value);
clear();
m_size = i_size;
m_buf = buf;
}
}
///
bool empty() const {
return !m_buf;
}
///
reference operator[](size_type i_n) {
return *(m_buf + i_n);
}
///
const_reference operator[](size_type i_n) const {
return *(m_buf + i_n);
}
///
const_reference at(size_type i_n) const {
return *(m_buf + i_n);
}
///
reference at(size_type i_n) {
return *(m_buf + i_n);
}
///
reference front() {
return *m_buf;
}
///
const_reference front() const {
return *m_buf;
}
///
reference back() {
return *(m_buf + m_size - 1);
}
///
const_reference back() const {
return *(m_buf + m_size - 1);
}
///
void swap(Array &i_o) {
if (&i_o != this) {
pointer buf = m_buf;
size_type size = m_size;
m_buf = i_o.m_buf;
m_size = i_o.m_size;
i_o.m_buf = buf;
i_o.m_size = size;
}
}
///
void clear() {
if (m_buf) {
for (size_type i = 0; i < m_size; i ++)
m_allocator.destroy(&m_buf[i]);
m_allocator.deallocate(m_buf, m_size);
m_buf = 0;
m_size = 0;
}
}
};
#endif // _ARRAY_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// target.cpp
#include "misc.h"
#include "mayurc.h"
#include "target.h"
#include "windowstool.h"
///
class Target
{
HWND m_hwnd; ///
HWND m_preHwnd; ///
HICON m_hCursor; ///
///
static void invertFrame(HWND i_hwnd) {
HDC hdc = GetWindowDC(i_hwnd);
ASSERT(hdc);
int rop2 = SetROP2(hdc, R2_XORPEN);
if (rop2) {
RECT rc;
CHECK_TRUE( GetWindowRect(i_hwnd, &rc) );
int width = rcWidth(&rc);
int height = rcHeight(&rc);
HANDLE hpen = SelectObject(hdc, GetStockObject(WHITE_PEN));
HANDLE hbr = SelectObject(hdc, GetStockObject(NULL_BRUSH));
CHECK_TRUE( Rectangle(hdc, 0, 0, width , height ) );
CHECK_TRUE( Rectangle(hdc, 1, 1, width - 1, height - 1) );
CHECK_TRUE( Rectangle(hdc, 2, 2, width - 2, height - 2) );
SelectObject(hdc, hpen);
SelectObject(hdc, hbr);
// no need to DeleteObject StockObject
SetROP2(hdc, rop2);
}
CHECK_TRUE( ReleaseDC(i_hwnd, hdc) );
}
///
Target(HWND i_hwnd)
: m_hwnd(i_hwnd),
m_preHwnd(NULL),
m_hCursor(NULL) {
}
/// WM_CREATE
int wmCreate(CREATESTRUCT * /* i_cs */) {
CHECK_TRUE( m_hCursor =
LoadCursor(g_hInst, MAKEINTRESOURCE(IDC_CURSOR_target)) );
return 0;
}
/// WM_PAINT
int wmPaint() {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(m_hwnd, &ps);
ASSERT(hdc);
if (GetCapture() != m_hwnd) {
RECT rc;
CHECK_TRUE( GetClientRect(m_hwnd, &rc) );
CHECK_TRUE(
DrawIcon(hdc, (rcWidth(&rc) - GetSystemMetrics(SM_CXICON)) / 2,
(rcHeight(&rc) - GetSystemMetrics(SM_CYICON)) / 2,
m_hCursor) );
}
EndPaint(m_hwnd, &ps);
return 0;
}
///
struct PointWindow {
POINT m_p; ///
HWND m_hwnd; ///
RECT m_rc; ///
};
///
static BOOL CALLBACK childWindowFromPoint(HWND i_hwnd, LPARAM i_lParam) {
if (IsWindowVisible(i_hwnd)) {
PointWindow &pw = *(PointWindow *)i_lParam;
RECT rc;
CHECK_TRUE( GetWindowRect(i_hwnd, &rc) );
if (PtInRect(&rc, pw.m_p))
if (isRectInRect(&rc, &pw.m_rc)) {
pw.m_hwnd = i_hwnd;
pw.m_rc = rc;
}
}
return TRUE;
}
///
static BOOL CALLBACK windowFromPoint(HWND i_hwnd, LPARAM i_lParam) {
if (IsWindowVisible(i_hwnd)) {
PointWindow &pw = *(PointWindow *)i_lParam;
RECT rc;
CHECK_TRUE( GetWindowRect(i_hwnd, &rc) );
if (PtInRect(&rc, pw.m_p)) {
pw.m_hwnd = i_hwnd;
pw.m_rc = rc;
return FALSE;
}
}
return TRUE;
}
/// WM_MOUSEMOVE
int wmMouseMove(WORD /* i_keys */, int /* i_x */, int /* i_y */) {
if (GetCapture() == m_hwnd) {
PointWindow pw;
CHECK_TRUE( GetCursorPos(&pw.m_p) );
pw.m_hwnd = 0;
CHECK_TRUE( GetWindowRect(GetDesktopWindow(), &pw.m_rc) );
EnumWindows(windowFromPoint, (LPARAM)&pw);
while (1) {
HWND hwndParent = pw.m_hwnd;
if (!EnumChildWindows(pw.m_hwnd, childWindowFromPoint, (LPARAM)&pw))
break;
if (hwndParent == pw.m_hwnd)
break;
}
if (pw.m_hwnd != m_preHwnd) {
if (m_preHwnd)
invertFrame(m_preHwnd);
m_preHwnd = pw.m_hwnd;
invertFrame(m_preHwnd);
SendMessage(GetParent(m_hwnd), WM_APP_targetNotify, 0,
(LPARAM)m_preHwnd);
}
SetCursor(m_hCursor);
}
return 0;
}
/// WM_LBUTTONDOWN
int wmLButtonDown(WORD /* i_keys */, int /* i_x */, int /* i_y */) {
SetCapture(m_hwnd);
SetCursor(m_hCursor);
CHECK_TRUE( InvalidateRect(m_hwnd, NULL, TRUE) );
CHECK_TRUE( UpdateWindow(m_hwnd) );
return 0;
}
/// WM_LBUTTONUP
int wmLButtonUp(WORD /* i_keys */, int /* i_x */, int /* i_y */) {
if (m_preHwnd)
invertFrame(m_preHwnd);
m_preHwnd = NULL;
ReleaseCapture();
CHECK_TRUE( InvalidateRect(m_hwnd, NULL, TRUE) );
CHECK_TRUE( UpdateWindow(m_hwnd) );
return 0;
}
public:
///
static LRESULT CALLBACK WndProc(HWND i_hwnd, UINT i_message,
WPARAM i_wParam, LPARAM i_lParam) {
Target *wc;
getUserData(i_hwnd, &wc);
if (!wc)
switch (i_message) {
case WM_CREATE:
wc = setUserData(i_hwnd, new Target(i_hwnd));
return wc->wmCreate((CREATESTRUCT *)i_lParam);
}
else
switch (i_message) {
case WM_PAINT:
return wc->wmPaint();
case WM_LBUTTONDOWN:
return wc->wmLButtonDown((WORD)i_wParam, (short)LOWORD(i_lParam),
(short)HIWORD(i_lParam));
case WM_LBUTTONUP:
return wc->wmLButtonUp((WORD)i_wParam, (short)LOWORD(i_lParam),
(short)HIWORD(i_lParam));
case WM_MOUSEMOVE:
return wc->wmMouseMove((WORD)i_wParam, (short)LOWORD(i_lParam),
(short)HIWORD(i_lParam));
case WM_NCDESTROY:
delete wc;
return 0;
}
return DefWindowProc(i_hwnd, i_message, i_wParam, i_lParam);
}
};
//
ATOM Register_target()
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = Target::WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = g_hInst;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = _T("mayuTarget");
return RegisterClass(&wc);
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// dlgversion.h
#ifndef _DLGVERSION_H
# define _DLGVERSION_H
# include <windows.h>
///
#ifdef MAYU64
INT_PTR CALLBACK dlgVersion_dlgProc(
#else
BOOL CALLBACK dlgVersion_dlgProc(
#endif
HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam);
#endif // !_DLGVERSION_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// dlgversion.cpp
#include "misc.h"
#include "mayu.h"
#include "mayurc.h"
#include "windowstool.h"
#include "compiler_specific_func.h"
#include "layoutmanager.h"
#include <cstdio>
#include <windowsx.h>
///
class DlgVersion : public LayoutManager
{
HWND m_hwnd; ///
public:
///
DlgVersion(HWND i_hwnd)
: LayoutManager(i_hwnd),
m_hwnd(i_hwnd) {
}
/// WM_INITDIALOG
BOOL wmInitDialog(HWND /* i_focus */, LPARAM i_lParam) {
TCHAR *mayudVersion = (TCHAR*)i_lParam;
setSmallIcon(m_hwnd, IDI_ICON_mayu);
setBigIcon(m_hwnd, IDI_ICON_mayu);
_TCHAR modulebuf[1024];
CHECK_TRUE( GetModuleFileName(g_hInst, modulebuf,
NUMBER_OF(modulebuf)) );
_TCHAR buf[1024];
_sntprintf(buf, NUMBER_OF(buf), loadString(IDS_version).c_str(),
_T(VERSION)
#ifndef NDEBUG
_T(" (DEBUG)")
#endif // !NDEBUG
#ifdef _UNICODE
_T(" (UNICODE)")
#endif // !_UNICODE
,
loadString(IDS_homepage).c_str(),
(_T(LOGNAME) _T("@") + toLower(_T(COMPUTERNAME))).c_str(),
_T(__DATE__) _T(" ") _T(__TIME__),
getCompilerVersionString().c_str(),
modulebuf);
Edit_SetText(GetDlgItem(m_hwnd, IDC_EDIT_builtBy), buf);
// set layout manager
typedef LayoutManager LM;
addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuIcon),
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_EDIT_builtBy),
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_BOTTOM_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_BUTTON_download),
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE,
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE);
addItem(GetDlgItem(m_hwnd, IDOK),
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE,
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE);
restrictSmallestSize();
return TRUE;
}
/// WM_CLOSE
BOOL wmClose() {
CHECK_TRUE( EndDialog(m_hwnd, 0) );
return TRUE;
}
/// WM_COMMAND
BOOL wmCommand(int /* i_notifyCode */, int i_id, HWND /* i_hwndControl */) {
switch (i_id) {
case IDOK: {
CHECK_TRUE( EndDialog(m_hwnd, 0) );
return TRUE;
}
case IDC_BUTTON_download: {
ShellExecute(NULL, NULL, loadString(IDS_homepage).c_str(),
NULL, NULL, SW_SHOWNORMAL);
CHECK_TRUE( EndDialog(m_hwnd, 0) );
return TRUE;
}
}
return FALSE;
}
};
//
#ifdef MAYU64
INT_PTR CALLBACK dlgVersion_dlgProc(
#else
BOOL CALLBACK dlgVersion_dlgProc(
#endif
HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam)
{
DlgVersion *wc;
getUserData(i_hwnd, &wc);
if (!wc)
switch (i_message) {
case WM_INITDIALOG:
wc = setUserData(i_hwnd, new DlgVersion(i_hwnd));
return wc->wmInitDialog(reinterpret_cast<HWND>(i_wParam), i_lParam);
}
else
switch (i_message) {
case WM_COMMAND:
return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam),
reinterpret_cast<HWND>(i_lParam));
case WM_CLOSE:
return wc->wmClose();
case WM_NCDESTROY:
delete wc;
return TRUE;
default:
return wc->defaultWMHandler(i_message, i_wParam, i_lParam);
}
return FALSE;
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// dlglog.cpp
#include "misc.h"
#include "mayu.h"
#include "mayurc.h"
#include "registry.h"
#include "windowstool.h"
#include "msgstream.h"
#include "layoutmanager.h"
#include "dlglog.h"
#include <windowsx.h>
///
class DlgLog : public LayoutManager
{
HWND m_hwndEdit; ///
HWND m_hwndTaskTray; /// tasktray window
LOGFONT m_lf; ///
HFONT m_hfontOriginal; ///
HFONT m_hfont; ///
tomsgstream *m_log; ///
public:
///
DlgLog(HWND i_hwnd)
: LayoutManager(i_hwnd),
m_hwndEdit(GetDlgItem(m_hwnd, IDC_EDIT_log)),
m_hwndTaskTray(NULL),
m_hfontOriginal(GetWindowFont(m_hwnd)),
m_hfont(NULL) {
}
/// WM_INITDIALOG
BOOL wmInitDialog(HWND /* i_focus */, LPARAM i_lParam) {
DlgLogData *dld = reinterpret_cast<DlgLogData *>(i_lParam);
m_log = dld->m_log;
m_hwndTaskTray = dld->m_hwndTaskTray;
// set icons
setSmallIcon(m_hwnd, IDI_ICON_mayu);
setBigIcon(m_hwnd, IDI_ICON_mayu);
// set font
Registry::read(MAYU_REGISTRY_ROOT, _T("logFont"), &m_lf,
loadString(IDS_logFont));
m_hfont = CreateFontIndirect(&m_lf);
SetWindowFont(m_hwndEdit, m_hfont, false);
// resize
RECT rc;
CHECK_TRUE( GetClientRect(m_hwnd, &rc) );
wmSize(0, (short)rc.right, (short)rc.bottom);
// debug level
bool isChecked =
(IsDlgButtonChecked(m_hwnd, IDC_CHECK_detail) == BST_CHECKED);
m_log->setDebugLevel(isChecked ? 1 : 0);
// set layout manager
typedef LayoutManager LM;
addItem(GetDlgItem(m_hwnd, IDOK),
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE,
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_EDIT_log),
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_BOTTOM_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_BUTTON_clearLog),
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE,
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_BUTTON_changeFont),
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE,
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_CHECK_detail),
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE,
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE);
restrictSmallestSize();
// enlarge window
GetWindowRect(m_hwnd, &rc);
rc.bottom += (rc.bottom - rc.top) * 3;
MoveWindow(m_hwnd, rc.left, rc.top,
rc.right - rc.left, rc.bottom - rc.top, true);
return TRUE;
}
/// WM_DESTROY
BOOL wmDestroy() {
// unset font
SetWindowFont(m_hwndEdit, m_hfontOriginal, false);
DeleteObject(m_hfont);
// unset icons
unsetBigIcon(m_hwnd);
unsetSmallIcon(m_hwnd);
return TRUE;
}
/// WM_CLOSE
BOOL wmClose() {
ShowWindow(m_hwnd, SW_HIDE);
return TRUE;
}
/// WM_COMMAND
BOOL wmCommand(int /* i_notifyCode */, int i_id, HWND /* i_hwndControl */) {
switch (i_id) {
case IDOK: {
ShowWindow(m_hwnd, SW_HIDE);
return TRUE;
}
case IDC_BUTTON_clearLog: {
Edit_SetSel(m_hwndEdit, 0, Edit_GetTextLength(m_hwndEdit));
Edit_ReplaceSel(m_hwndEdit, _T(""));
SendMessage(m_hwndTaskTray, WM_APP_dlglogNotify,
DlgLogNotify_logCleared, 0);
return TRUE;
}
case IDC_BUTTON_changeFont: {
CHOOSEFONT cf;
memset(&cf, 0, sizeof(cf));
cf.lStructSize = sizeof(cf);
cf.hwndOwner = m_hwnd;
cf.lpLogFont = &m_lf;
cf.Flags = CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS;
if (ChooseFont(&cf)) {
HFONT hfontNew = CreateFontIndirect(&m_lf);
SetWindowFont(m_hwnd, hfontNew, true);
DeleteObject(m_hfont);
m_hfont = hfontNew;
Registry::write(MAYU_REGISTRY_ROOT, _T("logFont"), m_lf);
}
return TRUE;
}
case IDC_CHECK_detail: {
bool isChecked =
(IsDlgButtonChecked(m_hwnd, IDC_CHECK_detail) == BST_CHECKED);
m_log->setDebugLevel(isChecked ? 1 : 0);
return TRUE;
}
}
return FALSE;
}
};
//
#ifdef MAYU64
INT_PTR CALLBACK dlgLog_dlgProc(HWND i_hwnd, UINT i_message,
#else
BOOL CALLBACK dlgLog_dlgProc(HWND i_hwnd, UINT i_message,
#endif
WPARAM i_wParam, LPARAM i_lParam)
{
DlgLog *wc;
getUserData(i_hwnd, &wc);
if (!wc)
switch (i_message) {
case WM_INITDIALOG:
wc = setUserData(i_hwnd, new DlgLog(i_hwnd));
return wc->wmInitDialog(reinterpret_cast<HWND>(i_wParam), i_lParam);
}
else
switch (i_message) {
case WM_COMMAND:
return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam),
reinterpret_cast<HWND>(i_lParam));
case WM_CLOSE:
return wc->wmClose();
case WM_DESTROY:
return wc->wmDestroy();
case WM_NCDESTROY:
delete wc;
return TRUE;
default:
return wc->defaultWMHandler(i_message, i_wParam, i_lParam);
}
return FALSE;
}
<file_sep>#if DBG
#include <ntddk.h>
#include <stdarg.h>
#include "log.h"
#define BUF_MAX_SIZE 128
typedef struct _logEntry {
LIST_ENTRY listEntry;
UNICODE_STRING log;
} logEntry;
static LIST_ENTRY s_logList;
static KSPIN_LOCK s_logListLock;
static PIRP s_irp;
void mayuLogInit(const char *message)
{
InitializeListHead(&s_logList);
KeInitializeSpinLock(&s_logListLock);
s_irp = NULL;
mayuLogEnque(message);
}
void mayuLogTerm()
{
if (s_irp) {
IoReleaseCancelSpinLock(s_irp->CancelIrql);
s_irp->IoStatus.Status = STATUS_CANCELLED;
s_irp->IoStatus.Information = 0;
IoCompleteRequest(s_irp, IO_NO_INCREMENT);
s_irp = NULL;
}
}
void mayuLogEnque(const char *fmt, ...)
{
va_list argp;
logEntry *entry;
ANSI_STRING ansiBuf;
UNICODE_STRING unicodeBuf;
CHAR buf[BUF_MAX_SIZE] = "";
WCHAR wbuf[BUF_MAX_SIZE] = L"";
USHORT i, j;
ULONG ul;
PUNICODE_STRING punicode;
entry = (logEntry*)ExAllocatePool(NonPagedPool, sizeof(logEntry));
if (!entry)
return;
entry->log.Length = 0;
entry->log.MaximumLength = BUF_MAX_SIZE;
entry->log.Buffer = (PWSTR)ExAllocatePool(NonPagedPool, BUF_MAX_SIZE);
unicodeBuf.Length = 0;
unicodeBuf.MaximumLength = BUF_MAX_SIZE;
unicodeBuf.Buffer = wbuf;
ansiBuf.Length = 0;
ansiBuf.MaximumLength = BUF_MAX_SIZE;
ansiBuf.Buffer = buf;
va_start(argp, fmt);
for (i = j = 0; i < BUF_MAX_SIZE; ++i) {
ansiBuf.Buffer[i - j] = fmt[i];
if (fmt[i] == '\0') {
ansiBuf.Length = i - j;
RtlAnsiStringToUnicodeString(&unicodeBuf, &ansiBuf, FALSE);
RtlAppendUnicodeStringToString(&entry->log, &unicodeBuf);
break;
}
if (fmt[i] == '%') {
ansiBuf.Length = i - j;
RtlAnsiStringToUnicodeString(&unicodeBuf, &ansiBuf, FALSE);
RtlAppendUnicodeStringToString(&entry->log, &unicodeBuf);
switch (fmt[++i]) {
case 'x':
ul = va_arg(argp, ULONG);
RtlIntegerToUnicodeString(ul, 16, &unicodeBuf);
RtlAppendUnicodeStringToString(&entry->log, &unicodeBuf);
break;
case 'd':
ul = va_arg(argp, ULONG);
RtlIntegerToUnicodeString(ul, 10, &unicodeBuf);
RtlAppendUnicodeStringToString(&entry->log, &unicodeBuf);
break;
case 'T':
punicode = va_arg(argp, PUNICODE_STRING);
RtlAppendUnicodeStringToString(&entry->log, punicode);
}
j = i + 1;
}
}
va_end(argp);
ExInterlockedInsertTailList(&s_logList, &entry->listEntry, &s_logListLock);
if (s_irp) {
KIRQL cancelIrql;
mayuLogDeque(s_irp);
IoAcquireCancelSpinLock(&cancelIrql);
IoSetCancelRoutine(s_irp, NULL);
IoReleaseCancelSpinLock(cancelIrql);
IoCompleteRequest(s_irp, IO_NO_INCREMENT);
s_irp = NULL;
}
}
VOID mayuLogCancel(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
s_irp = NULL;
IoReleaseCancelSpinLock(irp->CancelIrql);
irp->IoStatus.Status = STATUS_CANCELLED;
irp->IoStatus.Information = 0;
IoCompleteRequest(irp, IO_NO_INCREMENT);
}
NTSTATUS mayuLogDeque(PIRP irp)
{
KIRQL currentIrql;
KeAcquireSpinLock(&s_logListLock, ¤tIrql);
if (IsListEmpty(&s_logList) == TRUE) {
KIRQL cancelIrql;
IoAcquireCancelSpinLock(&cancelIrql);
IoMarkIrpPending(irp);
s_irp = irp;
IoSetCancelRoutine(irp, mayuLogCancel);
IoReleaseCancelSpinLock(cancelIrql);
KeReleaseSpinLock(&s_logListLock, currentIrql);
irp->IoStatus.Information = 0;
irp->IoStatus.Status = STATUS_PENDING;
} else {
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp);
PLIST_ENTRY pListEntry;
logEntry *pEntry;
KeReleaseSpinLock(&s_logListLock, currentIrql);
pListEntry = ExInterlockedRemoveHeadList(&s_logList, &s_logListLock);
pEntry = CONTAINING_RECORD(pListEntry, logEntry, listEntry);
RtlCopyMemory(irp->AssociatedIrp.SystemBuffer,
pEntry->log.Buffer, pEntry->log.Length);
irp->IoStatus.Information = pEntry->log.Length;
irp->IoStatus.Status = STATUS_SUCCESS;
ExFreePool(pEntry->log.Buffer);
ExFreePool(pEntry);
}
return irp->IoStatus.Status;
}
#endif // DBG
<file_sep>#ifndef _LOG_H
#define _LOG_H
#if DBG
// Initiallize logging queue and enqueue "message" as
// first log.
void mayuLogInit(const char *message);
// Finalize logging queue.
void mayuLogTerm(void);
// Enqueue one message to loggin queue.
// Use printf like format to enqueue,
// following types are available.
// %x: (ULONG)unsigned long in hexadecimal
// %d: (ULONG)unsigned long in decimal
// %T: (PUNICODE)pointer to unicode string
// Notice: specifing minimal width such as "%2d"
// is unavailable yet.
void mayuLogEnque(const char *fmt, ...);
// Dequeue one message from logging queue to "irp".
NTSTATUS mayuLogDeque(PIRP irp);
#endif // DBG
#endif // !_LOG_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// stringtool.h
#ifndef _STRINGTOOL_H
# define _STRINGTOOL_H
# include "misc.h"
# include <tchar.h>
# include <cctype>
# include <string>
# include <iosfwd>
# include <fstream>
# include <locale>
# include <boost/regex.hpp>
# include <stdio.h> // for snprintf
/// string for generic international text
typedef std::basic_string<_TCHAR> tstring;
/// istream for generic international text
typedef std::basic_istream<_TCHAR> tistream;
/// ostream for generic international text
typedef std::basic_ostream<_TCHAR> tostream;
/// streambuf for for generic international text
typedef std::basic_streambuf<_TCHAR> tstreambuf;
/// stringstream for generic international text
typedef std::basic_stringstream<_TCHAR> tstringstream;
/// ifstream for generic international text
typedef std::basic_ifstream<_TCHAR> tifstream;
/// ofstream for generic international text
typedef std::basic_ofstream<_TCHAR> tofstream;
/// basic_regex for generic international text
typedef boost::basic_regex<_TCHAR> tregex;
/// match_results for generic international text
typedef boost::match_results<tstring::const_iterator> tsmatch;
/// string with custom stream output
class tstringq : public tstring
{
public:
///
tstringq() { }
///
tstringq(const tstringq &i_str) : tstring(i_str) { }
///
tstringq(const tstring &i_str) : tstring(i_str) { }
///
tstringq(const _TCHAR *i_str) : tstring(i_str) { }
///
tstringq(const _TCHAR *i_str, size_t i_n) : tstring(i_str, i_n) { }
///
tstringq(const _TCHAR *i_str, size_t i_pos, size_t i_n)
: tstring(i_str, i_pos, i_n) { }
///
tstringq(size_t i_n, _TCHAR i_c) : tstring(i_n, i_c) { }
};
/// stream output
extern tostream &operator<<(tostream &i_ost, const tstringq &i_data);
/// interpret meta characters such as \n
tstring interpretMetaCharacters(const _TCHAR *i_str, size_t i_len,
const _TCHAR *i_quote = NULL,
bool i_doesUseRegexpBackReference = false);
/// add session id to i_str
tstring addSessionId(const _TCHAR *i_str);
/// copy
size_t strlcpy(char *o_dest, const char *i_src, size_t i_destSize);
/// copy
size_t mbslcpy(unsigned char *o_dest, const unsigned char *i_src,
size_t i_destSize);
/// copy
size_t wcslcpy(wchar_t *o_dest, const wchar_t *i_src, size_t i_destSize);
/// copy
inline size_t tcslcpy(char *o_dest, const char *i_src, size_t i_destSize)
{
return strlcpy(o_dest, i_src, i_destSize);
}
/// copy
inline size_t tcslcpy(unsigned char *o_dest, const unsigned char *i_src,
size_t i_destSize)
{
return mbslcpy(o_dest, i_src, i_destSize);
}
/// copy
inline size_t tcslcpy(wchar_t *o_dest, const wchar_t *i_src, size_t i_destSize)
{
return wcslcpy(o_dest, i_src, i_destSize);
}
// escape regexp special characters in MBCS trail bytes
std::string guardRegexpFromMbcs(const char *i_str);
/// converter
std::wstring to_wstring(const std::string &i_str);
/// converter
std::string to_string(const std::wstring &i_str);
// convert wstring to UTF-8
std::string to_UTF_8(const std::wstring &i_str);
/// case insensitive string
class tstringi : public tstring
{
public:
///
tstringi() { }
///
tstringi(const tstringi &i_str) : tstring(i_str) { }
///
tstringi(const tstring &i_str) : tstring(i_str) { }
///
tstringi(const _TCHAR *i_str) : tstring(i_str) { }
///
tstringi(const _TCHAR *i_str, size_t i_n) : tstring(i_str, i_n) { }
///
tstringi(const _TCHAR *i_str, size_t i_pos, size_t i_n)
: tstring(i_str, i_pos, i_n) { }
///
tstringi(size_t i_n, _TCHAR i_c) : tstring(i_n, i_c) { }
///
int compare(const tstringi &i_str) const {
return compare(i_str.c_str());
}
///
int compare(const tstring &i_str) const {
return compare(i_str.c_str());
}
///
int compare(const _TCHAR *i_str) const {
return _tcsicmp(c_str(), i_str);
}
///
tstring &getString() {
return *this;
}
///
const tstring &getString() const {
return *this;
}
};
/// case insensitive string comparison
inline bool operator<(const tstringi &i_str1, const _TCHAR *i_str2)
{
return i_str1.compare(i_str2) < 0;
}
/// case insensitive string comparison
inline bool operator<(const _TCHAR *i_str1, const tstringi &i_str2)
{
return 0 < i_str2.compare(i_str1);
}
/// case insensitive string comparison
inline bool operator<(const tstringi &i_str1, const tstring &i_str2)
{
return i_str1.compare(i_str2) < 0;
}
/// case insensitive string comparison
inline bool operator<(const tstring &i_str1, const tstringi &i_str2)
{
return 0 < i_str2.compare(i_str1);
}
/// case insensitive string comparison
inline bool operator<(const tstringi &i_str1, const tstringi &i_str2)
{
return i_str1.compare(i_str2) < 0;
}
/// case insensitive string comparison
inline bool operator==(const _TCHAR *i_str1, const tstringi &i_str2)
{
return i_str2.compare(i_str1) == 0;
}
/// case insensitive string comparison
inline bool operator==(const tstringi &i_str1, const _TCHAR *i_str2)
{
return i_str1.compare(i_str2) == 0;
}
/// case insensitive string comparison
inline bool operator==(const tstring &i_str1, const tstringi &i_str2)
{
return i_str2.compare(i_str1) == 0;
}
/// case insensitive string comparison
inline bool operator==(const tstringi &i_str1, const tstring &i_str2)
{
return i_str1.compare(i_str2) == 0;
}
/// case insensitive string comparison
inline bool operator==(const tstringi &i_str1, const tstringi &i_str2)
{
return i_str1.compare(i_str2) == 0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// workarounds for Borland C++
/// case insensitive string comparison
inline bool operator!=(const _TCHAR *i_str1, const tstringi &i_str2)
{
return i_str2.compare(i_str1) != 0;
}
/// case insensitive string comparison
inline bool operator!=(const tstringi &i_str1, const _TCHAR *i_str2)
{
return i_str1.compare(i_str2) != 0;
}
/// case insensitive string comparison
inline bool operator!=(const tstring &i_str1, const tstringi &i_str2)
{
return i_str2.compare(i_str1) != 0;
}
/// case insensitive string comparison
inline bool operator!=(const tstringi &i_str1, const tstring &i_str2)
{
return i_str1.compare(i_str2) != 0;
}
/// case insensitive string comparison
inline bool operator!=(const tstringi &i_str1, const tstringi &i_str2)
{
return i_str1.compare(i_str2) != 0;
}
/// stream output
extern tostream &operator<<(tostream &i_ost, const tregex &i_data);
/// get lower string
extern tstring toLower(const tstring &i_str);
#endif // !_STRINGTOOL_H
<file_sep>#ifndef _IOCTL_H
#define _IOCTL_H
#define TOUCHPAD_SCANCODE 0xfe
// Ioctl value
#define IOCTL_MAYU_DETOUR_CANCEL \
CTL_CODE(FILE_DEVICE_KEYBOARD, 0x801, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_MAYU_GET_VERSION \
CTL_CODE(FILE_DEVICE_KEYBOARD, 0x802, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_MAYU_GET_LOG \
CTL_CODE(FILE_DEVICE_KEYBOARD, 0x803, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_MAYU_FORCE_KEYBOARD_INPUT \
CTL_CODE(FILE_DEVICE_KEYBOARD, 0x804, METHOD_BUFFERED, FILE_WRITE_ACCESS)
#endif // !_IOCTL_H
<file_sep>############################################################## -*- Makefile -*-
#
# Makefile for mayu
#
###############################################################################
F = mayu-vc.mak
all:
@echo "============================================================================="
@echo "Visual C++ 6.0:"
@echo " nmake MAYU_VC=vc6"
@echo " nmake MAYU_VC=vc6 clean"
@echo " nmake MAYU_VC=vc6 distrib"
@echo " nmake MAYU_VC=vc6 depend"
@echo "Visual C++ 7.0:"
@echo " nmake MAYU_VC=vc7"
@echo " nmake MAYU_VC=vc7 clean"
@echo " nmake MAYU_VC=vc7 distrib"
@echo " nmake MAYU_VC=vc7 depend"
@echo "Visual C++ 7.1:"
@echo " nmake MAYU_VC=vc71"
@echo " nmake MAYU_VC=vc71 clean"
@echo " nmake MAYU_VC=vc71 distrib"
@echo " nmake MAYU_VC=vc71 depend"
@echo "Visual C++ Toolkit 2003:"
@echo " nmake MAYU_VC=vct"
@echo " nmake MAYU_VC=vct clean"
@echo " nmake MAYU_VC=vct distrib"
@echo " nmake MAYU_VC=vct depend"
@echo "============================================================================="
$(MAKE) -f $(F) $(MAKEFLAGS) batch
clean:
$(MAKE) -f $(F) $(MAKEFLAGS) batch_clean
distclean:
$(MAKE) -f $(F) $(MAKEFLAGS) batch_distclean
distrib:
$(MAKE) -f $(F) $(MAKEFLAGS) batch_distrib
depend:
$(MAKE) -f $(F) $(MAKEFLAGS) TARGETOS=WINNT depend
<file_sep>///////////////////////////////////////////////////////////////////////////////
// Driver for Madotsukai no Yu^utsu for WindowsNT4.0
#define MAYUD_NT4
#include "../mayud.c"
<file_sep>#include <windows.h>
#include <process.h>
#include <tchar.h>
#include "../driver.h"
#ifdef STS4MAYU
#include "SynKit.h"
#pragma comment(lib, "SynCom.lib")
#endif /* STS4MAYU */
#ifdef CTS4MAYU
#include "Touchpad.h"
#pragma comment(lib, "TouchPad.lib")
#endif /* CTS4MAYU */
static HANDLE s_instance;
static UINT s_engineThreadId;
#ifdef STS4MAYU
static ISynAPI *s_synAPI;
static ISynDevice *s_synDevice;
static HANDLE s_notifyEvent;
static int s_terminated;
static HANDLE s_loopThread;
static unsigned int s_loopThreadId;
#endif /* STS4MAYU */
#ifdef CTS4MAYU
static HTOUCHPAD s_hTP[16];
static int s_devNum;
#endif /* CTS4MAYU */
static void changeTouch(int i_isBreak)
{
PostThreadMessage(s_engineThreadId, WM_APP + 201, i_isBreak ? 0 : 1, 0);
}
static void postEvent(WPARAM wParam, LPARAM lParam)
{
PostThreadMessage(s_engineThreadId, WM_APP + 201, wParam, lParam);
}
#ifdef STS4MAYU
static unsigned int WINAPI loop(void *dummy)
{
HRESULT result;
SynPacket packet;
int isTouched = 0;
while (s_terminated == 0) {
WaitForSingleObject(s_notifyEvent, INFINITE);
if (s_terminated) {
break;
}
for (;;) {
long value;
result = s_synAPI->GetEventParameter(&value);
if (result != SYN_OK) {
break;
}
if (value == SE_Configuration_Changed) {
s_synDevice->SetEventNotification(s_notifyEvent);
}
}
for (;;) {
result = s_synDevice->LoadPacket(packet);
if (result == SYNE_FAIL) {
break;
}
if (isTouched) {
if (!(packet.FingerState() & SF_FingerTouch)) {
changeTouch(1);
isTouched = 0;
}
} else {
if (packet.FingerState() & SF_FingerTouch) {
changeTouch(0);
isTouched = 1;
}
}
}
}
_endthreadex(0);
return 0;
}
#endif /* STS4MAYU */
#ifdef CTS4MAYU
static void CALLBACK TouchpadFunc(HTOUCHPAD hTP, LPFEEDHDR lpFeedHdr, LPARAM i_lParam)
{
LPRAWFEED lpRawFeed;
static int isTouched = 0;
static WPARAM s_wParam;
static LPARAM s_lParam;
WPARAM wParam;
LPARAM lParam;
lpRawFeed = (LPRAWFEED)(lpFeedHdr + 1);
#if 1
wParam = lpRawFeed->wPressure;
lParam = lpRawFeed->y << 16 | lpRawFeed->x;
if (wParam != s_wParam || lParam != s_lParam) {
postEvent(wParam, lParam);
s_wParam = wParam;
s_lParam = lParam;
}
#else
if (isTouched) {
if (!lpRawFeed->wPressure) {
changeTouch(1);
isTouched = 0;
}
} else {
if (lpRawFeed->wPressure) {
changeTouch(0);
isTouched = 1;
}
}
#endif
EnableWindowsCursor(hTP, TRUE);
}
static BOOL CALLBACK DevicesFunc(LPGENERICDEVICE device, LPARAM lParam)
{
HTOUCHPAD hTP = NULL;
BOOL ret = FALSE;
s_hTP[s_devNum] = GetPad(device->devicePort);
CreateCallback(s_hTP[s_devNum], TouchpadFunc,
TPF_RAW | TPF_POSTMESSAGE, NULL);
StartFeed(s_hTP[s_devNum]);
++s_devNum;
return TRUE;
}
#endif /* CTS4MAYU */
bool WINAPI ts4mayuInit(UINT i_engineThreadId)
{
s_engineThreadId = i_engineThreadId;
#ifdef STS4MAYU
HRESULT result;
long hdl;
s_synAPI = NULL;
s_synDevice = NULL;
s_notifyEvent = NULL;
s_terminated = 0;
result = SynCreateAPI(&s_synAPI);
if (result != SYN_OK) {
goto error_on_init;
}
hdl = -1;
result = s_synAPI->FindDevice(SE_ConnectionAny, SE_DeviceTouchPad, &hdl);
if (result != SYN_OK) {
goto error_on_init;
}
result = s_synAPI->CreateDevice(hdl, &s_synDevice);
if (result != SYN_OK) {
goto error_on_init;
}
s_notifyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (s_notifyEvent == NULL) {
goto error_on_init;
}
s_synAPI->SetEventNotification(s_notifyEvent);
s_synDevice->SetEventNotification(s_notifyEvent);
s_loopThread =
(HANDLE)_beginthreadex(NULL, 0, loop, NULL, 0, &s_loopThreadId);
if (s_loopThread == 0) {
goto error_on_init;
}
return true;
error_on_init:
if (s_notifyEvent) {
CloseHandle(s_notifyEvent);
}
if (s_synDevice) {
s_synDevice->Release();
}
if (s_synAPI) {
s_synAPI->Release();
}
return false;
#endif /* STS4MAYU */
#ifdef CTS4MAYU
// enumerate devices
EnumDevices(DevicesFunc, NULL);
return true;
#endif /* CTS4MAYU */
}
bool WINAPI ts4mayuTerm()
{
#ifdef STS4MAYU
s_terminated = 1;
if (s_loopThread) {
SetEvent(s_notifyEvent);
WaitForSingleObject(s_loopThread, INFINITE);
CloseHandle(s_loopThread);
}
if (s_notifyEvent) {
CloseHandle(s_notifyEvent);
}
if (s_synDevice) {
s_synDevice->Release();
}
if (s_synAPI) {
s_synAPI->Release();
}
return true;
#endif /* STS4MAYU */
#ifdef CTS4MAYU
for (int i = 0; i < s_devNum; i++) {
StopFeed(s_hTP[i]);
}
return false;
#endif /* CTS4MAYU */
}
BOOL WINAPI DllMain(HANDLE module, DWORD reason, LPVOID reserve)
{
s_instance = (HINSTANCE)module;
return TRUE;
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// registry.cpp
#include "registry.h"
#include "stringtool.h"
#include "array.h"
#include <malloc.h>
// remove
bool Registry::remove(HKEY i_root, const tstring &i_path,
const tstring &i_name)
{
if (i_root) {
if (i_name.empty())
return RegDeleteKey(i_root, i_path.c_str()) == ERROR_SUCCESS;
HKEY hkey;
if (ERROR_SUCCESS != RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_SET_VALUE, &hkey))
return false;
LONG r = RegDeleteValue(hkey, i_name.c_str());
RegCloseKey(hkey);
return r == ERROR_SUCCESS;
} else {
return false;
if (i_name.empty())
return false;
return WritePrivateProfileString(_T("yamy"), i_name.c_str(), NULL, i_path.c_str()) == TRUE;
}
}
// does exist the key ?
bool Registry::doesExist(HKEY i_root, const tstring &i_path)
{
if (i_root) {
HKEY hkey;
if (ERROR_SUCCESS != RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey))
return false;
RegCloseKey(hkey);
return true;
} else {
return true;
}
}
// read DWORD
bool Registry::read(HKEY i_root, const tstring &i_path,
const tstring &i_name, int *o_value, int i_defaultValue)
{
if (i_root) {
HKEY hkey;
if (ERROR_SUCCESS == RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) {
DWORD type = REG_DWORD;
DWORD size = sizeof(*o_value);
LONG r = RegQueryValueEx(hkey, i_name.c_str(), NULL, &type, (BYTE *)o_value, &size);
RegCloseKey(hkey);
if (r == ERROR_SUCCESS)
return true;
}
*o_value = i_defaultValue;
return false;
} else {
*o_value = GetPrivateProfileInt(_T("yamy"), i_name.c_str(), i_defaultValue, i_path.c_str());
return true;
}
}
// write DWORD
bool Registry::write(HKEY i_root, const tstring &i_path, const tstring &i_name,
int i_value)
{
if (i_root) {
HKEY hkey;
DWORD disposition;
if (ERROR_SUCCESS !=
RegCreateKeyEx(i_root, i_path.c_str(), 0, _T(""),
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS, NULL, &hkey, &disposition))
return false;
LONG r = RegSetValueEx(hkey, i_name.c_str(), NULL, REG_DWORD,
(BYTE *)&i_value, sizeof(i_value));
RegCloseKey(hkey);
return r == ERROR_SUCCESS;
} else {
DWORD ret;
_TCHAR buf[GANA_MAX_PATH];
_stprintf(buf, _T("%d"), i_value);
ret = WritePrivateProfileString(_T("yamy"), i_name.c_str(),
buf, i_path.c_str());
return ret != 0;
}
}
// read string
bool Registry::read(HKEY i_root, const tstring &i_path, const tstring &i_name,
tstring *o_value, const tstring &i_defaultValue)
{
if (i_root) {
HKEY hkey;
if (ERROR_SUCCESS ==
RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) {
DWORD type = REG_SZ;
DWORD size = 0;
BYTE dummy;
if (ERROR_MORE_DATA ==
RegQueryValueEx(hkey, i_name.c_str(), NULL, &type, &dummy, &size)) {
if (0 < size) {
Array<BYTE> buf(size);
if (ERROR_SUCCESS == RegQueryValueEx(hkey, i_name.c_str(),
NULL, &type, buf.get(), &size)) {
buf.back() = 0;
*o_value = reinterpret_cast<_TCHAR *>(buf.get());
RegCloseKey(hkey);
return true;
}
}
}
RegCloseKey(hkey);
}
if (!i_defaultValue.empty())
*o_value = i_defaultValue;
return false;
} else {
_TCHAR buf[GANA_MAX_PATH];
DWORD len;
len = GetPrivateProfileString(_T("yamy"), i_name.c_str(), _T(""),
buf, sizeof(buf) / sizeof(buf[0]), i_path.c_str());
if (len > 0) {
*o_value = buf;
return true;
}
if (!i_defaultValue.empty())
*o_value = i_defaultValue;
return false;
}
}
// write string
bool Registry::write(HKEY i_root, const tstring &i_path,
const tstring &i_name, const tstring &i_value)
{
if (i_root) {
HKEY hkey;
DWORD disposition;
if (ERROR_SUCCESS !=
RegCreateKeyEx(i_root, i_path.c_str(), 0, _T(""),
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS, NULL, &hkey, &disposition))
return false;
RegSetValueEx(hkey, i_name.c_str(), NULL, REG_SZ,
(BYTE *)i_value.c_str(),
(i_value.size() + 1) * sizeof(tstring::value_type));
RegCloseKey(hkey);
return true;
} else {
DWORD ret;
ret = WritePrivateProfileString(_T("yamy"), i_name.c_str(),
i_value.c_str(), i_path.c_str());
return ret != 0;
}
}
#ifndef USE_INI
// read list of string
bool Registry::read(HKEY i_root, const tstring &i_path, const tstring &i_name,
tstrings *o_value, const tstrings &i_defaultValue)
{
HKEY hkey;
if (ERROR_SUCCESS ==
RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) {
DWORD type = REG_MULTI_SZ;
DWORD size = 0;
BYTE dummy;
if (ERROR_MORE_DATA ==
RegQueryValueEx(hkey, i_name.c_str(), NULL, &type, &dummy, &size)) {
if (0 < size) {
Array<BYTE> buf(size);
if (ERROR_SUCCESS == RegQueryValueEx(hkey, i_name.c_str(),
NULL, &type, buf.get(), &size)) {
buf.back() = 0;
o_value->clear();
const _TCHAR *p = reinterpret_cast<_TCHAR *>(buf.get());
const _TCHAR *end = reinterpret_cast<_TCHAR *>(buf.end());
while (p < end && *p) {
o_value->push_back(p);
p += o_value->back().length() + 1;
}
RegCloseKey(hkey);
return true;
}
}
}
RegCloseKey(hkey);
}
if (!i_defaultValue.empty())
*o_value = i_defaultValue;
return false;
}
// write list of string
bool Registry::write(HKEY i_root, const tstring &i_path,
const tstring &i_name, const tstrings &i_value)
{
HKEY hkey;
DWORD disposition;
if (ERROR_SUCCESS !=
RegCreateKeyEx(i_root, i_path.c_str(), 0, _T(""),
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS, NULL, &hkey, &disposition))
return false;
tstring value;
for (tstrings::const_iterator i = i_value.begin(); i != i_value.end(); ++ i) {
value += *i;
value += _T('\0');
}
RegSetValueEx(hkey, i_name.c_str(), NULL, REG_MULTI_SZ,
(BYTE *)value.c_str(),
(value.size() + 1) * sizeof(tstring::value_type));
RegCloseKey(hkey);
return true;
}
#endif //!USE_INI
// read binary
bool Registry::read(HKEY i_root, const tstring &i_path,
const tstring &i_name, BYTE *o_value, DWORD *i_valueSize,
const BYTE *i_defaultValue, DWORD i_defaultValueSize)
{
if (i_root) {
if (i_valueSize) {
HKEY hkey;
if (ERROR_SUCCESS ==
RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) {
DWORD type = REG_BINARY;
LONG r = RegQueryValueEx(hkey, i_name.c_str(), NULL, &type,
(BYTE *)o_value, i_valueSize);
RegCloseKey(hkey);
if (r == ERROR_SUCCESS)
return true;
}
}
if (i_defaultValue)
CopyMemory(o_value, i_defaultValue,
MIN(i_defaultValueSize, *i_valueSize));
return false;
} else {
return false;
}
}
// write binary
bool Registry::write(HKEY i_root, const tstring &i_path, const tstring &i_name,
const BYTE *i_value, DWORD i_valueSize)
{
if (i_root) {
if (!i_value)
return false;
HKEY hkey;
DWORD disposition;
if (ERROR_SUCCESS !=
RegCreateKeyEx(i_root, i_path.c_str(), 0, _T(""),
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS, NULL, &hkey, &disposition))
return false;
RegSetValueEx(hkey, i_name.c_str(), NULL, REG_BINARY, i_value, i_valueSize);
RegCloseKey(hkey);
return true;
} else {
return false;
}
}
//
static bool string2logfont(LOGFONT *o_lf, const tstring &i_strlf)
{
// -13,0,0,0,400,0,0,0,128,1,2,1,1,Terminal
tregex lf(_T("^(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+),")
_T("(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+),")
_T("(-?\\d+),(-?\\d+),(-?\\d+),(.+)$"));
tsmatch what;
if (!boost::regex_match(i_strlf, what, lf))
return false;
o_lf->lfHeight = _ttoi(what.str(1).c_str());
o_lf->lfWidth = _ttoi(what.str(2).c_str());
o_lf->lfEscapement = _ttoi(what.str(3).c_str());
o_lf->lfOrientation = _ttoi(what.str(4).c_str());
o_lf->lfWeight = _ttoi(what.str(5).c_str());
o_lf->lfItalic = (BYTE)_ttoi(what.str(6).c_str());
o_lf->lfUnderline = (BYTE)_ttoi(what.str(7).c_str());
o_lf->lfStrikeOut = (BYTE)_ttoi(what.str(8).c_str());
o_lf->lfCharSet = (BYTE)_ttoi(what.str(9).c_str());
o_lf->lfOutPrecision = (BYTE)_ttoi(what.str(10).c_str());
o_lf->lfClipPrecision = (BYTE)_ttoi(what.str(11).c_str());
o_lf->lfQuality = (BYTE)_ttoi(what.str(12).c_str());
o_lf->lfPitchAndFamily = (BYTE)_ttoi(what.str(13).c_str());
tcslcpy(o_lf->lfFaceName, what.str(14).c_str(), NUMBER_OF(o_lf->lfFaceName));
return true;
}
// read LOGFONT
bool Registry::read(HKEY i_root, const tstring &i_path, const tstring &i_name,
LOGFONT *o_value, const tstring &i_defaultStringValue)
{
tstring buf;
if (!read(i_root, i_path, i_name, &buf) || !string2logfont(o_value, buf)) {
if (!i_defaultStringValue.empty())
string2logfont(o_value, i_defaultStringValue);
return false;
}
return true;
}
// write LOGFONT
bool Registry::write(HKEY i_root, const tstring &i_path, const tstring &i_name,
const LOGFONT &i_value)
{
_TCHAR buf[1024];
_sntprintf(buf, NUMBER_OF(buf),
_T("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%s"),
i_value.lfHeight, i_value.lfWidth, i_value.lfEscapement,
i_value.lfOrientation, i_value.lfWeight, i_value.lfItalic,
i_value.lfUnderline, i_value.lfStrikeOut, i_value.lfCharSet,
i_value.lfOutPrecision, i_value.lfClipPrecision,
i_value.lfQuality,
i_value.lfPitchAndFamily, i_value.lfFaceName);
return Registry::write(i_root, i_path, i_name, buf);
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// dlginvestigate.cpp
#include "misc.h"
#include "engine.h"
#include "focus.h"
#include "hook.h"
#include "mayurc.h"
#include "stringtool.h"
#include "target.h"
#include "windowstool.h"
#include "vkeytable.h"
#include "dlginvestigate.h"
#include <iomanip>
///
class DlgInvestigate
{
HWND m_hwnd; ///
UINT m_WM_MAYU_MESSAGE; ///
DlgInvestigateData m_data; ///
public:
///
DlgInvestigate(HWND i_hwnd)
: m_hwnd(i_hwnd),
m_WM_MAYU_MESSAGE(RegisterWindowMessage(
addSessionId(WM_MAYU_MESSAGE_NAME).c_str())) {
m_data.m_engine = NULL;
m_data.m_hwndLog = NULL;
}
/// WM_INITDIALOG
BOOL wmInitDialog(HWND /* i_focus */, LPARAM i_lParam) {
m_data = *reinterpret_cast<DlgInvestigateData *>(i_lParam);
setSmallIcon(m_hwnd, IDI_ICON_mayu);
setBigIcon(m_hwnd, IDI_ICON_mayu);
return TRUE;
}
/// WM_DESTROY
BOOL wmDestroy() {
unsetSmallIcon(m_hwnd);
unsetBigIcon(m_hwnd);
return TRUE;
}
/// WM_CLOSE
BOOL wmClose() {
ShowWindow(m_hwnd, SW_HIDE);
return TRUE;
}
/// WM_COMMAND
BOOL wmCommand(int /* i_notifyCode */, int i_id, HWND /* i_hwndControl */) {
switch (i_id) {
case IDOK: {
ShowWindow(m_hwnd, SW_HIDE);
return TRUE;
}
}
return FALSE;
}
/// WM_focusNotify
BOOL wmFocusNotify(bool i_isFocused, HWND i_hwndFocus) {
if (m_data.m_engine &&
i_hwndFocus == GetDlgItem(m_hwnd, IDC_CUSTOM_scancode))
m_data.m_engine->enableLogMode(i_isFocused);
return TRUE;
}
/// WM_targetNotify
BOOL wmTargetNotify(HWND i_hwndTarget) {
_TCHAR className[GANA_MAX_ATOM_LENGTH];
bool ok = false;
if (GetClassName(i_hwndTarget, className, NUMBER_OF(className))) {
if (_tcsicmp(className, _T("ConsoleWindowClass")) == 0) {
_TCHAR titleName[1024];
if (GetWindowText(i_hwndTarget, titleName, NUMBER_OF(titleName)) == 0)
titleName[0] = _T('\0');
{
Acquire a(&m_data.m_engine->m_log, 1);
m_data.m_engine->m_log << _T("HWND:\t") << std::hex
<< reinterpret_cast<int>(i_hwndTarget)
<< std::dec << std::endl;
}
Acquire a(&m_data.m_engine->m_log, 0);
m_data.m_engine->m_log << _T("CLASS:\t") << className << std::endl;
m_data.m_engine->m_log << _T("TITLE:\t") << titleName << std::endl;
ok = true;
}
}
if (!ok)
CHECK_TRUE( PostMessage(i_hwndTarget, m_WM_MAYU_MESSAGE,
MayuMessage_notifyName, 0) );
return TRUE;
}
/// WM_vkeyNotify
BOOL wmVkeyNotify(int i_nVirtKey, int /* i_repeatCount */,
BYTE /* i_scanCode */, bool i_isExtended,
bool /* i_isAltDown */, bool i_isKeyup) {
Acquire a(&m_data.m_engine->m_log, 0);
m_data.m_engine->m_log
<< (i_isExtended ? _T(" E-") : _T(" "))
<< _T("0x") << std::hex << std::setw(2) << std::setfill(_T('0'))
<< i_nVirtKey << std::dec << _T(" &VK( ")
<< (i_isExtended ? _T("E-") : _T(" "))
<< (i_isKeyup ? _T("U-") : _T("D-"));
for (const VKeyTable *vkt = g_vkeyTable; vkt->m_name; ++ vkt) {
if (vkt->m_code == i_nVirtKey) {
m_data.m_engine->m_log << vkt->m_name << _T(" )") << std::endl;
return TRUE;
}
}
m_data.m_engine->m_log << _T("0x") << std::hex << std::setw(2)
<< std::setfill(_T('0')) << i_nVirtKey << std::dec
<< _T(" )") << std::endl;
return TRUE;
}
BOOL wmMove(int /* i_x */, int /* i_y */) {
RECT rc1, rc2;
GetWindowRect(m_hwnd, &rc1);
GetWindowRect(m_data.m_hwndLog, &rc2);
MoveWindow(m_data.m_hwndLog, rc1.left, rc1.bottom,
rcWidth(&rc2), rcHeight(&rc2), TRUE);
return TRUE;
}
};
//
#ifdef MAYU64
INT_PTR CALLBACK dlgInvestigate_dlgProc(HWND i_hwnd, UINT i_message,
#else
BOOL CALLBACK dlgInvestigate_dlgProc(HWND i_hwnd, UINT i_message,
#endif
WPARAM i_wParam, LPARAM i_lParam)
{
DlgInvestigate *wc;
getUserData(i_hwnd, &wc);
if (!wc)
switch (i_message) {
case WM_INITDIALOG:
wc = setUserData(i_hwnd, new DlgInvestigate(i_hwnd));
return wc->wmInitDialog(reinterpret_cast<HWND>(i_wParam), i_lParam);
}
else
switch (i_message) {
case WM_MOVE:
return wc->wmMove(static_cast<short>(LOWORD(i_lParam)),
static_cast<short>(HIWORD(i_lParam)));
case WM_COMMAND:
return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam),
reinterpret_cast<HWND>(i_lParam));
case WM_CLOSE:
return wc->wmClose();
case WM_DESTROY:
return wc->wmDestroy();
case WM_APP_notifyFocus:
return wc->wmFocusNotify(!!i_wParam,
reinterpret_cast<HWND>(i_lParam));
case WM_APP_targetNotify:
return wc->wmTargetNotify(reinterpret_cast<HWND>(i_lParam));
case WM_APP_notifyVKey:
return wc->wmVkeyNotify(
static_cast<int>(i_wParam), static_cast<int>(i_lParam & 0xffff),
static_cast<BYTE>((i_lParam >> 16) & 0xff),
!!(i_lParam & (1 << 24)),
!!(i_lParam & (1 << 29)),
!!(i_lParam & (1 << 31)));
case WM_NCDESTROY:
delete wc;
return TRUE;
}
return FALSE;
}
<file_sep>///////////////////////////////////////////////////////////////////////////////
// setup.cpp
#include "../misc.h"
#include "../registry.h"
#include "../stringtool.h"
#include "../windowstool.h"
#include "../mayu.h"
#include "setuprc.h"
#include "installer.h"
#include <windowsx.h>
#include <shlobj.h>
using namespace Installer;
///////////////////////////////////////////////////////////////////////////////
// Registry
#define DIR_REGISTRY_ROOT \
HKEY_LOCAL_MACHINE, \
_T("Software\\GANAware\\mayu")
///////////////////////////////////////////////////////////////////////////////
// Globals
enum {
Flag_Usb = 1 << 1,
};
u_int32 g_flags = SetupFile::Normal;
using namespace SetupFile;
const SetupFile::Data g_setupFiles[] = {
// same name
#define SN(i_kind, i_os, i_from, i_destination) \
{ i_kind, i_os, Normal|Flag_Usb, _T(i_from), i_destination, _T(i_from) }
// different name
#define DN(i_kind, i_os, i_from, i_destination, i_to) \
{ i_kind, i_os, Normal|Flag_Usb, _T(i_from), i_destination, _T(i_to) }
// executables
SN(Dll , ALL, "mayu.dll" , ToDest),
SN(File, ALL, "mayu.exe" , ToDest),
SN(File, ALL, "setup.exe" , ToDest),
// drivers
#if defined(_WINNT)
SN(File, NT , "mayud.sys" , ToDest),
SN(File, NT , "mayudnt4.sys" , ToDest),
SN(File, W2k, "mayudrsc.sys" , ToDest),
SN(File, W2k, "mayud.sys" , ToDriver),
DN(File, NT4, "mayudnt4.sys" , ToDriver, "mayud.sys"),
SN(File, W2k, "mayudrsc.sys" , ToDriver),
#elif defined(_WIN95)
SN(File, W9x, "mayud.vxd" , ToDest),
#else
# error
#endif
// setting files
SN(File, ALL, "104.mayu" , ToDest),
SN(File, ALL, "104on109.mayu" , ToDest),
SN(File, ALL, "109.mayu" , ToDest),
SN(File, ALL, "109on104.mayu" , ToDest),
SN(File, ALL, "default.mayu" , ToDest),
SN(File, ALL, "dot.mayu" , ToDest),
SN(File, ALL, "emacsedit.mayu" , ToDest),
// documents
SN(Dir , ALL, "doc" , ToDest), // mkdir
DN(File, ALL, "banner-ja.gif" , ToDest, "doc\\banner-ja.gif" ),
DN(File, ALL, "edit-setting-ja.png", ToDest, "doc\\edit-setting-ja.png"),
DN(File, ALL, "investigate-ja.png" , ToDest, "doc\\investigate-ja.png" ),
DN(File, ALL, "log-ja.png" , ToDest, "doc\\log-ja.png" ),
DN(File, ALL, "menu-ja.png" , ToDest, "doc\\menu-ja.png" ),
DN(File, ALL, "pause-ja.png" , ToDest, "doc\\pause-ja.png" ),
DN(File, ALL, "setting-ja.png" , ToDest, "doc\\setting-ja.png" ),
DN(File, ALL, "target.png" , ToDest, "doc\\target.png" ),
DN(File, ALL, "version-ja.png" , ToDest, "doc\\version-ja.png" ),
DN(File, ALL, "CONTENTS-ja.html" , ToDest, "doc\\CONTENTS-ja.html" ),
DN(File, ALL, "CUSTOMIZE-ja.html" , ToDest, "doc\\CUSTOMIZE-ja.html" ),
DN(File, ALL, "MANUAL-ja.html" , ToDest, "doc\\MANUAL-ja.html" ),
DN(File, ALL, "README-ja.html" , ToDest, "doc\\README-ja.html" ),
DN(File, ALL, "README.css" , ToDest, "doc\\README.css" ),
DN(File, ALL, "syntax.txt" , ToDest, "doc\\syntax.txt" ),
SN(File, ALL, "mayu-mode.el" , ToDest),
SN(Dir , ALL, "contrib" , ToDest), // mkdir
DN(File, ALL, "mayu-settings.txt" , ToDest, "contrib\\mayu-settings.txt"),
DN(File, ALL, "dvorak.mayu" , ToDest, "contrib\\dvorak.mayu" ),
DN(File, ALL, "DVORAKon109.mayu" , ToDest, "contrib\\DVORAKon109.mayu" ),
DN(File, ALL, "keitai.mayu" , ToDest, "contrib\\keitai.mayu" ),
DN(File, ALL, "ax.mayu" , ToDest, "contrib\\ax.mayu" ),
DN(File, ALL, "98x1.mayu" , ToDest, "contrib\\98x1.mayu" ),
DN(File, ALL, "109onAX.mayu" , ToDest, "contrib\\109onAX.mayu" ),
SN(Dir , ALL, "Plugins" , ToDest), // mkdir
};
enum KeyboardKind {
KEYBOARD_KIND_109,
KEYBOARD_KIND_104,
} g_keyboardKind;
static const StringResource g_strres[] = {
#include "strres.h"
};
bool g_wasExecutedBySFX = false; // Was setup executed by cab32 SFX ?
Resource *g_resource; // resource information
tstringi g_destDir; // destination directory
///////////////////////////////////////////////////////////////////////////////
// functions
// show message
int message(int i_id, int i_flag, HWND i_hwnd = NULL)
{
return MessageBox(i_hwnd, g_resource->loadString(i_id),
g_resource->loadString(IDS_mayuSetup), i_flag);
}
// driver service error
void driverServiceError(DWORD i_err)
{
switch (i_err) {
case ERROR_ACCESS_DENIED:
message(IDS_notAdministrator, MB_OK | MB_ICONSTOP);
break;
case ERROR_SERVICE_MARKED_FOR_DELETE:
message(IDS_alreadyUninstalled, MB_OK | MB_ICONSTOP);
break;
default: {
TCHAR *errmsg;
int err = int(i_err);
if (err < 0) {
i_err = -err;
}
if (FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, i_err, 0, (LPTSTR)&errmsg, 0, NULL)) {
TCHAR buf[1024];
_sntprintf(buf, NUMBER_OF(buf), _T("%s: %d: %s\n"),
g_resource->loadString(IDS_error),
err, errmsg);
LocalFree(errmsg);
MessageBox(NULL, buf, g_resource->loadString(IDS_mayuSetup),
MB_OK | MB_ICONSTOP);
} else {
message(IDS_error, MB_OK | MB_ICONSTOP);
}
break;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// dialogue
// dialog box
class DlgMain
{
HWND m_hwnd;
bool m_doRegisterToStartMenu; // if register to the start menu
bool m_doRegisterToStartUp; // if register to the start up
private:
// install
int install() {
Registry reg(DIR_REGISTRY_ROOT);
CHECK_TRUE( reg.write(_T("dir"), g_destDir) );
tstringi srcDir = getModuleDirectory();
if (!installFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, srcDir,
g_destDir)) {
removeFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, g_destDir);
if (g_wasExecutedBySFX)
removeSrcFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, srcDir);
return 1;
}
if (g_wasExecutedBySFX)
removeSrcFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, srcDir);
#if defined(_WINNT)
DWORD err =
createDriverService(_T("mayud"),
g_resource->loadString(IDS_mayud),
getDriverDirectory() + _T("\\mayud.sys"),
_T("+Keyboard Class\0"),
g_flags & Flag_Usb ? true : false);
if (err != ERROR_SUCCESS) {
driverServiceError(err);
removeFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, g_destDir);
return 1;
}
if (g_flags == Flag_Usb)
CHECK_TRUE( reg.write(_T("isUsbDriver"), DWORD(1)) );
#endif // _WINNT
// create shortcut
if (m_doRegisterToStartMenu) {
tstringi shortcut = getStartMenuName(loadString(IDS_shortcutName));
if (!shortcut.empty())
createLink((g_destDir + _T("\\mayu.exe")).c_str(), shortcut.c_str(),
g_resource->loadString(IDS_shortcutName),
g_destDir.c_str());
}
if (m_doRegisterToStartUp) {
tstringi shortcut = getStartUpName(loadString(IDS_shortcutName));
if (!shortcut.empty())
createLink((g_destDir + _T("\\mayu.exe")).c_str(), shortcut.c_str(),
g_resource->loadString(IDS_shortcutName),
g_destDir.c_str());
}
// set registry
reg.write(_T("layout"),
(g_keyboardKind == KEYBOARD_KIND_109) ? _T("109") : _T("104"));
// file extension
createFileExtension(_T(".mayu"), _T("text/plain"),
_T("mayu file"), g_resource->loadString(IDS_mayuFile),
g_destDir + _T("\\mayu.exe,1"),
g_resource->loadString(IDS_mayuShellOpen));
// uninstall
createUninstallInformation(_T("mayu"), g_resource->loadString(IDS_mayu),
g_destDir + _T("\\setup.exe -u"));
if (g_flags == Flag_Usb) {
if (message(IDS_copyFinishUsb, MB_YESNO | MB_ICONQUESTION, m_hwnd)
== IDYES) {
// reboot ...
HANDLE hToken;
// Get a token for this process.
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
message(IDS_failedToReboot, MB_OK | MB_ICONSTOP);
return 0;
}
// Get the LUID for the shutdown privilege.
TOKEN_PRIVILEGES tkp;
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1; // one privilege to set
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// Get the shutdown privilege for this process.
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
(PTOKEN_PRIVILEGES)NULL, 0);
// Cannot test the return value of AdjustTokenPrivileges.
if (GetLastError() != ERROR_SUCCESS) {
message(IDS_failedToReboot, MB_OK | MB_ICONSTOP);
return 0;
}
// Shut down the system and force all applications to close.
if (!ExitWindowsEx(EWX_REBOOT | EWX_FORCE, 0)) {
message(IDS_failedToReboot, MB_OK | MB_ICONSTOP);
return 0;
}
}
} else {
if (message(IDS_copyFinish, MB_YESNO | MB_ICONQUESTION, m_hwnd)
== IDYES)
ExitWindows(0, 0); // logoff
}
return 0;
}
private:
// WM_INITDIALOG
BOOL wmInitDialog(HWND /* focus */, LPARAM /* lParam */) {
setSmallIcon(m_hwnd, IDI_ICON_mayu);
setBigIcon(m_hwnd, IDI_ICON_mayu);
Edit_SetText(GetDlgItem(m_hwnd, IDC_EDIT_path), g_destDir.c_str());
HWND hwndCombo = GetDlgItem(m_hwnd, IDC_COMBO_keyboard);
#if 0
if (checkOs(SetupFile::W2k))
#endif
{
ComboBox_AddString(hwndCombo,
g_resource->loadString(IDS_keyboard109usb));
ComboBox_AddString(hwndCombo,
g_resource->loadString(IDS_keyboard104usb));
}
#if 0
ComboBox_AddString(hwndCombo, g_resource->loadString(IDS_keyboard109));
ComboBox_AddString(hwndCombo, g_resource->loadString(IDS_keyboard104));
#endif
ComboBox_SetCurSel(hwndCombo,
(g_keyboardKind == KEYBOARD_KIND_109) ? 0 : 1);
tstring note;
for (int i = IDS_note01; i <= IDS_note13; ++ i) {
note += g_resource->loadString(i);
}
Edit_SetText(GetDlgItem(m_hwnd, IDC_EDIT_note), note.c_str());
return TRUE;
}
// WM_CLOSE
BOOL wmClose() {
EndDialog(m_hwnd, 0);
return TRUE;
}
// WM_COMMAND
BOOL wmCommand(int /* notify_code */, int i_id, HWND /* hwnd_control */) {
switch (i_id) {
case IDC_BUTTON_browse: {
_TCHAR folder[GANA_MAX_PATH];
BROWSEINFO bi;
ZeroMemory(&bi, sizeof(bi));
bi.hwndOwner = m_hwnd;
bi.pidlRoot = NULL;
bi.pszDisplayName = folder;
bi.lpszTitle = g_resource->loadString(IDS_selectDir);
ITEMIDLIST *browse = SHBrowseForFolder(&bi);
if (browse != NULL) {
if (SHGetPathFromIDList(browse, folder)) {
if (createDirectories(folder))
Edit_SetText(GetDlgItem(m_hwnd, IDC_EDIT_path), folder);
}
IMalloc *imalloc = NULL;
if (SHGetMalloc(&imalloc) == NOERROR)
imalloc->Free((void *)browse);
}
return TRUE;
}
case IDOK: {
_TCHAR buf[GANA_MAX_PATH];
Edit_GetText(GetDlgItem(m_hwnd, IDC_EDIT_path), buf, NUMBER_OF(buf));
if (buf[0]) {
g_destDir = normalizePath(buf);
m_doRegisterToStartMenu =
(IsDlgButtonChecked(m_hwnd, IDC_CHECK_registerStartMenu) ==
BST_CHECKED);
m_doRegisterToStartUp =
(IsDlgButtonChecked(m_hwnd, IDC_CHECK_registerStartUp) ==
BST_CHECKED);
int curSel =
ComboBox_GetCurSel(GetDlgItem(m_hwnd, IDC_COMBO_keyboard));
g_flags = SetupFile::Normal;
#if 0
if (checkOs(SetupFile::W2k))
#endif
{
switch (curSel) {
case 0:
g_keyboardKind = KEYBOARD_KIND_109;
g_flags = Flag_Usb;
break;
case 1:
g_keyboardKind = KEYBOARD_KIND_104;
g_flags = Flag_Usb;
break;
#if 0
case 2:
g_keyboardKind = KEYBOARD_KIND_109;
break;
case 3:
g_keyboardKind = KEYBOARD_KIND_104;
break;
#endif
};
}
#if 0
else {
switch (curSel) {
case 0:
g_keyboardKind = KEYBOARD_KIND_109;
break;
case 1:
g_keyboardKind = KEYBOARD_KIND_104;
break;
};
}
#endif
#if 0
if (g_flags == Flag_Usb)
if (message(IDS_usbWarning, MB_OKCANCEL | MB_ICONWARNING, m_hwnd)
== IDCANCEL)
return TRUE;
#endif
if (createDirectories(g_destDir.c_str()))
EndDialog(m_hwnd, install());
else
message(IDS_invalidDirectory, MB_OK | MB_ICONSTOP, m_hwnd);
} else
message(IDS_mayuEmpty, MB_OK, m_hwnd);
return TRUE;
}
case IDCANCEL: {
CHECK_TRUE( EndDialog(m_hwnd, 0) );
return TRUE;
}
}
return FALSE;
}
public:
DlgMain(HWND i_hwnd)
: m_hwnd(i_hwnd),
m_doRegisterToStartMenu(false),
m_doRegisterToStartUp(false) {
}
static BOOL CALLBACK dlgProc(HWND i_hwnd, UINT i_message,
WPARAM i_wParam, LPARAM i_lParam) {
DlgMain *wc;
getUserData(i_hwnd, &wc);
if (!wc)
switch (i_message) {
case WM_INITDIALOG:
wc = setUserData(i_hwnd, new DlgMain(i_hwnd));
return wc->wmInitDialog(reinterpret_cast<HWND>(i_wParam), i_lParam);
}
else
switch (i_message) {
case WM_COMMAND:
return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam),
reinterpret_cast<HWND>(i_lParam));
case WM_CLOSE:
return wc->wmClose();
case WM_NCDESTROY:
delete wc;
return TRUE;
}
return FALSE;
}
};
// uninstall
// (in this function, we cannot use any resource, so we use strres[])
int uninstall()
{
if (IDYES != message(IDS_removeOk, MB_YESNO | MB_ICONQUESTION))
return 1;
#if defined(_WINNT)
DWORD err = removeDriverService(_T("mayud"));
if (err != ERROR_SUCCESS) {
driverServiceError(err);
return 1;
}
#endif // _WINNT
DeleteFile(getStartMenuName(
g_resource->loadString(IDS_shortcutName)).c_str());
DeleteFile(getStartUpName(
g_resource->loadString(IDS_shortcutName)).c_str());
removeFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, g_destDir);
removeFileExtension(_T(".mayu"), _T("mayu file"));
removeUninstallInformation(_T("mayu"));
Registry::remove(DIR_REGISTRY_ROOT);
Registry::remove(HKEY_CURRENT_USER, _T("Software\\GANAware\\mayu"));
message(IDS_removeFinish, MB_OK | MB_ICONINFORMATION);
return 0;
}
int WINAPI _tWinMain(HINSTANCE i_hInstance, HINSTANCE /* hPrevInstance */,
LPTSTR /* lpszCmdLine */, int /* nCmdShow */)
{
CoInitialize(NULL);
g_hInst = i_hInstance;
Resource resource(g_strres);
g_resource = &resource;
// check OS
if (
#if defined(_WINNT)
!checkOs(SetupFile::NT)
#elif defined(_WIN95)
!checkOs(SetupFile::W9x)
#else
# error
#endif
) {
message(IDS_invalidOS, MB_OK | MB_ICONSTOP);
return 1;
}
// keyboard kind
g_keyboardKind =
(resource.getLocale() == LOCALE_Japanese_Japan_932) ?
KEYBOARD_KIND_109 : KEYBOARD_KIND_104;
// read registry
tstringi programFiles; // "Program Files" directory
Registry::read(HKEY_LOCAL_MACHINE,
_T("Software\\Microsoft\\Windows\\CurrentVersion"),
_T("ProgramFilesDir"), &programFiles);
Registry::read(DIR_REGISTRY_ROOT, _T("dir"), &g_destDir,
programFiles + _T("\\mayu"));
int retval = 1;
if (__argc == 2 && _tcsicmp(__targv[1], _T("-u")) == 0)
retval = uninstallStep1(_T("-u"));
else {
HANDLE mutexPrevVer = CreateMutex(
(SECURITY_ATTRIBUTES *)NULL, TRUE,
MUTEX_MAYU_EXCLUSIVE_RUNNING);
if (GetLastError() == ERROR_ALREADY_EXISTS) { // mayu is running
message(IDS_mayuRunning, MB_OK | MB_ICONSTOP);
} else {
// is mayu running ?
HANDLE mutex = CreateMutex(
(SECURITY_ATTRIBUTES *)NULL, TRUE,
addSessionId(MUTEX_MAYU_EXCLUSIVE_RUNNING).c_str());
if (GetLastError() == ERROR_ALREADY_EXISTS) { // mayu is running
message(IDS_mayuRunning, MB_OK | MB_ICONSTOP);
} else if (__argc == 3 && _tcsicmp(__targv[1], _T("-u")) == 0) {
uninstallStep2(__targv[2]);
retval = uninstall();
} else if (__argc == 2 && _tcsicmp(__targv[1], _T("-s")) == 0) {
g_wasExecutedBySFX = true;
retval = DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_main), NULL,
DlgMain::dlgProc);
} else if (__argc == 1) {
retval = DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_main), NULL,
DlgMain::dlgProc);
}
CloseHandle(mutex);
}
CloseHandle(mutexPrevVer);
}
return retval;
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// mayu.cpp
#define APSTUDIO_INVOKED
#include "misc.h"
#include "compiler_specific_func.h"
#include "dlginvestigate.h"
#include "dlglog.h"
#include "dlgsetting.h"
#include "dlgversion.h"
#include "engine.h"
#include "errormessage.h"
#include "focus.h"
#include "function.h"
#include "hook.h"
#include "mayu.h"
#include "mayuipc.h"
#include "mayurc.h"
#include "msgstream.h"
#include "multithread.h"
#include "registry.h"
#include "setting.h"
#include "target.h"
#include "windowstool.h"
#include "fixscancodemap.h"
#include "vk2tchar.h"
#include <process.h>
#include <time.h>
#include <commctrl.h>
#include <wtsapi32.h>
#include <aclapi.h>
///
#define ID_MENUITEM_reloadBegin _APS_NEXT_COMMAND_VALUE
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Mayu
///
class Mayu
{
HWND m_hwndTaskTray; /// tasktray window
HWND m_hwndLog; /// log dialog
HWND m_hwndInvestigate; /// investigate dialog
HWND m_hwndVersion; /// version dialog
UINT m_WM_TaskbarRestart; /** window message sent when
taskber restarts */
UINT m_WM_MayuIPC; /** IPC message sent from
other applications */
NOTIFYICONDATA m_ni; /// taskbar icon data
HICON m_tasktrayIcon[2]; /// taskbar icon
bool m_canUseTasktrayBaloon; ///
tomsgstream m_log; /** log stream (output to log
dialog's edit) */
#ifdef LOG_TO_FILE
tofstream m_logFile;
#endif // LOG_TO_FILE
HMENU m_hMenuTaskTray; /// tasktray menu
#ifdef _WIN64
HANDLE m_hMutexYamyd;
STARTUPINFO m_si;
PROCESS_INFORMATION m_pi;
#endif // _WIN64
HANDLE m_mutex;
HANDLE m_hNotifyMailslot; /// mailslot to receive notify
HANDLE m_hNotifyEvent; /// event on receive notify
OVERLAPPED m_olNotify; ///
BYTE m_notifyBuf[NOTIFY_MESSAGE_SIZE];
static const DWORD SESSION_LOCKED = 1<<0;
static const DWORD SESSION_DISCONNECTED = 1<<1;
static const DWORD SESSION_END_QUERIED = 1<<2;
DWORD m_sessionState;
int m_escapeNlsKeys;
FixScancodeMap m_fixScancodeMap;
Setting *m_setting; /// current setting
bool m_isSettingDialogOpened; /// is setting dialog opened ?
Engine m_engine; /// engine
bool m_usingSN; /// using WTSRegisterSessionNotification() ?
time_t m_startTime; /// mayu started at ...
enum {
WM_APP_taskTrayNotify = WM_APP + 101, ///
WM_APP_msgStreamNotify = WM_APP + 102, ///
WM_APP_escapeNLSKeysFailed = WM_APP + 121, ///
ID_TaskTrayIcon = 1, ///
};
enum {
YAMY_TIMER_ESCAPE_NLS_KEYS = 0, ///
};
private:
static VOID CALLBACK mailslotProc(DWORD i_code, DWORD i_len, LPOVERLAPPED i_ol) {
Mayu *pThis;
if (i_code == ERROR_SUCCESS) {
pThis = reinterpret_cast<Mayu*>(CONTAINING_RECORD(i_ol, Mayu, m_olNotify));
pThis->mailslotHandler(i_code, i_len);
}
return;
}
BOOL mailslotHandler(DWORD i_code, DWORD i_len) {
BOOL result;
if (i_len) {
COPYDATASTRUCT cd;
cd.dwData = reinterpret_cast<Notify *>(m_notifyBuf)->m_type;
cd.cbData = i_len;
cd.lpData = m_notifyBuf;
notifyHandler(&cd);
}
memset(m_notifyBuf, 0, sizeof(m_notifyBuf));
result = ReadFileEx(m_hNotifyMailslot, m_notifyBuf, sizeof(m_notifyBuf),
&m_olNotify, Mayu::mailslotProc);
return result;
}
/// register class for tasktray
ATOM Register_tasktray() {
WNDCLASS wc;
wc.style = 0;
wc.lpfnWndProc = tasktray_wndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = sizeof(Mayu *);
wc.hInstance = g_hInst;
wc.hIcon = NULL;
wc.hCursor = NULL;
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = _T("mayuTasktray");
return RegisterClass(&wc);
}
/// notify handler
BOOL notifyHandler(COPYDATASTRUCT *cd) {
switch (cd->dwData) {
case Notify::Type_setFocus:
case Notify::Type_name: {
NotifySetFocus *n = (NotifySetFocus *)cd->lpData;
n->m_className[NUMBER_OF(n->m_className) - 1] = _T('\0');
n->m_titleName[NUMBER_OF(n->m_titleName) - 1] = _T('\0');
if (n->m_type == Notify::Type_setFocus)
m_engine.setFocus(reinterpret_cast<HWND>(n->m_hwnd), n->m_threadId,
n->m_className, n->m_titleName, false);
{
Acquire a(&m_log, 1);
m_log << _T("HWND:\t") << std::hex
<< n->m_hwnd
<< std::dec << std::endl;
m_log << _T("THREADID:") << static_cast<int>(n->m_threadId)
<< std::endl;
}
Acquire a(&m_log, (n->m_type == Notify::Type_name) ? 0 : 1);
m_log << _T("CLASS:\t") << n->m_className << std::endl;
m_log << _T("TITLE:\t") << n->m_titleName << std::endl;
bool isMDI = true;
HWND hwnd = getToplevelWindow(reinterpret_cast<HWND>(n->m_hwnd), &isMDI);
RECT rc;
if (isMDI) {
getChildWindowRect(hwnd, &rc);
m_log << _T("MDI Window Position/Size: (")
<< rc.left << _T(", ") << rc.top << _T(") / (")
<< rcWidth(&rc) << _T("x") << rcHeight(&rc) << _T(")")
<< std::endl;
hwnd = getToplevelWindow(reinterpret_cast<HWND>(n->m_hwnd), NULL);
}
GetWindowRect(hwnd, &rc);
m_log << _T("Toplevel Window Position/Size: (")
<< rc.left << _T(", ") << rc.top << _T(") / (")
<< rcWidth(&rc) << _T("x") << rcHeight(&rc) << _T(")")
<< std::endl;
SystemParametersInfo(SPI_GETWORKAREA, 0, (void *)&rc, FALSE);
m_log << _T("Desktop Window Position/Size: (")
<< rc.left << _T(", ") << rc.top << _T(") / (")
<< rcWidth(&rc) << _T("x") << rcHeight(&rc) << _T(")")
<< std::endl;
m_log << std::endl;
break;
}
case Notify::Type_lockState: {
NotifyLockState *n = (NotifyLockState *)cd->lpData;
m_engine.setLockState(n->m_isNumLockToggled,
n->m_isCapsLockToggled,
n->m_isScrollLockToggled,
n->m_isKanaLockToggled,
n->m_isImeLockToggled,
n->m_isImeCompToggled);
#if 0
Acquire a(&m_log, 0);
if (n->m_isKanaLockToggled) {
m_log << _T("Notify::Type_lockState Kana on : ");
} else {
m_log << _T("Notify::Type_lockState Kana off : ");
}
m_log << n->m_debugParam << ", "
<< g_hookData->m_correctKanaLockHandling << std::endl;
#endif
break;
}
case Notify::Type_sync: {
m_engine.syncNotify();
break;
}
case Notify::Type_threadAttach: {
NotifyThreadAttach *n = (NotifyThreadAttach *)cd->lpData;
m_engine.threadAttachNotify(n->m_threadId);
break;
}
case Notify::Type_threadDetach: {
NotifyThreadDetach *n = (NotifyThreadDetach *)cd->lpData;
m_engine.threadDetachNotify(n->m_threadId);
break;
}
case Notify::Type_command64: {
NotifyCommand64 *n = (NotifyCommand64 *)cd->lpData;
m_engine.commandNotify(n->m_hwnd, n->m_message,
n->m_wParam, n->m_lParam);
break;
}
case Notify::Type_command32: {
NotifyCommand32 *n = (NotifyCommand32 *)cd->lpData;
m_engine.commandNotify(n->m_hwnd, n->m_message,
n->m_wParam, n->m_lParam);
break;
}
case Notify::Type_show: {
NotifyShow *n = (NotifyShow *)cd->lpData;
switch (n->m_show) {
case NotifyShow::Show_Maximized:
m_engine.setShow(true, false, n->m_isMDI);
break;
case NotifyShow::Show_Minimized:
m_engine.setShow(false, true, n->m_isMDI);
break;
case NotifyShow::Show_Normal:
default:
m_engine.setShow(false, false, n->m_isMDI);
break;
}
break;
}
case Notify::Type_log: {
Acquire a(&m_log, 1);
NotifyLog *n = (NotifyLog *)cd->lpData;
m_log << _T("hook log: ") << n->m_msg << std::endl;
break;
}
}
return true;
}
/// window procedure for tasktray
static LRESULT CALLBACK
tasktray_wndProc(HWND i_hwnd, UINT i_message,
WPARAM i_wParam, LPARAM i_lParam) {
#ifdef MAYU64
Mayu *This = reinterpret_cast<Mayu *>(GetWindowLongPtr(i_hwnd, 0));
#else
Mayu *This = reinterpret_cast<Mayu *>(GetWindowLong(i_hwnd, 0));
#endif
if (!This)
switch (i_message) {
case WM_CREATE:
This = reinterpret_cast<Mayu *>(
reinterpret_cast<CREATESTRUCT *>(i_lParam)->lpCreateParams);
This->m_fixScancodeMap.init(i_hwnd, WM_APP_escapeNLSKeysFailed);
if (This->m_escapeNlsKeys) {
This->m_fixScancodeMap.escape(true);
}
#ifdef MAYU64
SetWindowLongPtr(i_hwnd, 0, (LONG_PTR)This);
#else
SetWindowLong(i_hwnd, 0, (long)This);
#endif
return 0;
}
else
switch (i_message) {
case WM_COPYDATA: {
COPYDATASTRUCT *cd;
cd = reinterpret_cast<COPYDATASTRUCT *>(i_lParam);
return This->notifyHandler(cd);
}
case WM_QUERYENDSESSION:
if (!This->m_sessionState) {
if (This->m_escapeNlsKeys && This->m_engine.getIsEnabled()) {
This->m_fixScancodeMap.escape(false);
}
}
This->m_sessionState |= Mayu::SESSION_END_QUERIED;
This->m_engine.prepairQuit();
PostQuitMessage(0);
return TRUE;
#ifndef WM_WTSSESSION_CHANGE // WinUser.h
# define WM_WTSSESSION_CHANGE 0x02B1
#endif
case WM_WTSSESSION_CHANGE: {
const char *m = "";
switch (i_wParam) {
#ifndef WTS_CONSOLE_CONNECT // WinUser.h
# define WTS_CONSOLE_CONNECT 0x1
# define WTS_CONSOLE_DISCONNECT 0x2
# define WTS_REMOTE_CONNECT 0x3
# define WTS_REMOTE_DISCONNECT 0x4
# define WTS_SESSION_LOGON 0x5
# define WTS_SESSION_LOGOFF 0x6
# define WTS_SESSION_LOCK 0x7
# define WTS_SESSION_UNLOCK 0x8
#endif
/*
restore NLS keys when any bits of m_sessionState is on
and
escape NLS keys when all bits of m_sessionState cleared
*/
case WTS_CONSOLE_CONNECT:
This->m_sessionState &= ~Mayu::SESSION_DISCONNECTED;
if (!This->m_sessionState) {
if (This->m_escapeNlsKeys && This->m_engine.getIsEnabled()) {
This->m_fixScancodeMap.escape(true);
}
}
m = "WTS_CONSOLE_CONNECT";
break;
case WTS_CONSOLE_DISCONNECT:
if (!This->m_sessionState) {
if (This->m_escapeNlsKeys && This->m_engine.getIsEnabled()) {
This->m_fixScancodeMap.escape(false);
}
}
This->m_sessionState |= Mayu::SESSION_DISCONNECTED;
m = "WTS_CONSOLE_DISCONNECT";
break;
case WTS_REMOTE_CONNECT:
This->m_sessionState &= ~Mayu::SESSION_DISCONNECTED;
if (!This->m_sessionState) {
if (This->m_escapeNlsKeys && This->m_engine.getIsEnabled()) {
This->m_fixScancodeMap.escape(true);
}
}
m = "WTS_REMOTE_CONNECT";
break;
case WTS_REMOTE_DISCONNECT:
if (!This->m_sessionState) {
if (This->m_escapeNlsKeys && This->m_engine.getIsEnabled()) {
This->m_fixScancodeMap.escape(false);
}
}
This->m_sessionState |= Mayu::SESSION_DISCONNECTED;
m = "WTS_REMOTE_DISCONNECT";
break;
case WTS_SESSION_LOGON:
m = "WTS_SESSION_LOGON";
break;
case WTS_SESSION_LOGOFF:
m = "WTS_SESSION_LOGOFF";
break;
case WTS_SESSION_LOCK: {
if (!This->m_sessionState) {
if (This->m_escapeNlsKeys && This->m_engine.getIsEnabled()) {
This->m_fixScancodeMap.escape(false);
}
}
This->m_sessionState |= Mayu::SESSION_LOCKED;
m = "WTS_SESSION_LOCK";
break;
}
case WTS_SESSION_UNLOCK: {
This->m_sessionState &= ~Mayu::SESSION_LOCKED;
if (!This->m_sessionState) {
if (This->m_escapeNlsKeys && This->m_engine.getIsEnabled()) {
This->m_fixScancodeMap.escape(true);
}
}
m = "WTS_SESSION_UNLOCK";
break;
}
//case WTS_SESSION_REMOTE_CONTROL: m = "WTS_SESSION_REMOTE_CONTROL"; break;
}
This->m_log << _T("WM_WTSESSION_CHANGE(")
<< i_wParam << ", " << i_lParam << "): "
<< m << std::endl;
return TRUE;
}
case WM_APP_msgStreamNotify: {
tomsgstream::StreamBuf *log =
reinterpret_cast<tomsgstream::StreamBuf *>(i_lParam);
const tstring &str = log->acquireString();
#ifdef LOG_TO_FILE
This->m_logFile << str << std::flush;
#endif // LOG_TO_FILE
editInsertTextAtLast(GetDlgItem(This->m_hwndLog, IDC_EDIT_log),
str, 65000);
log->releaseString();
return 0;
}
case WM_APP_taskTrayNotify: {
if (i_wParam == ID_TaskTrayIcon)
switch (i_lParam) {
case WM_RBUTTONUP: {
POINT p;
CHECK_TRUE( GetCursorPos(&p) );
SetForegroundWindow(i_hwnd);
HMENU hMenuSub = GetSubMenu(This->m_hMenuTaskTray, 0);
if (This->m_engine.getIsEnabled())
CheckMenuItem(hMenuSub, ID_MENUITEM_disable,
MF_UNCHECKED | MF_BYCOMMAND);
else
CheckMenuItem(hMenuSub, ID_MENUITEM_disable,
MF_CHECKED | MF_BYCOMMAND);
CHECK_TRUE( SetMenuDefaultItem(hMenuSub,
ID_MENUITEM_investigate, FALSE) );
// create reload menu
HMENU hMenuSubSub = GetSubMenu(hMenuSub, 1);
Registry reg(MAYU_REGISTRY_ROOT);
int mayuIndex;
reg.read(_T(".mayuIndex"), &mayuIndex, 0);
while (DeleteMenu(hMenuSubSub, 0, MF_BYPOSITION))
;
tregex getName(_T("^([^;]*);"));
for (int index = 0; ; index ++) {
_TCHAR buf[100];
_sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index);
tstringi dot_mayu;
if (!reg.read(buf, &dot_mayu))
break;
tsmatch what;
if (boost::regex_search(dot_mayu, what, getName)) {
MENUITEMINFO mii;
std::memset(&mii, 0, sizeof(mii));
mii.cbSize = sizeof(mii);
mii.fMask = MIIM_ID | MIIM_STATE | MIIM_TYPE;
mii.fType = MFT_STRING;
mii.fState =
MFS_ENABLED | ((mayuIndex == index) ? MFS_CHECKED : 0);
mii.wID = ID_MENUITEM_reloadBegin + index;
tstringi name(what.str(1));
mii.dwTypeData = const_cast<_TCHAR *>(name.c_str());
mii.cch = name.size();
InsertMenuItem(hMenuSubSub, index, TRUE, &mii);
}
}
// show popup menu
TrackPopupMenu(hMenuSub, TPM_LEFTALIGN,
p.x, p.y, 0, i_hwnd, NULL);
// TrackPopupMenu may fail (ERROR_POPUP_ALREADY_ACTIVE)
break;
}
case WM_LBUTTONDBLCLK:
SendMessage(i_hwnd, WM_COMMAND,
MAKELONG(ID_MENUITEM_investigate, 0), 0);
break;
}
return 0;
}
case WM_APP_escapeNLSKeysFailed:
if (i_lParam) {
int ret;
This->m_log << _T("escape NLS keys done code=") << i_wParam << std::endl;
switch (i_wParam) {
case YAMY_SUCCESS:
case YAMY_ERROR_RETRY_INJECTION_SUCCESS:
// escape NLS keys success
break;
case YAMY_ERROR_TIMEOUT_INJECTION:
ret = This->errorDialogWithCode(IDS_escapeNlsKeysRetry, i_wParam, MB_RETRYCANCEL | MB_ICONSTOP);
if (ret == IDRETRY) {
This->m_fixScancodeMap.escape(true);
}
break;
default:
This->errorDialogWithCode(IDS_escapeNlsKeysFailed, i_wParam, MB_OK);
break;
}
} else {
This->m_log << _T("restore NLS keys done with code=") << i_wParam << std::endl;
}
return 0;
break;
case WM_COMMAND: {
int notify_code = HIWORD(i_wParam);
int id = LOWORD(i_wParam);
if (notify_code == 0) // menu
switch (id) {
default:
if (ID_MENUITEM_reloadBegin <= id) {
Registry reg(MAYU_REGISTRY_ROOT);
reg.write(_T(".mayuIndex"), id - ID_MENUITEM_reloadBegin);
This->load();
}
break;
case ID_MENUITEM_reload:
This->load();
break;
case ID_MENUITEM_investigate: {
ShowWindow(This->m_hwndLog, SW_SHOW);
ShowWindow(This->m_hwndInvestigate, SW_SHOW);
RECT rc1, rc2;
GetWindowRect(This->m_hwndInvestigate, &rc1);
GetWindowRect(This->m_hwndLog, &rc2);
MoveWindow(This->m_hwndLog, rc1.left, rc1.bottom,
rcWidth(&rc1), rcHeight(&rc2), TRUE);
SetForegroundWindow(This->m_hwndLog);
SetForegroundWindow(This->m_hwndInvestigate);
break;
}
case ID_MENUITEM_setting:
if (!This->m_isSettingDialogOpened) {
This->m_isSettingDialogOpened = true;
if (DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_setting),
NULL, dlgSetting_dlgProc))
This->load();
This->m_isSettingDialogOpened = false;
}
break;
case ID_MENUITEM_log:
ShowWindow(This->m_hwndLog, SW_SHOW);
SetForegroundWindow(This->m_hwndLog);
break;
case ID_MENUITEM_check: {
BOOL ret;
BYTE keys[256];
ret = GetKeyboardState(keys);
if (ret == 0) {
This->m_log << _T("Check Keystate Failed(%d)")
<< GetLastError() << std::endl;
} else {
This->m_log << _T("Check Keystate: ") << std::endl;
for (int i = 0; i < 0xff; i++) {
USHORT asyncKey;
asyncKey = GetAsyncKeyState(i);
This->m_log << std::hex;
if (asyncKey & 0x8000) {
This->m_log << _T(" ") << VK2TCHAR[i]
<< _T("(0x") << i << _T("): pressed!")
<< std::endl;
}
if (i == 0x14 || // VK_CAPTITAL
i == 0x15 || // VK_KANA
i == 0x19 || // VK_KANJI
i == 0x90 || // VK_NUMLOCK
i == 0x91 // VK_SCROLL
) {
if (keys[i] & 1) {
This->m_log << _T(" ") << VK2TCHAR[i]
<< _T("(0x") << i << _T("): locked!")
<< std::endl;
}
}
This->m_log << std::dec;
}
This->m_log << std::endl;
}
break;
}
case ID_MENUITEM_version:
ShowWindow(This->m_hwndVersion, SW_SHOW);
SetForegroundWindow(This->m_hwndVersion);
break;
case ID_MENUITEM_help: {
_TCHAR buf[GANA_MAX_PATH];
CHECK_TRUE( GetModuleFileName(g_hInst, buf, NUMBER_OF(buf)) );
tstringi helpFilename = pathRemoveFileSpec(buf);
helpFilename += _T("\\");
helpFilename += loadString(IDS_helpFilename);
ShellExecute(NULL, _T("open"), helpFilename.c_str(),
NULL, NULL, SW_SHOWNORMAL);
break;
}
case ID_MENUITEM_disable:
This->m_engine.enable(!This->m_engine.getIsEnabled());
if (This->m_engine.getIsEnabled()) {
This->m_fixScancodeMap.escape(true);
} else {
This->m_fixScancodeMap.escape(false);
}
This->showTasktrayIcon();
break;
case ID_MENUITEM_quit:
This->m_engine.prepairQuit();
PostQuitMessage(0);
break;
}
return 0;
}
case WM_APP_engineNotify: {
switch (i_wParam) {
case EngineNotify_shellExecute:
This->m_engine.shellExecute();
break;
case EngineNotify_loadSetting:
This->load();
break;
case EngineNotify_helpMessage:
This->showHelpMessage(false);
if (i_lParam)
This->showHelpMessage(true);
break;
case EngineNotify_showDlg: {
// show investigate/log window
int sw = (i_lParam & ~MayuDialogType_mask);
HWND hwnd = NULL;
switch (static_cast<MayuDialogType>(
i_lParam & MayuDialogType_mask)) {
case MayuDialogType_investigate:
hwnd = This->m_hwndInvestigate;
break;
case MayuDialogType_log:
hwnd = This->m_hwndLog;
break;
}
if (hwnd) {
ShowWindow(hwnd, sw);
switch (sw) {
case SW_SHOWNORMAL:
case SW_SHOWMAXIMIZED:
case SW_SHOW:
case SW_RESTORE:
case SW_SHOWDEFAULT:
SetForegroundWindow(hwnd);
break;
}
}
break;
}
case EngineNotify_setForegroundWindow:
// FIXME: completely useless. why ?
setForegroundWindow(reinterpret_cast<HWND>(i_lParam));
{
Acquire a(&This->m_log, 1);
This->m_log << _T("setForegroundWindow(0x")
<< std::hex << i_lParam << std::dec << _T(")")
<< std::endl;
}
break;
case EngineNotify_clearLog:
SendMessage(This->m_hwndLog, WM_COMMAND,
MAKELONG(IDC_BUTTON_clearLog, 0), 0);
break;
default:
break;
}
return 0;
}
case WM_APP_dlglogNotify: {
switch (i_wParam) {
case DlgLogNotify_logCleared:
This->showBanner(true);
break;
default:
break;
}
return 0;
}
case WM_DESTROY:
if (This->m_usingSN) {
wtsUnRegisterSessionNotification(i_hwnd);
This->m_usingSN = false;
}
if (!This->m_sessionState) {
if (This->m_escapeNlsKeys && This->m_engine.getIsEnabled()) {
This->m_fixScancodeMap.escape(false);
}
}
return 0;
default:
if (i_message == This->m_WM_TaskbarRestart) {
if (This->showTasktrayIcon(true)) {
Acquire a(&This->m_log, 0);
This->m_log << _T("Tasktray icon is updated.") << std::endl;
} else {
Acquire a(&This->m_log, 1);
This->m_log << _T("Tasktray icon already exists.") << std::endl;
}
return 0;
} else if (i_message == This->m_WM_MayuIPC) {
switch (static_cast<MayuIPCCommand>(i_wParam)) {
case MayuIPCCommand_Enable:
This->m_engine.enable(!!i_lParam);
if (This->m_engine.getIsEnabled()) {
This->m_fixScancodeMap.escape(true);
} else {
This->m_fixScancodeMap.escape(false);
}
This->showTasktrayIcon();
if (i_lParam) {
Acquire a(&This->m_log, 1);
This->m_log << _T("Enabled by another application.")
<< std::endl;
} else {
Acquire a(&This->m_log, 1);
This->m_log << _T("Disabled by another application.")
<< std::endl;
}
break;
}
}
}
return DefWindowProc(i_hwnd, i_message, i_wParam, i_lParam);
}
/// load setting
void load() {
Setting *newSetting = new Setting;
// set symbol
for (int i = 1; i < __argc; ++ i) {
if (__targv[i][0] == _T('-') && __targv[i][1] == _T('D'))
newSetting->m_symbols.insert(__targv[i] + 2);
}
if (!SettingLoader(&m_log, &m_log).load(newSetting)) {
ShowWindow(m_hwndLog, SW_SHOW);
SetForegroundWindow(m_hwndLog);
delete newSetting;
Acquire a(&m_log, 0);
m_log << _T("error: failed to load.") << std::endl;
return;
}
m_log << _T("successfully loaded.") << std::endl;
while (!m_engine.setSetting(newSetting))
Sleep(1000);
delete m_setting;
m_setting = newSetting;
}
// show message (a baloon from the task tray icon)
void showHelpMessage(bool i_doesShow = true) {
if (m_canUseTasktrayBaloon) {
if (i_doesShow) {
tstring helpMessage, helpTitle;
m_engine.getHelpMessages(&helpMessage, &helpTitle);
tcslcpy(m_ni.szInfo, helpMessage.c_str(), NUMBER_OF(m_ni.szInfo));
tcslcpy(m_ni.szInfoTitle, helpTitle.c_str(),
NUMBER_OF(m_ni.szInfoTitle));
m_ni.dwInfoFlags = NIIF_INFO;
} else
m_ni.szInfo[0] = m_ni.szInfoTitle[0] = _T('\0');
CHECK_TRUE( Shell_NotifyIcon(NIM_MODIFY, &m_ni) );
}
}
// change the task tray icon
bool showTasktrayIcon(bool i_doesAdd = false) {
m_ni.hIcon = m_tasktrayIcon[m_engine.getIsEnabled() ? 1 : 0];
m_ni.szInfo[0] = m_ni.szInfoTitle[0] = _T('\0');
if (i_doesAdd) {
// http://support.microsoft.com/kb/418138/JA/
int guard = 60;
for (; !Shell_NotifyIcon(NIM_ADD, &m_ni) && 0 < guard; -- guard) {
if (Shell_NotifyIcon(NIM_MODIFY, &m_ni)) {
return true;
}
Sleep(1000); // 1sec
}
return 0 < guard;
} else {
return !!Shell_NotifyIcon(NIM_MODIFY, &m_ni);
}
}
void showBanner(bool i_isCleared) {
time_t now;
time(&now);
_TCHAR starttimebuf[1024];
_TCHAR timebuf[1024];
#ifdef __BORLANDC__
#pragma message("\t\t****\tAfter std::ostream() is called, ")
#pragma message("\t\t****\tstrftime(... \"%%#c\" ...) fails.")
#pragma message("\t\t****\tWhy ? Bug of Borland C++ 5.5.1 ? ")
#pragma message("\t\t****\t - nayuta")
_tcsftime(timebuf, NUMBER_OF(timebuf), _T("%Y/%m/%d %H:%M:%S"),
localtime(&now));
_tcsftime(starttimebuf, NUMBER_OF(starttimebuf), _T("%Y/%m/%d %H:%M:%S"),
localtime(&m_startTime));
#else
_tcsftime(timebuf, NUMBER_OF(timebuf), _T("%#c"), localtime(&now));
_tcsftime(starttimebuf, NUMBER_OF(starttimebuf), _T("%#c"),
localtime(&m_startTime));
#endif
Acquire a(&m_log, 0);
m_log << _T("------------------------------------------------------------") << std::endl;
m_log << loadString(IDS_mayu) << _T(" ") _T(VERSION);
#ifndef NDEBUG
m_log << _T(" (DEBUG)");
#endif
#ifdef _UNICODE
m_log << _T(" (UNICODE)");
#endif
m_log << std::endl;
m_log << _T(" built by ")
<< _T(LOGNAME) << _T("@") << toLower(_T(COMPUTERNAME))
<< _T(" (") << _T(__DATE__) << _T(" ")
<< _T(__TIME__) << _T(", ")
<< getCompilerVersionString() << _T(")") << std::endl;
_TCHAR modulebuf[1024];
CHECK_TRUE( GetModuleFileName(g_hInst, modulebuf,
NUMBER_OF(modulebuf)) );
m_log << _T("started at ") << starttimebuf << std::endl;
m_log << modulebuf << std::endl;
m_log << _T("------------------------------------------------------------") << std::endl;
if (i_isCleared) {
m_log << _T("log was cleared at ") << timebuf << std::endl;
} else {
m_log << _T("log begins at ") << timebuf << std::endl;
}
}
int errorDialogWithCode(UINT ids, int code, UINT style = MB_OK | MB_ICONSTOP)
{
_TCHAR title[1024];
_TCHAR text[1024];
_sntprintf_s(title, NUMBER_OF(title), _TRUNCATE, loadString(IDS_mayu).c_str());
_sntprintf_s(text, NUMBER_OF(text), _TRUNCATE, loadString(ids).c_str(), code);
return MessageBox((HWND)NULL, text, title, style);
}
int enableToWriteByUser(HANDLE hdl)
{
TCHAR userName[GANA_MAX_ATOM_LENGTH];
DWORD userNameSize = NUMBER_OF(userName);
SID_NAME_USE sidType;
PSID pSid = NULL;
DWORD sidSize = 0;
TCHAR *pDomain = NULL;
DWORD domainSize = 0;
PSECURITY_DESCRIPTOR pSd;
PACL pOrigDacl;
ACL_SIZE_INFORMATION aclInfo;
PACL pNewDacl;
DWORD newDaclSize;
DWORD aceIndex;
DWORD newAceIndex = 0;
BOOL ret;
int err = 0;
ret = GetUserName(userName, &userNameSize);
if (ret == FALSE) {
err = YAMY_ERROR_ON_GET_USERNAME;
goto exit;
}
// get buffer size for pSid (and pDomain)
ret = LookupAccountName(NULL, userName, pSid, &sidSize, pDomain, &domainSize, &sidType);
if (ret != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
// above call should fail by ERROR_INSUFFICIENT_BUFFER
err = YAMY_ERROR_ON_GET_LOGONUSERNAME;
goto exit;
}
pSid = reinterpret_cast<PSID>(LocalAlloc(LPTR, sidSize));
pDomain = reinterpret_cast<TCHAR*>(LocalAlloc(LPTR, domainSize * sizeof(TCHAR)));
if (pSid == NULL || pDomain == NULL) {
err = YAMY_ERROR_NO_MEMORY;
goto exit;
}
// get SID (and Domain) for logoned user
ret = LookupAccountName(NULL, userName, pSid, &sidSize, pDomain, &domainSize, &sidType);
if (ret == FALSE) {
// LookupAccountName() should success in this time
err = YAMY_ERROR_ON_GET_LOGONUSERNAME;
goto exit;
}
// get DACL for hdl
ret = GetSecurityInfo(hdl, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pOrigDacl, NULL, &pSd);
if (ret != ERROR_SUCCESS) {
err = YAMY_ERROR_ON_GET_SECURITYINFO;
goto exit;
}
// get size for original DACL
ret = GetAclInformation(pOrigDacl, &aclInfo, sizeof(aclInfo), AclSizeInformation);
if (ret == FALSE) {
err = YAMY_ERROR_ON_GET_DACL;
goto exit;
}
// compute size for new DACL
newDaclSize = aclInfo.AclBytesInUse + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(pSid) - sizeof(DWORD);
// allocate memory for new DACL
pNewDacl = reinterpret_cast<PACL>(LocalAlloc(LPTR, newDaclSize));
if (pNewDacl == NULL) {
err = YAMY_ERROR_NO_MEMORY;
goto exit;
}
// initialize new DACL
ret = InitializeAcl(pNewDacl, newDaclSize, ACL_REVISION);
if (ret == FALSE) {
err = YAMY_ERROR_ON_INITIALIZE_ACL;
goto exit;
}
// copy original DACL to new DACL
for (aceIndex = 0; aceIndex < aclInfo.AceCount; aceIndex++) {
LPVOID pAce;
ret = GetAce(pOrigDacl, aceIndex, &pAce);
if (ret == FALSE) {
err = YAMY_ERROR_ON_GET_ACE;
goto exit;
}
if ((reinterpret_cast<ACCESS_ALLOWED_ACE*>(pAce))->Header.AceFlags & INHERITED_ACE) {
break;
}
if (EqualSid(pSid, &(reinterpret_cast<ACCESS_ALLOWED_ACE*>(pAce))->SidStart) != FALSE) {
continue;
}
ret = AddAce(pNewDacl, ACL_REVISION, MAXDWORD, pAce, (reinterpret_cast<PACE_HEADER>(pAce))->AceSize);
if (ret == FALSE) {
err = YAMY_ERROR_ON_ADD_ACE;
goto exit;
}
newAceIndex++;
}
ret = AddAccessAllowedAce(pNewDacl, ACL_REVISION, GENERIC_ALL, pSid);
if (ret == FALSE) {
err = YAMY_ERROR_ON_ADD_ALLOWED_ACE;
goto exit;
}
// copy the rest of inherited ACEs
for (; aceIndex < aclInfo.AceCount; aceIndex++) {
LPVOID pAce;
ret = GetAce(pOrigDacl, aceIndex, &pAce);
if (ret == FALSE) {
err = YAMY_ERROR_ON_GET_ACE;
goto exit;
}
ret = AddAce(pNewDacl, ACL_REVISION, MAXDWORD, pAce, (reinterpret_cast<PACE_HEADER>(pAce))->AceSize);
if (ret == FALSE) {
err = YAMY_ERROR_ON_ADD_ACE;
goto exit;
}
}
ret = SetSecurityInfo(hdl, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, pNewDacl, NULL);
if (ret != ERROR_SUCCESS) {
err = YAMY_ERROR_ON_SET_SECURITYINFO;
}
exit:
LocalFree(pSd);
LocalFree(pSid);
LocalFree(pDomain);
LocalFree(pNewDacl);
return err;
}
public:
///
Mayu(HANDLE i_mutex)
: m_hwndTaskTray(NULL),
m_mutex(i_mutex),
m_hwndLog(NULL),
m_WM_TaskbarRestart(RegisterWindowMessage(_T("TaskbarCreated"))),
m_WM_MayuIPC(RegisterWindowMessage(WM_MayuIPC_NAME)),
m_canUseTasktrayBaloon(
PACKVERSION(5, 0) <= getDllVersion(_T("shlwapi.dll"))),
m_log(WM_APP_msgStreamNotify),
m_setting(NULL),
m_isSettingDialogOpened(false),
m_sessionState(0),
m_engine(m_log) {
Registry reg(MAYU_REGISTRY_ROOT);
reg.read(_T("escapeNLSKeys"), &m_escapeNlsKeys, 0);
m_hNotifyMailslot = CreateMailslot(NOTIFY_MAILSLOT_NAME, 0, MAILSLOT_WAIT_FOREVER, (SECURITY_ATTRIBUTES *)NULL);
ASSERT(m_hNotifyMailslot != INVALID_HANDLE_VALUE);
int err;
if (checkWindowsVersion(6, 0) != FALSE) { // enableToWriteByUser() is available only Vista or later
err = enableToWriteByUser(m_hNotifyMailslot);
if (err) {
errorDialogWithCode(IDS_cannotPermitStandardUser, err);
}
}
m_hNotifyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
ASSERT(m_hNotifyEvent);
m_olNotify.Offset = 0;
m_olNotify.OffsetHigh = 0;
m_olNotify.hEvent = m_hNotifyEvent;
time(&m_startTime);
CHECK_TRUE( Register_focus() );
CHECK_TRUE( Register_target() );
CHECK_TRUE( Register_tasktray() );
// change dir
#if 0
HomeDirectories pathes;
getHomeDirectories(&pathes);
for (HomeDirectories::iterator i = pathes.begin(); i != pathes.end(); ++ i)
if (SetCurrentDirectory(i->c_str()))
break;
#endif
// create windows, dialogs
tstringi title = loadString(IDS_mayu);
m_hwndTaskTray = CreateWindow(_T("mayuTasktray"), title.c_str(),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, g_hInst, this);
CHECK_TRUE( m_hwndTaskTray );
// set window handle of tasktray to hooks
CHECK_FALSE( installMessageHook(reinterpret_cast<DWORD>(m_hwndTaskTray)) );
m_usingSN = wtsRegisterSessionNotification(m_hwndTaskTray,
NOTIFY_FOR_THIS_SESSION);
DlgLogData dld;
dld.m_log = &m_log;
dld.m_hwndTaskTray = m_hwndTaskTray;
m_hwndLog =
CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_log), NULL,
dlgLog_dlgProc, (LPARAM)&dld);
CHECK_TRUE( m_hwndLog );
DlgInvestigateData did;
did.m_engine = &m_engine;
did.m_hwndLog = m_hwndLog;
m_hwndInvestigate =
CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_investigate), NULL,
dlgInvestigate_dlgProc, (LPARAM)&did);
CHECK_TRUE( m_hwndInvestigate );
m_hwndVersion =
CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_version),
NULL, dlgVersion_dlgProc,
(LPARAM)_T(""));
CHECK_TRUE( m_hwndVersion );
// attach log
#ifdef LOG_TO_FILE
tstring path;
_TCHAR exePath[GANA_MAX_PATH];
_TCHAR exeDrive[GANA_MAX_PATH];
_TCHAR exeDir[GANA_MAX_PATH];
GetModuleFileName(NULL, exePath, GANA_MAX_PATH);
_tsplitpath_s(exePath, exeDrive, GANA_MAX_PATH, exeDir, GANA_MAX_PATH, NULL, 0, NULL, 0);
path = exeDrive;
path += exeDir;
path += _T("mayu.log");
m_logFile.open(path.c_str(), std::ios::app);
m_logFile.imbue(std::locale("japanese"));
#endif // LOG_TO_FILE
SendMessage(GetDlgItem(m_hwndLog, IDC_EDIT_log), EM_SETLIMITTEXT, 0, 0);
m_log.attach(m_hwndTaskTray);
// start keyboard handler thread
m_engine.setAssociatedWndow(m_hwndTaskTray);
m_engine.start();
// show tasktray icon
m_tasktrayIcon[0] = loadSmallIcon(IDI_ICON_mayu_disabled);
m_tasktrayIcon[1] = loadSmallIcon(IDI_ICON_mayu);
std::memset(&m_ni, 0, sizeof(m_ni));
m_ni.uID = ID_TaskTrayIcon;
m_ni.hWnd = m_hwndTaskTray;
m_ni.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
m_ni.hIcon = m_tasktrayIcon[1];
m_ni.uCallbackMessage = WM_APP_taskTrayNotify;
tstring tip = loadString(IDS_mayu);
tcslcpy(m_ni.szTip, tip.c_str(), NUMBER_OF(m_ni.szTip));
if (m_canUseTasktrayBaloon) {
m_ni.cbSize = NOTIFYICONDATA_V3_SIZE;
m_ni.uFlags |= NIF_INFO;
} else
m_ni.cbSize = NOTIFYICONDATA_V1_SIZE;
showTasktrayIcon(true);
// create menu
m_hMenuTaskTray = LoadMenu(g_hInst, MAKEINTRESOURCE(IDR_MENU_tasktray));
ASSERT(m_hMenuTaskTray);
// set initial lock state
notifyLockState();
#ifdef _WIN64
ZeroMemory(&m_pi,sizeof(m_pi));
ZeroMemory(&m_si,sizeof(m_si));
m_si.cb=sizeof(m_si);
// create mutex to block yamyd
m_hMutexYamyd = CreateMutex((SECURITY_ATTRIBUTES *)NULL, TRUE, MUTEX_YAMYD_BLOCKER);
tstring yamydPath;
_TCHAR exePath[GANA_MAX_PATH];
_TCHAR exeDrive[GANA_MAX_PATH];
_TCHAR exeDir[GANA_MAX_PATH];
GetModuleFileName(NULL, exePath, GANA_MAX_PATH);
_tsplitpath_s(exePath, exeDrive, GANA_MAX_PATH, exeDir, GANA_MAX_PATH, NULL, 0, NULL, 0);
yamydPath = exeDrive;
yamydPath += exeDir;
yamydPath += _T("yamyd32");
BOOL result = CreateProcess(yamydPath.c_str(), NULL, NULL, NULL, FALSE,
NORMAL_PRIORITY_CLASS, 0, NULL, &m_si, &m_pi);
if (result == FALSE) {
TCHAR buf[1024];
TCHAR text[1024];
TCHAR title[1024];
m_pi.hProcess = NULL;
LoadString(GetModuleHandle(NULL), IDS_cannotInvoke,
text, sizeof(text)/sizeof(text[0]));
LoadString(GetModuleHandle(NULL), IDS_mayu,
title, sizeof(title)/sizeof(title[0]));
_stprintf_s(buf, sizeof(buf)/sizeof(buf[0]),
text, _T("yamyd32"), GetLastError());
MessageBox((HWND)NULL, buf, title, MB_OK | MB_ICONSTOP);
} else {
CloseHandle(m_pi.hThread);
}
#endif // _WIN64
}
///
~Mayu() {
// stop notify from mayu.dll
g_hookData->m_hwndTaskTray = NULL;
CHECK_FALSE( uninstallMessageHook() );
#ifdef _WIN64
ReleaseMutex(m_hMutexYamyd);
if (m_pi.hProcess) {
WaitForSingleObject(m_pi.hProcess, 5000);
CloseHandle(m_pi.hProcess);
}
CloseHandle(m_hMutexYamyd);
#endif // _WIN64
CancelIo(m_hNotifyMailslot);
SleepEx(0, TRUE);
CloseHandle(m_hNotifyMailslot);
CloseHandle(m_hNotifyEvent);
ReleaseMutex(m_mutex);
WaitForSingleObject(m_mutex, INFINITE);
// first, detach log from edit control to avoid deadlock
m_log.detach();
#ifdef LOG_TO_FILE
m_logFile.close();
#endif // LOG_TO_FILE
// destroy windows
CHECK_TRUE( DestroyWindow(m_hwndVersion) );
CHECK_TRUE( DestroyWindow(m_hwndInvestigate) );
CHECK_TRUE( DestroyWindow(m_hwndLog) );
CHECK_TRUE( DestroyWindow(m_hwndTaskTray) );
// destroy menu
DestroyMenu(m_hMenuTaskTray);
// delete tasktray icon
CHECK_TRUE( Shell_NotifyIcon(NIM_DELETE, &m_ni) );
CHECK_TRUE( DestroyIcon(m_tasktrayIcon[1]) );
CHECK_TRUE( DestroyIcon(m_tasktrayIcon[0]) );
// stop keyboard handler thread
m_engine.stop();
if (!(m_sessionState & SESSION_END_QUERIED)) {
DWORD_PTR result;
SendMessageTimeout(HWND_BROADCAST, WM_NULL, 0, 0, 0, 3000, &result);
}
// remove setting;
delete m_setting;
}
/// message loop
WPARAM messageLoop() {
showBanner(false);
load();
mailslotHandler(0, 0);
while (1) {
HANDLE handles[] = { m_hNotifyEvent };
DWORD ret;
switch (ret = MsgWaitForMultipleObjectsEx(NUMBER_OF(handles), &handles[0],
INFINITE, QS_ALLINPUT, MWMO_ALERTABLE | MWMO_INPUTAVAILABLE)) {
case WAIT_OBJECT_0: // m_hNotifyEvent
break;
case WAIT_OBJECT_0 + NUMBER_OF(handles): {
MSG msg;
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != 0) {
if (msg.message == WM_QUIT) {
return msg.wParam;
}
if (IsDialogMessage(m_hwndLog, &msg))
break;
if (IsDialogMessage(m_hwndInvestigate, &msg))
break;
if (IsDialogMessage(m_hwndVersion, &msg))
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
break;
}
break;
}
case WAIT_IO_COMPLETION:
break;
case 0x102:
default:
break;
}
}
}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Functions
/// convert registry
void convertRegistry()
{
Registry reg(MAYU_REGISTRY_ROOT);
tstringi dot_mayu;
bool doesAdd = false;
DWORD index;
if (reg.read(_T(".mayu"), &dot_mayu)) {
reg.write(_T(".mayu0"), _T(";") + dot_mayu + _T(";"));
reg.remove(_T(".mayu"));
doesAdd = true;
index = 0;
} else if (!reg.read(_T(".mayu0"), &dot_mayu)) {
reg.write(_T(".mayu0"), loadString(IDS_readFromHomeDirectory) + _T(";;"));
doesAdd = true;
index = 1;
}
if (doesAdd) {
Registry commonreg(HKEY_LOCAL_MACHINE, _T("Software\\GANAware\\mayu"));
tstringi dir, layout;
if (commonreg.read(_T("dir"), &dir) &&
commonreg.read(_T("layout"), &layout)) {
tstringi tmp = _T(";") + dir + _T("\\dot.mayu");
if (layout == _T("109")) {
reg.write(_T(".mayu1"), loadString(IDS_109Emacs) + tmp
+ _T(";-DUSE109") _T(";-DUSEdefault"));
reg.write(_T(".mayu2"), loadString(IDS_104on109Emacs) + tmp
+ _T(";-DUSE109") _T(";-DUSEdefault") _T(";-DUSE104on109"));
reg.write(_T(".mayu3"), loadString(IDS_109) + tmp
+ _T(";-DUSE109"));
reg.write(_T(".mayu4"), loadString(IDS_104on109) + tmp
+ _T(";-DUSE109") _T(";-DUSE104on109"));
} else {
reg.write(_T(".mayu1"), loadString(IDS_104Emacs) + tmp
+ _T(";-DUSE104") _T(";-DUSEdefault"));
reg.write(_T(".mayu2"), loadString(IDS_109on104Emacs) + tmp
+ _T(";-DUSE104") _T(";-DUSEdefault") _T(";-DUSE109on104"));
reg.write(_T(".mayu3"), loadString(IDS_104) + tmp
+ _T(";-DUSE104"));
reg.write(_T(".mayu4"), loadString(IDS_109on104) + tmp
+ _T(";-DUSE104") _T(";-DUSE109on104"));
}
reg.write(_T(".mayuIndex"), index);
}
}
}
/// main
int WINAPI _tWinMain(HINSTANCE i_hInstance, HINSTANCE /* i_hPrevInstance */,
LPTSTR /* i_lpszCmdLine */, int /* i_nCmdShow */)
{
g_hInst = i_hInstance;
// set locale
CHECK_TRUE( _tsetlocale(LC_ALL, _T("")) );
// common controls
#if defined(_WIN95)
InitCommonControls();
#else
INITCOMMONCONTROLSEX icc;
icc.dwSize = sizeof(icc);
icc.dwICC = ICC_LISTVIEW_CLASSES;
CHECK_TRUE( InitCommonControlsEx(&icc) );
#endif
// convert old registry to new registry
#ifndef USE_INI
convertRegistry();
#endif // !USE_INI
// is another mayu running ?
HANDLE mutex = CreateMutex((SECURITY_ATTRIBUTES *)NULL, TRUE,
MUTEX_MAYU_EXCLUSIVE_RUNNING);
if (GetLastError() == ERROR_ALREADY_EXISTS) {
// another mayu already running
tstring text = loadString(IDS_mayuAlreadyExists);
tstring title = loadString(IDS_mayu);
if (g_hookData) {
UINT WM_TaskbarRestart = RegisterWindowMessage(_T("TaskbarCreated"));
PostMessage(reinterpret_cast<HWND>(g_hookData->m_hwndTaskTray),
WM_TaskbarRestart, 0, 0);
}
MessageBox((HWND)NULL, text.c_str(), title.c_str(), MB_OK | MB_ICONSTOP);
return 1;
}
try {
Mayu(mutex).messageLoop();
} catch (ErrorMessage &i_e) {
tstring title = loadString(IDS_mayu);
MessageBox((HWND)NULL, i_e.getMessage().c_str(), title.c_str(),
MB_OK | MB_ICONSTOP);
}
CHECK_TRUE( CloseHandle(mutex) );
return 0;
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// keymap.h
#ifndef _KEYMAP_H
# define _KEYMAP_H
# include "keyboard.h"
# include "function.h"
# include <vector>
///
class Action
{
public:
///
enum Type {
Type_key, ///
Type_keySeq, ///
Type_function, ///
};
private:
Action(const Action &i_action);
public:
Action() { }
///
virtual ~Action() { }
///
virtual Type getType() const = 0;
/// create clone
virtual Action *clone() const = 0;
/// stream output
virtual tostream &output(tostream &i_ost) const = 0;
};
///
tostream &operator<<(tostream &i_ost, const Action &i_action);
///
class ActionKey : public Action
{
public:
///
const ModifiedKey m_modifiedKey;
private:
ActionKey(const ActionKey &i_actionKey);
public:
///
ActionKey(const ModifiedKey &i_mk);
///
virtual Type getType() const;
/// create clone
virtual Action *clone() const;
/// stream output
virtual tostream &output(tostream &i_ost) const;
};
class KeySeq;
///
class ActionKeySeq : public Action
{
public:
KeySeq * const m_keySeq; ///
private:
ActionKeySeq(const ActionKeySeq &i_actionKeySeq);
public:
///
ActionKeySeq(KeySeq *i_keySeq);
///
virtual Type getType() const;
/// create clone
virtual Action *clone() const;
/// stream output
virtual tostream &output(tostream &i_ost) const;
};
///
class ActionFunction : public Action
{
public:
FunctionData * const m_functionData; /// function data
const Modifier m_modifier; /// modifier for &Sync
private:
ActionFunction(const ActionFunction &i_actionFunction);
public:
///
ActionFunction(FunctionData *i_functionData,
Modifier i_modifier = Modifier());
///
virtual ~ActionFunction();
///
virtual Type getType() const;
/// create clone
virtual Action *clone() const;
/// stream output
virtual tostream &output(tostream &i_ost) const;
};
///
class KeySeq
{
public:
typedef std::vector<Action *> Actions; ///
private:
Actions m_actions; ///
tstringi m_name; ///
Modifier::Type m_mode; /** Either Modifier::Type_KEYSEQ
or Modifier::Type_ASSIGN */
private:
///
void copy();
///
void clear();
public:
///
KeySeq(const tstringi &i_name);
///
KeySeq(const KeySeq &i_ks);
///
~KeySeq();
///
const Actions &getActions() const {
return m_actions;
}
///
KeySeq &operator=(const KeySeq &i_ks);
/// add
KeySeq &add(const Action &i_action);
/// get the first modified key of this key sequence
ModifiedKey getFirstModifiedKey() const;
///
const tstringi &getName() const {
return m_name;
}
/// stream output
friend tostream &operator<<(tostream &i_ost, const KeySeq &i_ks);
///
bool isCorrectMode(Modifier::Type i_mode) {
return m_mode <= i_mode;
}
///
void setMode(Modifier::Type i_mode) {
if (m_mode < i_mode)
m_mode = i_mode;
ASSERT( m_mode == Modifier::Type_KEYSEQ ||
m_mode == Modifier::Type_ASSIGN);
}
///
Modifier::Type getMode() const {
return m_mode;
}
};
///
class Keymap
{
public:
///
enum Type {
Type_keymap, /// this is keymap
Type_windowAnd, /// this is window &&
Type_windowOr, /// this is window ||
};
///
enum AssignOperator {
AO_new, /// =
AO_add, /// +=
AO_sub, /// -=
AO_overwrite, /// !, !!
};
///
enum AssignMode {
AM_notModifier, /// not modifier
AM_normal, /// normal modifier
AM_true, /** ! true modifier(doesn't
generate scan code) */
AM_oneShot, /// !! one shot modifier
AM_oneShotRepeatable, /// !!! one shot modifier
};
/// key assignment
class KeyAssignment
{
public:
ModifiedKey m_modifiedKey; ///
KeySeq *m_keySeq; ///
public:
///
KeyAssignment(const ModifiedKey &i_modifiedKey, KeySeq *i_keySeq)
: m_modifiedKey(i_modifiedKey), m_keySeq(i_keySeq) { }
///
KeyAssignment(const KeyAssignment &i_o)
: m_modifiedKey(i_o.m_modifiedKey), m_keySeq(i_o.m_keySeq) { }
///
bool operator<(const KeyAssignment &i_o) const {
return m_modifiedKey < i_o.m_modifiedKey;
}
};
/// modifier assignments
class ModAssignment
{
public:
AssignOperator m_assignOperator; ///
AssignMode m_assignMode; ///
Key *m_key; ///
};
typedef std::list<ModAssignment> ModAssignments; ///
/// parameter for describe();
class DescribeParam
{
private:
typedef std::list<ModifiedKey> DescribedKeys;
typedef std::list<const Keymap *> DescribedKeymap;
friend class Keymap;
private:
DescribedKeys m_dk;
DescribedKeymap m_dkeymap;
bool m_doesDescribeModifiers;
public:
DescribeParam() : m_doesDescribeModifiers(true) { }
};
private:
/// key assignments (hashed by first scan code)
typedef std::list<KeyAssignment> KeyAssignments;
enum {
HASHED_KEY_ASSIGNMENT_SIZE = 32, ///
};
private:
KeyAssignments m_hashedKeyAssignments[HASHED_KEY_ASSIGNMENT_SIZE]; ///
/// modifier assignments
ModAssignments m_modAssignments[Modifier::Type_ASSIGN];
Type m_type; /// type
tstringi m_name; /// keymap name
tregex m_windowClass; /// window class name regexp
tregex m_windowTitle; /// window title name regexp
KeySeq *m_defaultKeySeq; /// default keySeq
Keymap *m_parentKeymap; /// parent keymap
private:
///
KeyAssignments &getKeyAssignments(const ModifiedKey &i_mk);
///
const KeyAssignments &getKeyAssignments(const ModifiedKey &i_mk) const;
public:
///
Keymap(Type i_type,
const tstringi &i_name,
const tstringi &i_windowClass,
const tstringi &i_windowTitle,
KeySeq *i_defaultKeySeq,
Keymap *i_parentKeymap);
/// add a key assignment;
void addAssignment(const ModifiedKey &i_mk, KeySeq *i_keySeq);
/// add modifier
void addModifier(Modifier::Type i_mt, AssignOperator i_ao,
AssignMode i_am, Key *i_key);
/// search
const KeyAssignment *searchAssignment(const ModifiedKey &i_mk) const;
/// get
const KeySeq *getDefaultKeySeq() const {
return m_defaultKeySeq;
}
///
Keymap *getParentKeymap() const {
return m_parentKeymap;
}
///
const tstringi &getName() const {
return m_name;
}
/// does same window
bool doesSameWindow(const tstringi i_className,
const tstringi &i_titleName);
/// adjust modifier
void adjustModifier(Keyboard &i_keyboard);
/// get modAssignments
const ModAssignments &getModAssignments(Modifier::Type i_mt) const {
return m_modAssignments[i_mt];
}
/// describe
void describe(tostream &i_ost, DescribeParam *i_dp) const;
/// set default keySeq and parent keymap if default keySeq has not been set
bool setIfNotYet(KeySeq *i_keySeq, Keymap *i_parentKeymap);
};
/// stream output
extern tostream &operator<<(tostream &i_ost, const Keymap *i_keymap);
///
class Keymaps
{
public:
typedef std::list<Keymap *> KeymapPtrList; ///
private:
typedef std::list<Keymap> KeymapList; ///
private:
KeymapList m_keymapList; /** pointer into keymaps may
exist */
public:
///
Keymaps();
/// search by name
Keymap *searchByName(const tstringi &i_name);
/// search window
void searchWindow(KeymapPtrList *o_keymapPtrList,
const tstringi &i_className,
const tstringi &i_titleName);
/// add keymap
Keymap *add(const Keymap &i_keymap);
/// adjust modifier
void adjustModifier(Keyboard &i_keyboard);
};
///
class KeySeqs
{
private:
typedef std::list<KeySeq> KeySeqList; ///
private:
KeySeqList m_keySeqList; ///
public:
/// add a named keyseq (name can be empty)
KeySeq *add(const KeySeq &i_keySeq);
/// search by name
KeySeq *searchByName(const tstringi &i_name);
};
#endif // !_KEYMAP_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// target.h
#ifndef _TARGET_H
# define _TARGET_H
# include <windows.h>
///
extern ATOM Register_target();
///
enum {
///
WM_APP_targetNotify = WM_APP + 102,
};
#endif // !_TARGET_H
<file_sep>///////////////////////////////////////////////////////////////////////////////
// Driver for Madotsukai no Yu^utsu for Windows2000
#include <ntddk.h>
#include <ntddkbd.h>
#include <devioctl.h>
#pragma warning(3 : 4061 4100 4132 4701 4706)
#include "ioctl.h"
#include "keyque.c"
//#define USE_TOUCHPAD // very experimental!
#if DBG
// Enable debug logging only on checked build:
// We use macro to avoid function call overhead
// in non-logging case, and use double paren such
// as DEBUG_LOG((...)) because of va_list in macro.
#include "log.h"
#define DEBUG_LOG_INIT(x) mayuLogInit x
#define DEBUG_LOG_TERM(x) mayuLogTerm x
#define DEBUG_LOG(x) mayuLogEnque x
#define DEBUG_LOG_RETRIEVE(x) mayuLogDeque x
#else
#define DEBUG_LOG_INIT(x)
#define DEBUG_LOG_TERM(x)
#define DEBUG_LOG(x)
#define DEBUG_LOG_RETRIEVE(x) STATUS_INVALID_DEVICE_REQUEST
#endif
///////////////////////////////////////////////////////////////////////////////
// Device Extensions
struct _DetourDeviceExtension;
struct _FilterDeviceExtension;
typedef struct _DetourDeviceExtension {
PDRIVER_DISPATCH MajorFunction[IRP_MJ_MAXIMUM_FUNCTION + 1];
KSPIN_LOCK lock; // lock below datum
PDEVICE_OBJECT filterDevObj;
LONG isOpen;
BOOLEAN wasCleanupInitiated; //
PIRP irpq;
KeyQue readQue; // when IRP_MJ_READ, the contents of readQue are returned
} DetourDeviceExtension;
typedef struct _FilterDeviceExtension {
PDRIVER_DISPATCH MajorFunction[IRP_MJ_MAXIMUM_FUNCTION + 1];
PDEVICE_OBJECT detourDevObj;
PDEVICE_OBJECT kbdClassDevObj; // keyboard class device object
#ifdef USE_TOUCHPAD
BOOLEAN isKeyboard;
#endif
KSPIN_LOCK lock; // lock below datum
PIRP irpq;
KeyQue readQue; // when IRP_MJ_READ, the contents of readQue are returned
#ifdef USE_TOUCHPAD
BOOLEAN isTouched;
#endif
} FilterDeviceExtension;
///////////////////////////////////////////////////////////////////////////////
// Protorypes (TODO)
NTSTATUS DriverEntry (IN PDRIVER_OBJECT, IN PUNICODE_STRING);
NTSTATUS mayuAddDevice (IN PDRIVER_OBJECT, IN PDEVICE_OBJECT);
VOID mayuUnloadDriver (IN PDRIVER_OBJECT);
VOID mayuDetourReadCancel (IN PDEVICE_OBJECT, IN PIRP);
NTSTATUS filterGenericCompletion (IN PDEVICE_OBJECT, IN PIRP, IN PVOID);
NTSTATUS filterReadCompletion (IN PDEVICE_OBJECT, IN PIRP, IN PVOID);
NTSTATUS mayuGenericDispatch (IN PDEVICE_OBJECT, IN PIRP);
NTSTATUS detourCreate (IN PDEVICE_OBJECT, IN PIRP);
NTSTATUS detourClose (IN PDEVICE_OBJECT, IN PIRP);
NTSTATUS detourRead (IN PDEVICE_OBJECT, IN PIRP);
NTSTATUS detourWrite (IN PDEVICE_OBJECT, IN PIRP);
NTSTATUS detourCleanup (IN PDEVICE_OBJECT, IN PIRP);
NTSTATUS detourDeviceControl (IN PDEVICE_OBJECT, IN PIRP);
NTSTATUS filterRead (IN PDEVICE_OBJECT, IN PIRP);
NTSTATUS filterPassThrough (IN PDEVICE_OBJECT, IN PIRP);
NTSTATUS detourPnP (IN PDEVICE_OBJECT, IN PIRP);
NTSTATUS filterPnP (IN PDEVICE_OBJECT, IN PIRP);
#ifndef MAYUD_NT4
NTSTATUS detourPower (IN PDEVICE_OBJECT, IN PIRP);
NTSTATUS filterPower (IN PDEVICE_OBJECT, IN PIRP);
#endif // !MAYUD_NT4
BOOLEAN CancelKeyboardClassRead(IN PIRP, IN PDEVICE_OBJECT);
NTSTATUS readq(KeyQue*, PIRP);
#ifdef USE_TOUCHPAD
NTSTATUS filterTouchpadCompletion (IN PDEVICE_OBJECT, IN PIRP, IN PVOID);
NTSTATUS filterTouchpad (IN PDEVICE_OBJECT, IN PIRP);
#endif
#ifdef ALLOC_PRAGMA
#pragma alloc_text( init, DriverEntry )
#endif // ALLOC_PRAGMA
///////////////////////////////////////////////////////////////////////////////
// Global Constants / Variables
BOOLEAN g_isPnP;
BOOLEAN g_isXp;
ULONG g_SpinLock_offset;
ULONG g_RequestIsPending_offset;
// Device names
#define UnicodeString(str) { sizeof(str) - sizeof(UNICODE_NULL), \
sizeof(str) - sizeof(UNICODE_NULL), str }
static UNICODE_STRING MayuDetourDeviceName =
UnicodeString(L"\\Device\\MayuDetour0");
static UNICODE_STRING MayuDetourWin32DeviceName =
UnicodeString(L"\\DosDevices\\MayuDetour1");
static UNICODE_STRING KeyboardClassDeviceName =
UnicodeString(DD_KEYBOARD_DEVICE_NAME_U L"0");
static UNICODE_STRING KeyboardClassDriverName =
UnicodeString(L"\\Driver\\kbdclass");
#ifdef USE_TOUCHPAD
#define TOUCHPAD_PRESSURE_OFFSET 7
#endif
// Global Variables
PDRIVER_DISPATCH _IopInvalidDeviceRequest; // Default dispatch function
#define MAYUD_MODE L""
static UNICODE_STRING MayuDriverVersion =
UnicodeString(L"$Revision: 1.27 $" MAYUD_MODE);
///////////////////////////////////////////////////////////////////////////////
// Entry / Unload
void DEBUG_LOGChain(PDRIVER_OBJECT driverObject)
{
PDEVICE_OBJECT deviceObject = driverObject->DeviceObject;
if (deviceObject) {
while (deviceObject->NextDevice) {
DEBUG_LOG(("%x->", deviceObject));
deviceObject = deviceObject->NextDevice;
}
DEBUG_LOG(("%x", deviceObject));
}
return;
}
// initialize driver
NTSTATUS DriverEntry(IN PDRIVER_OBJECT driverObject,
IN PUNICODE_STRING registryPath)
{
NTSTATUS status;
BOOLEAN is_symbolicLinkCreated = FALSE;
ULONG i;
PDEVICE_OBJECT detourDevObj = NULL;
DetourDeviceExtension *detourDevExt = NULL;
ULONG start = 0;
RTL_QUERY_REGISTRY_TABLE query[2];
UNREFERENCED_PARAMETER(registryPath);
DEBUG_LOG_INIT(("mayud: start logging"));
// Environment specific initialize
RtlZeroMemory(query, sizeof(query));
query[0].Name = L"Start";
query[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
query[0].EntryContext = &start;
RtlQueryRegistryValues(RTL_REGISTRY_SERVICES, L"mayud", query, NULL, NULL);
if (start == 0x03) {
g_isPnP = TRUE;
DEBUG_LOG(("is PnP"));
} else {
g_isPnP = FALSE;
DEBUG_LOG(("is not PnP"));
}
#ifdef MAYUD_NT4
g_isXp = FALSE;
g_SpinLock_offset = 48;
g_RequestIsPending_offset = 0;
#else /* !MAYUD_NT4 */
if (IoIsWdmVersionAvailable(1, 0x20)) { // is WindowsXP
DEBUG_LOG(("is WindowsXp"));
g_isXp = TRUE;
g_SpinLock_offset = 108;
g_RequestIsPending_offset = 0;
} else if (IoIsWdmVersionAvailable(1, 0x10)) { // is Windows2000
DEBUG_LOG(("is Windows2000"));
g_isXp =FALSE;
g_SpinLock_offset = 116;
g_RequestIsPending_offset = 48;
} else { // Unknown version
DEBUG_LOG(("unknown Windows"));
status = STATUS_UNKNOWN_REVISION;
goto error;
}
#endif /* MAYUD_NT4 */
// initialize global variables
_IopInvalidDeviceRequest = driverObject->MajorFunction[IRP_MJ_CREATE];
// set major functions
driverObject->DriverUnload = mayuUnloadDriver;
if (g_isPnP == TRUE) {
driverObject->DriverExtension->AddDevice = mayuAddDevice;
}
for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++)
#ifdef MAYUD_NT4
if (i != IRP_MJ_POWER)
#endif // MAYUD_NT4
driverObject->MajorFunction[i] = mayuGenericDispatch;
if (g_isPnP == TRUE) {
driverObject->MajorFunction[IRP_MJ_PNP] = mayuGenericDispatch;
}
// create a device
{
// create detour device
status = IoCreateDevice(driverObject, sizeof(DetourDeviceExtension),
&MayuDetourDeviceName, FILE_DEVICE_KEYBOARD,
0, FALSE, &detourDevObj);
if (!NT_SUCCESS(status)) goto error;
DEBUG_LOG(("create detour device: %x", detourDevObj));
DEBUG_LOGChain(driverObject);
detourDevObj->Flags |= DO_BUFFERED_IO;
#ifndef MAYUD_NT4
detourDevObj->Flags |= DO_POWER_PAGABLE;
#endif // !MAYUD_NT4
// initialize detour device extension
detourDevExt = (DetourDeviceExtension*)detourDevObj->DeviceExtension;
RtlZeroMemory(detourDevExt, sizeof(DetourDeviceExtension));
detourDevExt->filterDevObj = NULL;
KeInitializeSpinLock(&detourDevExt->lock);
detourDevExt->isOpen = FALSE;
detourDevExt->wasCleanupInitiated = FALSE;
detourDevExt->irpq = NULL;
status = KqInitialize(&detourDevExt->readQue);
if (!NT_SUCCESS(status)) goto error;
// create symbolic link for detour
status =
IoCreateSymbolicLink(&MayuDetourWin32DeviceName, &MayuDetourDeviceName);
if (!NT_SUCCESS(status)) goto error;
is_symbolicLinkCreated = TRUE;
if (g_isPnP == FALSE)
// attach filter device to keyboard class device
{
PFILE_OBJECT f;
PDEVICE_OBJECT kbdClassDevObj;
status = IoGetDeviceObjectPointer(&KeyboardClassDeviceName,
FILE_ALL_ACCESS, &f,
&kbdClassDevObj);
if (!NT_SUCCESS(status)) goto error;
ObDereferenceObject(f);
status = mayuAddDevice(driverObject, kbdClassDevObj);
// why cannot I do below ?
// status = IoAttachDevice(filterDevObj, &KeyboardClassDeviceName,
// &filterDevExt->kbdClassDevObj);
if (!NT_SUCCESS(status)) goto error;
}
// initialize Major Functions
for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++) {
detourDevExt->MajorFunction[i] = _IopInvalidDeviceRequest;
}
detourDevExt->MajorFunction[IRP_MJ_READ] = detourRead;
detourDevExt->MajorFunction[IRP_MJ_WRITE] = detourWrite;
detourDevExt->MajorFunction[IRP_MJ_CREATE] = detourCreate;
detourDevExt->MajorFunction[IRP_MJ_CLOSE] = detourClose;
detourDevExt->MajorFunction[IRP_MJ_CLEANUP] = detourCleanup;
detourDevExt->MajorFunction[IRP_MJ_DEVICE_CONTROL] = detourDeviceControl;
#ifndef MAYUD_NT4
detourDevExt->MajorFunction[IRP_MJ_POWER] = detourPower;
#endif // !MAYUD_NT4
if (g_isPnP == TRUE) {
detourDevExt->MajorFunction[IRP_MJ_PNP] = detourPnP;
}
}
detourDevObj->Flags &= ~DO_DEVICE_INITIALIZING;
return STATUS_SUCCESS;
error: {
if (is_symbolicLinkCreated)
IoDeleteSymbolicLink(&MayuDetourWin32DeviceName);
if (detourDevObj) {
KqFinalize(&detourDevExt->readQue);
IoDeleteDevice(detourDevObj);
}
}
return status;
}
NTSTATUS mayuAddDevice(IN PDRIVER_OBJECT driverObject,
IN PDEVICE_OBJECT kbdClassDevObj)
{
NTSTATUS status;
PDEVICE_OBJECT devObj;
PDEVICE_OBJECT filterDevObj;
PDEVICE_OBJECT attachedDevObj;
DetourDeviceExtension *detourDevExt;
FilterDeviceExtension *filterDevExt;
ULONG i;
DEBUG_LOG(("attach to device: %x", kbdClassDevObj));
DEBUG_LOG(("type of device: %x", kbdClassDevObj->DeviceType));
DEBUG_LOG(("name of driver: %T", &(kbdClassDevObj->DriverObject->DriverName)));
// create filter device
status = IoCreateDevice(driverObject, sizeof(FilterDeviceExtension),
NULL, FILE_DEVICE_KEYBOARD,
0, FALSE, &filterDevObj);
DEBUG_LOG(("add filter device: %x", filterDevObj));
DEBUG_LOGChain(driverObject);
if (!NT_SUCCESS(status)) return status;
filterDevObj->Flags |= DO_BUFFERED_IO;
#ifndef MAYUD_NT4
filterDevObj->Flags |= DO_POWER_PAGABLE;
#endif // !MAYUD_NT4
// initialize filter device extension
filterDevExt = (FilterDeviceExtension*)filterDevObj->DeviceExtension;
RtlZeroMemory(filterDevExt, sizeof(FilterDeviceExtension));
KeInitializeSpinLock(&filterDevExt->lock);
filterDevExt->irpq = NULL;
status = KqInitialize(&filterDevExt->readQue);
if (!NT_SUCCESS(status)) goto error;
#ifdef USE_TOUCHPAD
filterDevExt->isKeyboard = FALSE;
filterDevExt->isTouched = FALSE;
#endif
attachedDevObj = kbdClassDevObj->AttachedDevice;
while (attachedDevObj) {
DEBUG_LOG(("attached to %T", &(attachedDevObj->DriverObject->DriverName)));
DEBUG_LOG(("type of attched device: %x", attachedDevObj->DeviceType));
#ifdef USE_TOUCHPAD
if (RtlCompareUnicodeString(&KeyboardClassDriverName, &attachedDevObj->DriverObject->DriverName, TRUE) == 0)
filterDevExt->isKeyboard = TRUE;
#endif
attachedDevObj = attachedDevObj->AttachedDevice;
}
devObj = filterDevObj->NextDevice;
while (devObj->NextDevice) {
devObj = devObj->NextDevice;
}
filterDevExt->detourDevObj = devObj;
detourDevExt = (DetourDeviceExtension*)devObj->DeviceExtension;
if (!detourDevExt->filterDevObj) {
detourDevExt->filterDevObj = filterDevObj;
}
filterDevExt->kbdClassDevObj =
IoAttachDeviceToDeviceStack(filterDevObj, kbdClassDevObj);
if (!filterDevExt->kbdClassDevObj) goto error;
for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++) {
filterDevExt->MajorFunction[i] =
(filterDevExt->kbdClassDevObj->DriverObject->MajorFunction[i]
== _IopInvalidDeviceRequest) ?
_IopInvalidDeviceRequest : filterPassThrough;
}
#ifdef USE_TOUCHPAD
if (filterDevExt->isKeyboard == FALSE) {
DEBUG_LOG(("filter read: GlidePoint"));
filterDevObj->DeviceType = FILE_DEVICE_MOUSE;
filterDevExt->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = filterTouchpad;
} else
#endif
{
DEBUG_LOG(("filter read: Keyboard"));
filterDevExt->MajorFunction[IRP_MJ_READ] = filterRead;
}
#ifndef MAYUD_NT4
filterDevExt->MajorFunction[IRP_MJ_POWER] = filterPower;
#endif // !MAYUD_NT4
if (g_isPnP == TRUE) {
filterDevExt->MajorFunction[IRP_MJ_PNP] = filterPnP;
}
filterDevObj->Flags &= ~DO_DEVICE_INITIALIZING;
return STATUS_SUCCESS;
error:
DEBUG_LOG(("mayuAddDevice: error"));
if (filterDevObj) {
KqFinalize(&filterDevExt->readQue);
IoDeleteDevice(filterDevObj);
}
return status;
}
BOOLEAN CancelKeyboardClassRead(PIRP cancelIrp, PDEVICE_OBJECT kbdClassDevObj)
{
PVOID kbdClassDevExt;
BOOLEAN isSafe;
PKSPIN_LOCK SpinLock;
KIRQL currentIrql;
kbdClassDevExt = kbdClassDevObj->DeviceExtension;
SpinLock = (PKSPIN_LOCK)((ULONG)kbdClassDevExt + g_SpinLock_offset);
KeAcquireSpinLock(SpinLock, ¤tIrql);
if (g_isXp == TRUE) {
isSafe = cancelIrp->CancelRoutine ? TRUE : FALSE;
} else {
isSafe = *(BOOLEAN*)((ULONG)kbdClassDevExt + g_RequestIsPending_offset);
}
if (isSafe == TRUE) {
KeReleaseSpinLock(SpinLock, currentIrql);
IoCancelIrp(cancelIrp);
} else {
DEBUG_LOG(("cancel irp not pending"));
KeReleaseSpinLock(SpinLock, currentIrql);
}
return isSafe;
}
// unload driver
VOID mayuUnloadDriver(IN PDRIVER_OBJECT driverObject)
{
KIRQL currentIrql;
PIRP cancelIrp;
PDEVICE_OBJECT devObj;
DetourDeviceExtension *detourDevExt;
// walk on device chain(the last one is detour device?)
devObj = driverObject->DeviceObject;
while (devObj->NextDevice) {
FilterDeviceExtension *filterDevExt
= (FilterDeviceExtension*)devObj->DeviceExtension;
PDEVICE_OBJECT delObj;
PDEVICE_OBJECT kbdClassDevObj;
// detach
IoDetachDevice(filterDevExt->kbdClassDevObj);
// cancel filter IRP_MJ_READ
KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql);
// TODO: at this point, the irp may be completed (but what can I do for it ?)
// finalize read que
KqFinalize(&filterDevExt->readQue);
cancelIrp = filterDevExt->irpq;
filterDevExt->irpq = NULL;
kbdClassDevObj = filterDevExt->kbdClassDevObj;
KeReleaseSpinLock(&filterDevExt->lock, currentIrql);
if (cancelIrp) {
while (CancelKeyboardClassRead(cancelIrp, kbdClassDevObj) != TRUE);
}
// delete device objects
delObj= devObj;
devObj = devObj->NextDevice;
IoDeleteDevice(delObj);
}
detourDevExt = (DetourDeviceExtension*)devObj->DeviceExtension;
// cancel filter IRP_MJ_READ
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
// TODO: at this point, the irp may be completed (but what can I do for it ?)
cancelIrp = detourDevExt->irpq;
// finalize read que
KqFinalize(&detourDevExt->readQue);
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
if (cancelIrp)
IoCancelIrp(cancelIrp);
// delete device objects
IoDeleteDevice(devObj);
// delete symbolic link
IoDeleteSymbolicLink(&MayuDetourWin32DeviceName);
DEBUG_LOG_TERM(());
}
///////////////////////////////////////////////////////////////////////////////
// Cancel Functionss
// detour read cancel
VOID mayuDetourReadCancel(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
DetourDeviceExtension *devExt =
(DetourDeviceExtension *)deviceObject->DeviceExtension;
KIRQL currentIrql;
KeAcquireSpinLock(&devExt->lock, ¤tIrql);
devExt->irpq = NULL;
KeReleaseSpinLock(&devExt->lock, currentIrql);
IoReleaseCancelSpinLock(irp->CancelIrql);
DEBUG_LOG(("detourReadCancel:"));
#if 0
KeAcquireSpinLock(&devExt->lock, ¤tIrql);
if (devExt->irpq && irp == deviceObject->CurrentIrp)
// the current request is being cancelled
{
deviceObject->CurrentIrp = NULL;
devExt->irpq = NULL;
KeReleaseSpinLock(&devExt->lock, currentIrql);
IoStartNextPacket(deviceObject, TRUE);
} else {
// Cancel a request in the device queue
KIRQL cancelIrql;
IoAcquireCancelSpinLock(&cancelIrql);
KeRemoveEntryDeviceQueue(&deviceObject->DeviceQueue,
&irp->Tail.Overlay.DeviceQueueEntry);
IoReleaseCancelSpinLock(cancelIrql);
KeReleaseSpinLock(&devExt->lock, currentIrql);
}
#endif
irp->IoStatus.Status = STATUS_CANCELLED;
irp->IoStatus.Information = 0;
IoCompleteRequest(irp, IO_KEYBOARD_INCREMENT);
}
///////////////////////////////////////////////////////////////////////////////
// Complete Functions
//
NTSTATUS filterGenericCompletion(IN PDEVICE_OBJECT deviceObject,
IN PIRP irp, IN PVOID context)
{
UNREFERENCED_PARAMETER(deviceObject);
UNREFERENCED_PARAMETER(context);
if (irp->PendingReturned)
IoMarkIrpPending(irp);
return STATUS_SUCCESS;
}
//
NTSTATUS filterReadCompletion(IN PDEVICE_OBJECT deviceObject,
IN PIRP irp, IN PVOID context)
{
NTSTATUS status;
KIRQL currentIrql, cancelIrql;
PIRP irpCancel = NULL;
FilterDeviceExtension *filterDevExt =
(FilterDeviceExtension*)deviceObject->DeviceExtension;
PDEVICE_OBJECT detourDevObj = filterDevExt->detourDevObj;
DetourDeviceExtension *detourDevExt =
(DetourDeviceExtension*)detourDevObj->DeviceExtension;
UNREFERENCED_PARAMETER(context);
KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql);
filterDevExt->irpq = NULL;
KeReleaseSpinLock(&filterDevExt->lock, currentIrql);
if (irp->PendingReturned) {
status = STATUS_PENDING;
IoMarkIrpPending(irp);
} else {
status = STATUS_SUCCESS;
}
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
if (detourDevExt->isOpen && !detourDevExt->wasCleanupInitiated) {
// if detour is opened, key datum are forwarded to detour
if (irp->IoStatus.Status == STATUS_SUCCESS) {
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp);
KqEnque(&detourDevExt->readQue,
(KEYBOARD_INPUT_DATA *)irp->AssociatedIrp.SystemBuffer,
irp->IoStatus.Information / sizeof(KEYBOARD_INPUT_DATA));
irp->IoStatus.Status = STATUS_CANCELLED;
irp->IoStatus.Information = 0;
detourDevExt->filterDevObj = deviceObject;
}
IoAcquireCancelSpinLock(&cancelIrql);
if (detourDevExt->irpq) {
if (readq(&detourDevExt->readQue, detourDevExt->irpq) ==
STATUS_SUCCESS) {
IoSetCancelRoutine(detourDevExt->irpq, NULL);
IoCompleteRequest(detourDevExt->irpq, IO_KEYBOARD_INCREMENT);
detourDevExt->irpq = NULL;
}
}
IoReleaseCancelSpinLock(cancelIrql);
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql);
status = readq(&filterDevExt->readQue, irp);
KeReleaseSpinLock(&filterDevExt->lock, currentIrql);
} else {
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
}
if (status == STATUS_SUCCESS)
irp->IoStatus.Status = STATUS_SUCCESS;
return irp->IoStatus.Status;
}
NTSTATUS readq(KeyQue *readQue, PIRP irp)
{
if (!KqIsEmpty(readQue)) {
PIO_STACK_LOCATION irpSp;
ULONG len;
irpSp = IoGetCurrentIrpStackLocation(irp);
len = KqDeque(readQue,
(KEYBOARD_INPUT_DATA *)irp->AssociatedIrp.SystemBuffer,
irpSp->Parameters.Read.Length / sizeof(KEYBOARD_INPUT_DATA));
irp->IoStatus.Status = STATUS_SUCCESS;
irp->IoStatus.Information = len * sizeof(KEYBOARD_INPUT_DATA);
irpSp->Parameters.Read.Length = irp->IoStatus.Information;
return STATUS_SUCCESS;
} else {
irp->IoStatus.Status = STATUS_PENDING;
irp->IoStatus.Information = 0;
return STATUS_PENDING;
}
}
///////////////////////////////////////////////////////////////////////////////
// Dispatch Functions
// Generic Dispatcher
NTSTATUS mayuGenericDispatch(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp);
if (deviceObject->NextDevice) {
FilterDeviceExtension *filterDevExt =
(FilterDeviceExtension *)deviceObject->DeviceExtension;
#ifdef USE_TOUCHPAD
if (filterDevExt->isKeyboard == FALSE) {
DEBUG_LOG(("MajorFunction: %x", irpSp->MajorFunction));
}
#endif
return filterDevExt->MajorFunction[irpSp->MajorFunction](deviceObject, irp);
} else {
DetourDeviceExtension *detourDevExt =
(DetourDeviceExtension *)deviceObject->DeviceExtension;
return detourDevExt->MajorFunction[irpSp->MajorFunction](deviceObject, irp);
}
}
// detour IRP_MJ_CREATE
NTSTATUS detourCreate(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
DetourDeviceExtension *detourDevExt =
(DetourDeviceExtension*)deviceObject->DeviceExtension;
if (1 < InterlockedIncrement(&detourDevExt->isOpen))
// mayu detour device can be opend only once at a time
{
InterlockedDecrement(&detourDevExt->isOpen);
irp->IoStatus.Status = STATUS_INTERNAL_ERROR;
} else {
PIRP irpCancel;
KIRQL currentIrql;
PDEVICE_OBJECT filterDevObj;
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
detourDevExt->wasCleanupInitiated = FALSE;
KqClear(&detourDevExt->readQue);
filterDevObj = detourDevExt->filterDevObj;
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
if (filterDevObj) {
FilterDeviceExtension *filterDevExt =
(FilterDeviceExtension*)filterDevObj->DeviceExtension;
PDEVICE_OBJECT kbdClassDevObj;
KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql);
irpCancel = filterDevExt->kbdClassDevObj->CurrentIrp;
kbdClassDevObj = filterDevExt->kbdClassDevObj;
KeReleaseSpinLock(&filterDevExt->lock, currentIrql);
if (irpCancel) {
CancelKeyboardClassRead(irpCancel, kbdClassDevObj);
}
}
irp->IoStatus.Status = STATUS_SUCCESS;
}
irp->IoStatus.Information = 0;
IoCompleteRequest(irp, IO_NO_INCREMENT);
return irp->IoStatus.Status;
}
// detour IRP_MJ_CLOSE
NTSTATUS detourClose(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
DetourDeviceExtension *detourDevExt =
(DetourDeviceExtension*)deviceObject->DeviceExtension;
KIRQL currentIrql;
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
InterlockedDecrement(&detourDevExt->isOpen);
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
irp->IoStatus.Status = STATUS_SUCCESS;
irp->IoStatus.Information = 0;
IoCompleteRequest(irp, IO_NO_INCREMENT);
DEBUG_LOG_TERM(());
return STATUS_SUCCESS;
}
// detour IRP_MJ_READ
NTSTATUS detourRead(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
NTSTATUS status;
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp);
DetourDeviceExtension *detourDevExt =
(DetourDeviceExtension*)deviceObject->DeviceExtension;
KIRQL currentIrql, cancelIrql;
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
if (irpSp->Parameters.Read.Length == 0)
status = STATUS_SUCCESS;
else if (irpSp->Parameters.Read.Length % sizeof(KEYBOARD_INPUT_DATA))
status = STATUS_BUFFER_TOO_SMALL;
else
status = readq(&detourDevExt->readQue, irp);
if (status == STATUS_PENDING) {
IoAcquireCancelSpinLock(&cancelIrql);
IoMarkIrpPending(irp);
detourDevExt->irpq = irp;
IoSetCancelRoutine(irp, mayuDetourReadCancel);
IoReleaseCancelSpinLock(cancelIrql);
} else {
IoCompleteRequest(irp, IO_KEYBOARD_INCREMENT);
}
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
return status;
}
// detour IRP_MJ_WRITE
NTSTATUS detourWrite(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
NTSTATUS status;
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp);
ULONG len = irpSp->Parameters.Write.Length;
DetourDeviceExtension *detourDevExt =
(DetourDeviceExtension*)deviceObject->DeviceExtension;
irp->IoStatus.Information = 0;
if (len == 0)
status = STATUS_SUCCESS;
else if (len % sizeof(KEYBOARD_INPUT_DATA))
status = STATUS_INVALID_PARAMETER;
else {
// write to filter que
KIRQL cancelIrql, currentIrql;
PIRP irpCancel;
PDEVICE_OBJECT filterDevObj;
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
filterDevObj = detourDevExt->filterDevObj;
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
// enque filter que
if (filterDevObj) {
FilterDeviceExtension *filterDevExt =
(FilterDeviceExtension*)filterDevObj->DeviceExtension;
PDEVICE_OBJECT kbdClassDevObj;
KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql);
len /= sizeof(KEYBOARD_INPUT_DATA);
len = KqEnque(&filterDevExt->readQue,
(KEYBOARD_INPUT_DATA *)irp->AssociatedIrp.SystemBuffer,
len);
irp->IoStatus.Information = len * sizeof(KEYBOARD_INPUT_DATA);
irpSp->Parameters.Write.Length = irp->IoStatus.Information;
// cancel filter irp
irpCancel = filterDevExt->irpq;
filterDevExt->irpq = NULL;
kbdClassDevObj = filterDevExt->kbdClassDevObj;
KeReleaseSpinLock(&filterDevExt->lock, currentIrql);
if (irpCancel) {
CancelKeyboardClassRead(irpCancel, kbdClassDevObj);
}
status = STATUS_SUCCESS;
} else {
irp->IoStatus.Information = 0;
irpSp->Parameters.Write.Length = irp->IoStatus.Information;
status = STATUS_CANCELLED;
}
}
IoCompleteRequest(irp, IO_NO_INCREMENT);
return status;
}
// detour IRP_MJ_CLEANUP
NTSTATUS detourCleanup(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
KIRQL currentIrql, cancelIrql;
PIO_STACK_LOCATION irpSp;
PIRP currentIrp = NULL, irpCancel;
DetourDeviceExtension *detourDevExt =
(DetourDeviceExtension*)deviceObject->DeviceExtension;
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
IoAcquireCancelSpinLock(&cancelIrql);
irpSp = IoGetCurrentIrpStackLocation(irp);
detourDevExt->wasCleanupInitiated = TRUE;
// Complete all requests queued by this thread with STATUS_CANCELLED
currentIrp = deviceObject->CurrentIrp;
deviceObject->CurrentIrp = NULL;
detourDevExt->irpq = NULL;
while (currentIrp != NULL) {
IoSetCancelRoutine(currentIrp, NULL);
currentIrp->IoStatus.Status = STATUS_CANCELLED;
currentIrp->IoStatus.Information = 0;
IoReleaseCancelSpinLock(cancelIrql);
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
IoCompleteRequest(currentIrp, IO_NO_INCREMENT);
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
IoAcquireCancelSpinLock(&cancelIrql);
// Dequeue the next packet (IRP) from the device work queue.
{
PKDEVICE_QUEUE_ENTRY packet =
KeRemoveDeviceQueue(&deviceObject->DeviceQueue);
currentIrp = packet ?
CONTAINING_RECORD(packet, IRP, Tail.Overlay.DeviceQueueEntry) : NULL;
}
}
IoReleaseCancelSpinLock(cancelIrql);
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
// Complete the cleanup request with STATUS_SUCCESS.
irp->IoStatus.Status = STATUS_SUCCESS;
irp->IoStatus.Information = 0;
IoCompleteRequest(irp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
// detour IRP_MJ_DEVICE_CONTROL
NTSTATUS detourDeviceControl(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
NTSTATUS status;
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp);
DetourDeviceExtension *detourDevExt =
(DetourDeviceExtension*)deviceObject->DeviceExtension;
irp->IoStatus.Information = 0;
if (irpSp->Parameters.DeviceIoControl.IoControlCode != IOCTL_MAYU_GET_LOG) DEBUG_LOG(("DeviceIoControl: %x", irpSp->Parameters.DeviceIoControl.IoControlCode));
status = STATUS_INVALID_DEVICE_REQUEST;
switch (irpSp->Parameters.DeviceIoControl.IoControlCode) {
case IOCTL_MAYU_DETOUR_CANCEL: {
KIRQL currentIrql;
PIRP irpCancel = NULL;
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
if (detourDevExt->isOpen)
irpCancel = detourDevExt->irpq;
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
if (irpCancel)
IoCancelIrp(irpCancel);// at this point, the irpCancel may be completed
status = STATUS_SUCCESS;
break;
}
case IOCTL_MAYU_GET_VERSION: {
if (irpSp->Parameters.DeviceIoControl.OutputBufferLength <
MayuDriverVersion.Length) {
status = STATUS_INVALID_PARAMETER;
break;
}
RtlCopyMemory(irp->AssociatedIrp.SystemBuffer,
MayuDriverVersion.Buffer, MayuDriverVersion.Length);
irp->IoStatus.Information = MayuDriverVersion.Length;
DEBUG_LOG(("Version: %T", &MayuDriverVersion));
status = STATUS_SUCCESS;
break;
}
case IOCTL_MAYU_GET_LOG:
status = DEBUG_LOG_RETRIEVE((irp));
break;
case IOCTL_MAYU_FORCE_KEYBOARD_INPUT: {
KIRQL currentIrql, cancelIrql;
// if detour is opened, key datum are forwarded to detour
if (irpSp->Parameters.DeviceIoControl.InputBufferLength %
sizeof(KEYBOARD_INPUT_DATA)) {
status = STATUS_INVALID_PARAMETER;
break;
}
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
KqEnque(&detourDevExt->readQue,
(KEYBOARD_INPUT_DATA *)irp->AssociatedIrp.SystemBuffer,
irpSp->Parameters.DeviceIoControl.InputBufferLength
/ sizeof(KEYBOARD_INPUT_DATA));
if (detourDevExt->irpq) {
if (readq(&detourDevExt->readQue, detourDevExt->irpq) ==
STATUS_SUCCESS) {
IoAcquireCancelSpinLock(&cancelIrql);
IoSetCancelRoutine(detourDevExt->irpq, NULL);
IoReleaseCancelSpinLock(cancelIrql);
IoCompleteRequest(detourDevExt->irpq, IO_KEYBOARD_INCREMENT);
detourDevExt->irpq = NULL;
}
}
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
status = STATUS_SUCCESS;
break;
}
default:
status = STATUS_INVALID_DEVICE_REQUEST;
break;
}
irp->IoStatus.Status = status;
if (status != STATUS_PENDING)
IoCompleteRequest(irp, IO_NO_INCREMENT);
return status;
}
#ifndef MAYUD_NT4
// detour IRP_MJ_POWER
NTSTATUS detourPower(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
UNREFERENCED_PARAMETER(deviceObject);
PoStartNextPowerIrp(irp);
irp->IoStatus.Status = STATUS_SUCCESS;
irp->IoStatus.Information = 0;
IoCompleteRequest(irp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
#endif // !MAYUD_NT4
// filter IRP_MJ_READ
NTSTATUS filterRead(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
NTSTATUS status;
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp);
FilterDeviceExtension *filterDevExt =
(FilterDeviceExtension*)deviceObject->DeviceExtension;
DetourDeviceExtension *detourDevExt =
(DetourDeviceExtension*)filterDevExt->detourDevObj->DeviceExtension;
KIRQL currentIrql;
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
if (detourDevExt->isOpen && !detourDevExt->wasCleanupInitiated)
// read from que
{
ULONG len = irpSp->Parameters.Read.Length;
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
irp->IoStatus.Information = 0;
KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql);
if (len == 0)
status = STATUS_SUCCESS;
else if (len % sizeof(KEYBOARD_INPUT_DATA))
status = STATUS_BUFFER_TOO_SMALL;
else
status = readq(&filterDevExt->readQue, irp);
KeReleaseSpinLock(&filterDevExt->lock, currentIrql);
if (status != STATUS_PENDING) {
irp->IoStatus.Status = status;
IoCompleteRequest(irp, IO_NO_INCREMENT);
return status;
}
} else {
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
}
KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql);
filterDevExt->irpq = irp;
KeReleaseSpinLock(&filterDevExt->lock, currentIrql);
*IoGetNextIrpStackLocation(irp) = *irpSp;
IoSetCompletionRoutine(irp, filterReadCompletion, NULL, TRUE, TRUE, TRUE);
return IoCallDriver(filterDevExt->kbdClassDevObj, irp);
}
// pass throught irp to keyboard class driver
NTSTATUS filterPassThrough(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
FilterDeviceExtension *filterDevExt =
(FilterDeviceExtension*)deviceObject->DeviceExtension;
*IoGetNextIrpStackLocation(irp) = *IoGetCurrentIrpStackLocation(irp);
IoSetCompletionRoutine(irp, filterGenericCompletion,
NULL, TRUE, TRUE, TRUE);
return IoCallDriver(filterDevExt->kbdClassDevObj, irp);
}
#ifndef MAYUD_NT4
// filter IRP_MJ_POWER
NTSTATUS filterPower(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
FilterDeviceExtension *filterDevExt =
(FilterDeviceExtension*)deviceObject->DeviceExtension;
PoStartNextPowerIrp(irp);
IoSkipCurrentIrpStackLocation(irp);
return PoCallDriver(filterDevExt->kbdClassDevObj, irp);
}
#endif // !MAYUD_NT4
NTSTATUS filterPnP(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp);
FilterDeviceExtension *filterDevExt =
(FilterDeviceExtension*)deviceObject->DeviceExtension;
DetourDeviceExtension *detourDevExt =
(DetourDeviceExtension*)filterDevExt->detourDevObj->DeviceExtension;
KIRQL currentIrql;
NTSTATUS status;
ULONG minor;
PIRP cancelIrp;
PDRIVER_OBJECT driverObject = deviceObject->DriverObject;
minor = irpSp->MinorFunction;
IoSkipCurrentIrpStackLocation(irp);
status = IoCallDriver(filterDevExt->kbdClassDevObj, irp);
DEBUG_LOG(("filterPnP: minor=%d(%x)", minor, minor));
switch (minor) {
case IRP_MN_SURPRISE_REMOVAL:
case IRP_MN_REMOVE_DEVICE:
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
if (detourDevExt->filterDevObj == deviceObject) {
PDEVICE_OBJECT devObj = deviceObject->DriverObject->DeviceObject;
DEBUG_LOG(("filterPnP: current filter(%x) was removed", deviceObject));
detourDevExt->filterDevObj = NULL;
while (devObj->NextDevice) {
if (devObj != deviceObject) {
detourDevExt->filterDevObj = devObj;
break;
}
devObj = devObj->NextDevice;
}
DEBUG_LOG(("filterPnP: current filter was changed to %x", detourDevExt->filterDevObj));
}
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
// detach
IoDetachDevice(filterDevExt->kbdClassDevObj);
KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql);
// TODO: at this point, the irp may be completed (but what can I do for it ?)
cancelIrp = filterDevExt->irpq;
KqFinalize(&filterDevExt->readQue);
KeReleaseSpinLock(&filterDevExt->lock, currentIrql);
if (cancelIrp) {
IoCancelIrp(cancelIrp);
}
IoDeleteDevice(deviceObject);
DEBUG_LOG(("delete filter device: %x", deviceObject));
DEBUG_LOGChain(driverObject);
break;
default:
break;
}
return status;
}
#ifdef USE_TOUCHPAD
//
NTSTATUS filterTouchpadCompletion(IN PDEVICE_OBJECT deviceObject,
IN PIRP irp, IN PVOID context)
{
KIRQL currentIrql;
FilterDeviceExtension *filterDevExt =
(FilterDeviceExtension*)deviceObject->DeviceExtension;
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp);
//PIO_STACK_LOCATION irpSp = IoGetNextIrpStackLocation(irp);
UCHAR *data = irp->UserBuffer;
UCHAR pressure;
UNREFERENCED_PARAMETER(context);
if (irp->PendingReturned)
IoMarkIrpPending(irp);
if (data)
pressure = data[TOUCHPAD_PRESSURE_OFFSET];
else
pressure = 0;
if (data) {
ULONG *p = (ULONG*)data;
//DEBUG_LOG(("UserBuffer: %2x %2x %2x %2x", data[4], data[5], data[6], data[7]));
//DEBUG_LOG(("UserBuffer: %x %x %x %x %x %x %x %x", p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]));
}
KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql);
if (filterDevExt->isTouched == FALSE && pressure) {
KIRQL currentIrql, cancelIrql;
PDEVICE_OBJECT detourDevObj = filterDevExt->detourDevObj;
DetourDeviceExtension *detourDevExt =
(DetourDeviceExtension*)detourDevObj->DeviceExtension;
if (detourDevExt->isOpen) {
KEYBOARD_INPUT_DATA PadKey = {0, TOUCHPAD_SCANCODE, 0, 0, 0};
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
// if detour is opened, key datum are forwarded to detour
KqEnque(&detourDevExt->readQue, &PadKey, 1);
detourDevExt->filterDevObj = deviceObject;
if (detourDevExt->irpq) {
if (readq(&detourDevExt->readQue, detourDevExt->irpq) ==
STATUS_SUCCESS) {
IoAcquireCancelSpinLock(&cancelIrql);
IoSetCancelRoutine(detourDevExt->irpq, NULL);
IoReleaseCancelSpinLock(cancelIrql);
IoCompleteRequest(detourDevExt->irpq, IO_KEYBOARD_INCREMENT);
detourDevExt->irpq = NULL;
}
}
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
}
filterDevExt->isTouched = TRUE;
} else {
if (filterDevExt->isTouched == TRUE && pressure == 0) {
KIRQL currentIrql, cancelIrql;
PDEVICE_OBJECT detourDevObj = filterDevExt->detourDevObj;
DetourDeviceExtension *detourDevExt =
(DetourDeviceExtension*)detourDevObj->DeviceExtension;
if (detourDevExt->isOpen) {
KEYBOARD_INPUT_DATA PadKey = {0, TOUCHPAD_SCANCODE, 1, 0, 0};
KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql);
// if detour is opened, key datum are forwarded to detour
KqEnque(&detourDevExt->readQue, &PadKey, 1);
detourDevExt->filterDevObj = deviceObject;
if (detourDevExt->irpq) {
if (readq(&detourDevExt->readQue, detourDevExt->irpq) ==
STATUS_SUCCESS) {
IoAcquireCancelSpinLock(&cancelIrql);
IoSetCancelRoutine(detourDevExt->irpq, NULL);
IoReleaseCancelSpinLock(cancelIrql);
IoCompleteRequest(detourDevExt->irpq, IO_KEYBOARD_INCREMENT);
detourDevExt->irpq = NULL;
}
}
KeReleaseSpinLock(&detourDevExt->lock, currentIrql);
}
filterDevExt->isTouched = FALSE;
}
}
//DEBUG_LOG(("touchpad pressed: out=%u in=%u code=%u status=%x SystemBuffer=%x UserBuffer=%x", irpSp->Parameters.DeviceIoControl.OutputBufferLength, irpSp->Parameters.DeviceIoControl.InputBufferLength, irpSp->Parameters.DeviceIoControl.IoControlCode, irp->IoStatus.Status, irp->AssociatedIrp.SystemBuffer, irp->UserBuffer));
KeReleaseSpinLock(&filterDevExt->lock, currentIrql);
return STATUS_SUCCESS;
}
// filter touchpad input
NTSTATUS filterTouchpad(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
FilterDeviceExtension *filterDevExt =
(FilterDeviceExtension*)deviceObject->DeviceExtension;
*IoGetNextIrpStackLocation(irp) = *IoGetCurrentIrpStackLocation(irp);
IoSetCompletionRoutine(irp, filterTouchpadCompletion,
NULL, TRUE, TRUE, TRUE);
return IoCallDriver(filterDevExt->kbdClassDevObj, irp);
}
#endif
NTSTATUS detourPnP(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
UNREFERENCED_PARAMETER(deviceObject);
IoSkipCurrentIrpStackLocation(irp);
irp->IoStatus.Status = STATUS_SUCCESS;
irp->IoStatus.Information = 0;
IoCompleteRequest(irp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
<file_sep>#ifndef MAYU_AFXRES_H
# define MAYU_AFXRES_H
# include "windows.h"
# define IDC_STATIC -1
#endif // !MAYU_AFXRES_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// dlgeditsetting.h
#ifndef _DLGEDITSETTING_H
# define _DLGEDITSETTING_H
# include "stringtool.h"
/// dialog procedure of "Edit Setting" dialog box
#ifdef MAYU64
INT_PTR CALLBACK dlgEditSetting_dlgProc(
#else
BOOL CALLBACK dlgEditSetting_dlgProc(
#endif
HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam);
/// parameters for "Edit Setting" dialog box
class DlgEditSettingData {
public:
tstringi m_name; /// setting name
tstringi m_filename; /// filename of setting
tstringi m_symbols; /// symbol list (-Dsymbol1;-Dsymbol2;-D...)
};
#endif // !_DLGEDITSETTING_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// stringtool.cpp
#include "stringtool.h"
#include "array.h"
#include <locale>
#include <malloc.h>
#include <mbstring.h>
/* ************************************************************************** *
STRLCPY(3) OpenBSD Programmer's Manual STRLCPY(3)
NAME
strlcpy, strlcat - size-bounded string copying and concatenation
SYNOPSIS
#include <string.h>
size_t
strlcpy(char *dst, const char *src, size_t size);
size_t
strlcat(char *dst, const char *src, size_t size);
DESCRIPTION
The strlcpy() and strlcat() functions copy and concatenate strings re-
spectively. They are designed to be safer, more consistent, and less er-
ror prone replacements for strncpy(3) and strncat(3). Unlike those func-
tions, strlcpy() and strlcat() take the full size of the buffer (not just
the length) and guarantee to NUL-terminate the result (as long as size is
larger than 0). Note that you should include a byte for the NUL in size.
The strlcpy() function copies up to size - 1 characters from the NUL-ter-
minated string src to dst, NUL-terminating the result.
The strlcat() function appends the NUL-terminated string src to the end
of dst. It will append at most size - strlen(dst) - 1 bytes, NUL-termi-
nating the result.
RETURN VALUES
The strlcpy() and strlcat() functions return the total length of the
string they tried to create. For strlcpy() that means the length of src.
For strlcat() that means the initial length of dst plus the length of
src. While this may seem somewhat confusing it was done to make trunca-
tion detection simple.
EXAMPLES
The following code fragment illustrates the simple case:
char *s, *p, buf[BUFSIZ];
...
(void)strlcpy(buf, s, sizeof(buf));
(void)strlcat(buf, p, sizeof(buf));
To detect truncation, perhaps while building a pathname, something like
the following might be used:
char *dir, *file, pname[MAXPATHNAMELEN];
...
if (strlcpy(pname, dir, sizeof(pname)) >= sizeof(pname))
goto toolong;
if (strlcat(pname, file, sizeof(pname)) >= sizeof(pname))
goto toolong;
Since we know how many characters we copied the first time, we can speed
things up a bit by using a copy instead on an append:
char *dir, *file, pname[MAXPATHNAMELEN];
size_t n;
...
n = strlcpy(pname, dir, sizeof(pname));
if (n >= sizeof(pname))
goto toolong;
if (strlcpy(pname + n, file, sizeof(pname) - n) >= sizeof(pname)-n)
goto toolong;
However, one may question the validity of such optimizations, as they de-
feat the whole purpose of strlcpy() and strlcat(). As a matter of fact,
the first version of this manual page got it wrong.
SEE ALSO
snprintf(3), strncat(3), strncpy(3)
OpenBSD 2.6 June 22, 1998 2
-------------------------------------------------------------------------------
Source: OpenBSD 2.6 man pages. Copyright: Portions are copyrighted by BERKELEY
SOFTWARE DESIGN, INC., The Regents of the University of California,
Massachusetts Institute of Technology, Free Software Foundation, FreeBSD Inc.,
and others.
* ************************************************************************** */
// copy
template <class T>
static inline size_t xstrlcpy(T *o_dest, const T *i_src, size_t i_destSize)
{
T *d = o_dest;
const T *s = i_src;
size_t n = i_destSize;
ASSERT( o_dest != NULL );
ASSERT( i_src != NULL );
// Copy as many bytes as will fit
if (n != 0 && --n != 0) {
do {
if ((*d++ = *s++) == 0)
break;
} while (--n != 0);
}
// Not enough room in o_dest, add NUL and traverse rest of i_src
if (n == 0) {
if (i_destSize != 0)
*d = T(); // NUL-terminate o_dest
while (*s++)
;
}
return (s - i_src - 1); // count does not include NUL
}
// copy
size_t strlcpy(char *o_dest, const char *i_src, size_t i_destSize)
{
return xstrlcpy(o_dest, i_src, i_destSize);
}
// copy
size_t wcslcpy(wchar_t *o_dest, const wchar_t *i_src, size_t i_destSize)
{
return xstrlcpy(o_dest, i_src, i_destSize);
}
// copy
size_t mbslcpy(unsigned char *o_dest, const unsigned char *i_src,
size_t i_destSize)
{
unsigned char *d = o_dest;
const unsigned char *s = i_src;
size_t n = i_destSize;
ASSERT( o_dest != NULL );
ASSERT( i_src != NULL );
if (n == 0)
return strlen(reinterpret_cast<const char *>(i_src));
// Copy as many bytes as will fit
for (-- n; *s && 0 < n; -- n) {
if (_ismbblead(*s)) {
if (!(s[1] && 2 <= n))
break;
*d++ = *s++;
-- n;
}
*d++ = *s++;
}
*d = '\0';
for (; *s; ++ s)
;
return s - i_src;
}
/// stream output
tostream &operator<<(tostream &i_ost, const tstringq &i_data)
{
i_ost << _T("\"");
for (const _TCHAR *s = i_data.c_str(); *s; ++ s) {
switch (*s) {
case _T('\a'):
i_ost << _T("\\a");
break;
case _T('\f'):
i_ost << _T("\\f");
break;
case _T('\n'):
i_ost << _T("\\n");
break;
case _T('\r'):
i_ost << _T("\\r");
break;
case _T('\t'):
i_ost << _T("\\t");
break;
case _T('\v'):
i_ost << _T("\\v");
break;
case _T('"'):
i_ost << _T("\\\"");
break;
default:
if (_istlead(*s)) {
_TCHAR buf[3] = { s[0], s[1], 0 };
i_ost << buf;
++ s;
} else if (_istprint(*s)) {
_TCHAR buf[2] = { *s, 0 };
i_ost << buf;
} else {
i_ost << _T("\\x");
_TCHAR buf[5];
#ifdef _UNICODE
_sntprintf(buf, NUMBER_OF(buf), _T("%04x"), *s);
#else
_sntprintf(buf, NUMBER_OF(buf), _T("%02x"), *s);
#endif
i_ost << buf;
}
break;
}
}
i_ost << _T("\"");
return i_ost;
}
// interpret meta characters such as \n
tstring interpretMetaCharacters(const _TCHAR *i_str, size_t i_len,
const _TCHAR *i_quote,
bool i_doesUseRegexpBackReference)
{
// interpreted string is always less than i_len
Array<_TCHAR> result(i_len + 1);
// destination
_TCHAR *d = result.get();
// end pointer
const _TCHAR *end = i_str + i_len;
while (i_str < end && *i_str) {
if (*i_str != _T('\\')) {
if (_istlead(*i_str) && *(i_str + 1) && i_str + 1 < end)
*d++ = *i_str++;
*d++ = *i_str++;
} else if (*(i_str + 1) != _T('\0')) {
i_str ++;
if (i_quote && _tcschr(i_quote, *i_str))
*d++ = *i_str++;
else
switch (*i_str) {
case _T('a'):
*d++ = _T('\x07');
i_str ++;
break;
//case _T('b'): *d++ = _T('\b'); i_str ++; break;
case _T('e'):
*d++ = _T('\x1b');
i_str ++;
break;
case _T('f'):
*d++ = _T('\f');
i_str ++;
break;
case _T('n'):
*d++ = _T('\n');
i_str ++;
break;
case _T('r'):
*d++ = _T('\r');
i_str ++;
break;
case _T('t'):
*d++ = _T('\t');
i_str ++;
break;
case _T('v'):
*d++ = _T('\v');
i_str ++;
break;
//case _T('?'): *d++ = _T('\x7f'); i_str ++; break;
//case _T('_'): *d++ = _T(' '); i_str ++; break;
//case _T('\\'): *d++ = _T('\\'); i_str ++; break;
case _T('\''):
*d++ = _T('\'');
i_str ++;
break;
case _T('"'):
*d++ = _T('"');
i_str ++;
break;
case _T('\\'):
*d++ = _T('\\');
i_str ++;
break;
case _T('c'): // control code, for example '\c[' is escape: '\x1b'
i_str ++;
if (i_str < end && *i_str) {
static const _TCHAR *ctrlchar =
_T("@ABCDEFGHIJKLMNO")
_T("PQRSTUVWXYZ[\\]^_")
_T("@abcdefghijklmno")
_T("pqrstuvwxyz@@@@?");
static const _TCHAR *ctrlcode =
_T("\00\01\02\03\04\05\06\07\10\11\12\13\14\15\16\17")
_T("\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37")
_T("\00\01\02\03\04\05\06\07\10\11\12\13\14\15\16\17")
_T("\20\21\22\23\24\25\26\27\30\31\32\00\00\00\00\177");
if (const _TCHAR *c = _tcschr(ctrlchar, *i_str))
*d++ = ctrlcode[c - ctrlchar], i_str ++;
}
break;
case _T('x'):
case _T('X'): {
i_str ++;
static const _TCHAR *hexchar = _T("0123456789ABCDEFabcdef");
static int hexvalue[] = { 0, 1, 2, 3, 4, 5 ,6, 7, 8, 9,
10, 11, 12, 13, 14, 15,
10, 11, 12, 13, 14, 15,
};
bool brace = false;
if (i_str < end && *i_str == _T('{')) {
i_str ++;
brace = true;
}
int n = 0;
for (; i_str < end && *i_str; i_str ++)
if (const _TCHAR *c = _tcschr(hexchar, *i_str))
n = n * 16 + hexvalue[c - hexchar];
else
break;
if (i_str < end && *i_str == _T('}') && brace)
i_str ++;
if (0 < n)
*d++ = static_cast<_TCHAR>(n);
break;
}
case _T('1'):
case _T('2'):
case _T('3'):
case _T('4'):
case _T('5'):
case _T('6'):
case _T('7'):
if (i_doesUseRegexpBackReference)
goto case_default;
// fall through
case _T('0'): {
static const _TCHAR *octalchar = _T("01234567");
static int octalvalue[] = { 0, 1, 2, 3, 4, 5 ,6, 7, };
int n = 0;
for (; i_str < end && *i_str; i_str ++)
if (const _TCHAR *c = _tcschr(octalchar, *i_str))
n = n * 8 + octalvalue[c - octalchar];
else
break;
if (0 < n)
*d++ = static_cast<_TCHAR>(n);
break;
}
default:
case_default:
*d++ = _T('\\');
if (_istlead(*i_str) && *(i_str + 1) && i_str + 1 < end)
*d++ = *i_str++;
*d++ = *i_str++;
break;
}
}
}
*d =_T('\0');
return result.get();
}
// add session id to i_str
tstring addSessionId(const _TCHAR *i_str)
{
DWORD sessionId;
tstring s(i_str);
if (ProcessIdToSessionId(GetCurrentProcessId(), &sessionId)) {
_TCHAR buf[20];
_sntprintf(buf, NUMBER_OF(buf), _T("%u"), sessionId);
s += buf;
}
return s;
}
#ifdef _MBCS
// escape regexp special characters in MBCS trail bytes
std::string guardRegexpFromMbcs(const char *i_str)
{
size_t len = strlen(i_str);
Array<char> buf(len * 2 + 1);
char *p = buf.get();
while (*i_str) {
if (_ismbblead(static_cast<u_char>(*i_str)) && i_str[1]) {
*p ++ = *i_str ++;
if (strchr(".*?+(){}[]^$", *i_str))
*p ++ = '\\';
}
*p ++ = *i_str ++;
}
return std::string(buf.get(), p);
}
#endif // !_MBCS
// converter
std::wstring to_wstring(const std::string &i_str)
{
size_t size = mbstowcs(NULL, i_str.c_str(), i_str.size() + 1);
if (size == (size_t)-1)
return std::wstring();
Array<wchar_t> result(size + 1);
mbstowcs(result.get(), i_str.c_str(), i_str.size() + 1);
return std::wstring(result.get());
}
// converter
std::string to_string(const std::wstring &i_str)
{
size_t size = wcstombs(NULL, i_str.c_str(), i_str.size() + 1);
if (size == (size_t)-1)
return std::string();
Array<char> result(size + 1);
wcstombs(result.get(), i_str.c_str(), i_str.size() + 1);
return std::string(result.get());
}
/// stream output
tostream &operator<<(tostream &i_ost, const tregex &i_data)
{
return i_ost << i_data.str();
}
/// get lower string
tstring toLower(const tstring &i_str)
{
tstring str(i_str);
for (size_t i = 0; i < str.size(); ++ i) {
if (_ismbblead(str[i]))
++ i;
else
str[i] = tolower(str[i]);
}
return str;
}
// convert wstring to UTF-8
std::string to_UTF_8(const std::wstring &i_str)
{
// 0xxxxxxx: 00-7F
// 110xxxxx 10xxxxxx: 0080-07FF
// 1110xxxx 10xxxxxx 10xxxxxx: 0800 - FFFF
int size = 0;
// count needed buffer size
for (std::wstring::const_iterator i = i_str.begin(); i != i_str.end(); ++ i) {
if (0x0000 <= *i && *i <= 0x007f)
size += 1;
else if (0x0080 <= *i && *i <= 0x07ff)
size += 2;
else if (0x0800 <= *i && *i <= 0xffff)
size += 3;
}
Array<char> result(size);
int ri = 0;
// make UTF-8
for (std::wstring::const_iterator i = i_str.begin(); i != i_str.end(); ++ i) {
if (0x0000 <= *i && *i <= 0x007f)
result[ri ++] = static_cast<char>(*i);
else if (0x0080 <= *i && *i <= 0x07ff) {
result[ri ++] = static_cast<char>(((*i & 0x0fc0) >> 6) | 0xc0);
result[ri ++] = static_cast<char>(( *i & 0x003f ) | 0x80);
} else if (0x0800 <= *i && *i <= 0xffff) {
result[ri ++] = static_cast<char>(((*i & 0xf000) >> 12) | 0xe0);
result[ri ++] = static_cast<char>(((*i & 0x0fc0) >> 6) | 0x80);
result[ri ++] = static_cast<char>(( *i & 0x003f ) | 0x80);
}
}
return std::string(result.begin(), result.end());
}
<file_sep>#include <list>
#include <windows.h>
#include "registry.h"
typedef HMODULE (WINAPI *FpGetModuleHandleW)(LPCWSTR);
typedef FARPROC (WINAPI *FpGetProcAddress)(HMODULE, LPCSTR);
typedef BOOL (WINAPI *FpUpdatePerUserSystemParameters4)(BOOL);
typedef BOOL (WINAPI *FpUpdatePerUserSystemParameters8)(DWORD, BOOL);
typedef HANDLE (WINAPI *FpOpenProcess)(DWORD, BOOL, DWORD);
typedef BOOL (WINAPI *FpOpenProcessToken)(HANDLE, DWORD, PHANDLE);
typedef BOOL (WINAPI *FpImpersonateLoggedOnUser)(HANDLE);
typedef BOOL (WINAPI *FpRevertToSelf)(VOID);
typedef BOOL (WINAPI *FpCloseHandle)(HANDLE);
typedef struct {
DWORD isVistaOrLater_;
DWORD pid_;
TCHAR advapi32_[64];
CHAR impersonateLoggedOnUser_[32];
CHAR revertToSelf_[32];
CHAR openProcessToken_[32];
FpGetModuleHandleW pGetModuleHandle;
FpGetProcAddress pGetProcAddress;
FpUpdatePerUserSystemParameters4 pUpdate4;
FpUpdatePerUserSystemParameters8 pUpdate8;
FpOpenProcess pOpenProcess;
FpCloseHandle pCloseHandle;
} InjectInfo;
class FixScancodeMap {
private:
typedef struct {
DWORD header1;
DWORD header2;
DWORD count;
DWORD entry[1];
} ScancodeMap;
typedef struct {
HANDLE m_hProcess;
LPVOID m_remoteMem;
LPVOID m_remoteInfo;
HANDLE m_hThread;
} WlInfo;
private:
static const DWORD s_fixEntryNum;
static const DWORD s_fixEntry[];
private:
HWND m_hwnd;
UINT m_messageOnFail;
int m_errorOnConstruct;
DWORD m_winlogonPid;
std::list<WlInfo> m_wlTrash;
InjectInfo m_info;
Registry m_regHKCU;
Registry m_regHKLM;
Registry *m_pReg;
HANDLE m_hFixEvent;
HANDLE m_hRestoreEvent;
HANDLE m_hQuitEvent;
HANDLE m_hThread;
unsigned m_threadId;
private:
int acquirePrivileges();
DWORD getWinLogonPid();
static bool clean(WlInfo wl);
int injectThread(DWORD dwPID);
int update();
int fix();
int restore();
static unsigned int WINAPI threadLoop(void *i_this);
public:
FixScancodeMap();
~FixScancodeMap();
int init(HWND i_hwnd, UINT i_messageOnFail);
int escape(bool i_escape);
};
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// parser.h
#ifndef _PARSER_H
# define _PARSER_H
# include "misc.h"
# include "stringtool.h"
# include <vector>
///
class Token
{
public:
///
enum Type {
Type_string, ///
Type_number, ///
Type_regexp, ///
Type_openParen, ///
Type_closeParen, ///
Type_comma, ///
};
private:
u_char m_type; ///
bool m_isValueQuoted; ///
int m_numericValue; ///
tstringi m_stringValue; ///
long m_data; ///
public:
///
Token(const Token &i_token);
///
Token(int i_value, const tstringi &i_display);
///
Token(const tstringi &i_value, bool i_isValueQuoted,
bool i_isRegexp = false);
///
Token(Type i_type);
/// is the value quoted ?
bool isQuoted() const {
return m_isValueQuoted;
}
/// value type
Type getType() const {
return static_cast<Type>(m_type);
}
///
bool isString() const {
return m_type == Type_string;
}
///
bool isNumber() const {
return m_type == Type_number;
}
///
bool isRegexp() const {
return m_type == Type_regexp;
}
///
bool isOpenParen() const {
return m_type == Type_openParen;
}
///
bool isCloseParen() const {
return m_type == Type_closeParen;
}
///
bool isComma() const {
return m_type == Type_comma;
}
/// get numeric value
int getNumber() const;
/// get string value
tstringi getString() const;
/// get regexp value
tstringi getRegexp() const;
/// get data
long getData() const {
return m_data;
}
///
void setData(long i_data) {
m_data = i_data;
}
/// case insensitive equal
bool operator==(const tstringi &i_str) const {
return *this == i_str.c_str();
}
///
bool operator==(const _TCHAR *i_str) const;
///
bool operator!=(const tstringi &i_str) const {
return *this != i_str.c_str();
}
///
bool operator!=(const _TCHAR *i_str) const {
return !(*this == i_str);
}
/** paren equal
@param i_c '<code>(</code>' or '<code>)</code>' */
bool operator==(const _TCHAR i_c) const;
/** paren equal
@param i_c '<code>(</code>' or '<code>)</code>' */
bool operator!=(const _TCHAR i_c) const {
return !(*this == i_c);
}
/// add string
void add(const tstringi &i_str);
/// stream output
friend tostream &operator<<(tostream &i_ost, const Token &i_token);
};
///
class Parser
{
public:
///
typedef std::vector<Token> Tokens;
private:
///
typedef std::vector<tstringi> Prefixes;
private:
size_t m_lineNumber; /// current line number
const Prefixes *m_prefixes; /** string that may be prefix
of a token */
size_t m_internalLineNumber; /// next line number
const _TCHAR *m_ptr; /// read pointer
const _TCHAR *m_end; /// end pointer
private:
/// get a line
bool getLine(tstringi *o_line);
public:
///
Parser(const _TCHAR *i_str, size_t i_length);
/** get a parsed line. if no more lines exist, returns false */
bool getLine(Tokens *o_tokens);
/// get current line number
size_t getLineNumber() const {
return m_lineNumber;
}
/** set string that may be prefix of a token. prefix_ is not
copied, so it must be preserved after setPrefix() */
void setPrefixes(const Prefixes *m_prefixes);
};
#endif // !_PARSER_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// dlgsetting.cpp
#include "misc.h"
#include "mayu.h"
#include "mayurc.h"
#include "registry.h"
#include "stringtool.h"
#include "windowstool.h"
#include "setting.h"
#include "dlgeditsetting.h"
#include "layoutmanager.h"
#include <commctrl.h>
#include <windowsx.h>
///
class DlgSetting : public LayoutManager
{
HWND m_hwndMayuPaths; ///
///
Registry m_reg;
typedef DlgEditSettingData Data; ///
///
void insertItem(int i_index, const Data &i_data) {
LVITEM item;
item.mask = LVIF_TEXT;
item.iItem = i_index;
item.iSubItem = 0;
item.pszText = const_cast<_TCHAR *>(i_data.m_name.c_str());
CHECK_TRUE( ListView_InsertItem(m_hwndMayuPaths, &item) != -1 );
ListView_SetItemText(m_hwndMayuPaths, i_index, 1,
const_cast<_TCHAR *>(i_data.m_filename.c_str()));
ListView_SetItemText(m_hwndMayuPaths, i_index, 2,
const_cast<_TCHAR *>(i_data.m_symbols.c_str()));
}
///
void setItem(int i_index, const Data &i_data) {
ListView_SetItemText(m_hwndMayuPaths, i_index, 0,
const_cast<_TCHAR *>(i_data.m_name.c_str()));
ListView_SetItemText(m_hwndMayuPaths, i_index, 1,
const_cast<_TCHAR *>(i_data.m_filename.c_str()));
ListView_SetItemText(m_hwndMayuPaths, i_index, 2,
const_cast<_TCHAR *>(i_data.m_symbols.c_str()));
}
///
void getItem(int i_index, Data *o_data) {
_TCHAR buf[GANA_MAX_PATH];
LVITEM item;
item.mask = LVIF_TEXT;
item.iItem = i_index;
item.pszText = buf;
item.cchTextMax = NUMBER_OF(buf);
item.iSubItem = 0;
CHECK_TRUE( ListView_GetItem(m_hwndMayuPaths, &item) );
o_data->m_name = item.pszText;
item.iSubItem = 1;
CHECK_TRUE( ListView_GetItem(m_hwndMayuPaths, &item) );
o_data->m_filename = item.pszText;
item.iSubItem = 2;
CHECK_TRUE( ListView_GetItem(m_hwndMayuPaths, &item) );
o_data->m_symbols = item.pszText;
}
///
void setSelectedItem(int i_index) {
ListView_SetItemState(m_hwndMayuPaths, i_index,
LVIS_SELECTED, LVIS_SELECTED);
}
///
int getSelectedItem() {
if (ListView_GetSelectedCount(m_hwndMayuPaths) == 0)
return -1;
for (int i = 0; ; ++ i) {
if (ListView_GetItemState(m_hwndMayuPaths, i, LVIS_SELECTED))
return i;
}
}
public:
///
DlgSetting(HWND i_hwnd)
: LayoutManager(i_hwnd),
m_hwndMayuPaths(NULL),
m_reg(MAYU_REGISTRY_ROOT) {
}
/// WM_INITDIALOG
BOOL wmInitDialog(HWND /* i_focus */, LPARAM /* i_lParam */) {
setSmallIcon(m_hwnd, IDI_ICON_mayu);
setBigIcon(m_hwnd, IDI_ICON_mayu);
CHECK_TRUE( m_hwndMayuPaths = GetDlgItem(m_hwnd, IDC_LIST_mayuPaths) );
// create list view colmn
RECT rc;
GetClientRect(m_hwndMayuPaths, &rc);
LVCOLUMN lvc;
lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT;
lvc.fmt = LVCFMT_LEFT;
lvc.cx = (rc.right - rc.left) / 3;
tstringi str = loadString(IDS_mayuPathName);
lvc.pszText = const_cast<_TCHAR *>(str.c_str());
CHECK( 0 ==, ListView_InsertColumn(m_hwndMayuPaths, 0, &lvc) );
str = loadString(IDS_mayuPath);
lvc.pszText = const_cast<_TCHAR *>(str.c_str());
CHECK( 1 ==, ListView_InsertColumn(m_hwndMayuPaths, 1, &lvc) );
str = loadString(IDS_mayuSymbols);
lvc.pszText = const_cast<_TCHAR *>(str.c_str());
CHECK( 2 ==, ListView_InsertColumn(m_hwndMayuPaths, 2, &lvc) );
Data data;
insertItem(0, data); // TODO: why ?
// set list view
tregex split(_T("^([^;]*);([^;]*);(.*)$"));
tstringi dot_mayu;
int i;
for (i = 0; i < MAX_MAYU_REGISTRY_ENTRIES; ++ i) {
_TCHAR buf[100];
_sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), i);
if (!m_reg.read(buf, &dot_mayu))
break;
tsmatch what;
if (boost::regex_match(dot_mayu, what, split)) {
data.m_name = what.str(1);
data.m_filename = what.str(2);
data.m_symbols = what.str(3);
insertItem(i, data);
}
}
CHECK_TRUE( ListView_DeleteItem(m_hwndMayuPaths, i) ); // TODO: why ?
// arrange list view size
ListView_SetColumnWidth(m_hwndMayuPaths, 0, LVSCW_AUTOSIZE);
ListView_SetColumnWidth(m_hwndMayuPaths, 1, LVSCW_AUTOSIZE);
ListView_SetColumnWidth(m_hwndMayuPaths, 2, LVSCW_AUTOSIZE);
ListView_SetExtendedListViewStyle(m_hwndMayuPaths, LVS_EX_FULLROWSELECT);
// set selection
int index;
m_reg.read(_T(".mayuIndex"), &index, 0);
setSelectedItem(index);
// set layout manager
typedef LayoutManager LM;
addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuPaths),
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_BOTTOM_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_LIST_mayuPaths),
LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE,
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_BOTTOM_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_BUTTON_up),
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_CENTER,
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_CENTER);
addItem(GetDlgItem(m_hwnd, IDC_BUTTON_down),
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_CENTER,
LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_CENTER);
addItem(GetDlgItem(m_hwnd, IDC_BUTTON_add),
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE,
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_BUTTON_edit),
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE,
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE);
addItem(GetDlgItem(m_hwnd, IDC_BUTTON_delete),
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE,
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE);
addItem(GetDlgItem(m_hwnd, IDCANCEL),
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE,
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE);
addItem(GetDlgItem(m_hwnd, IDOK),
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE,
LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE);
restrictSmallestSize();
return TRUE;
}
/// WM_CLOSE
BOOL wmClose() {
EndDialog(m_hwnd, 0);
return TRUE;
}
/// WM_NOTIFY
BOOL wmNotify(int i_id, NMHDR *i_nmh) {
switch (i_id) {
case IDC_LIST_mayuPaths:
if (i_nmh->code == NM_DBLCLK)
FORWARD_WM_COMMAND(m_hwnd, IDC_BUTTON_edit, NULL, 0, SendMessage);
return TRUE;
}
return TRUE;
}
/// WM_COMMAND
BOOL wmCommand(int /* i_notifyCode */, int i_id, HWND /* i_hwndControl */) {
_TCHAR buf[GANA_MAX_PATH];
switch (i_id) {
case IDC_BUTTON_up:
case IDC_BUTTON_down: {
int count = ListView_GetItemCount(m_hwndMayuPaths);
if (count < 2)
return TRUE;
int index = getSelectedItem();
if (index < 0 ||
(i_id == IDC_BUTTON_up && index == 0) ||
(i_id == IDC_BUTTON_down && index == count - 1))
return TRUE;
int target = (i_id == IDC_BUTTON_up) ? index - 1 : index + 1;
Data dataIndex, dataTarget;
getItem(index, &dataIndex);
getItem(target, &dataTarget);
setItem(index, dataTarget);
setItem(target, dataIndex);
setSelectedItem(target);
return TRUE;
}
case IDC_BUTTON_add: {
Data data;
int index = getSelectedItem();
if (0 <= index)
getItem(index, &data);
if (DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_editSetting),
m_hwnd, dlgEditSetting_dlgProc, (LPARAM)&data))
if (!data.m_name.empty()) {
insertItem(0, data);
setSelectedItem(0);
}
return TRUE;
}
case IDC_BUTTON_delete: {
int index = getSelectedItem();
if (0 <= index) {
CHECK_TRUE( ListView_DeleteItem(m_hwndMayuPaths, index) );
int count = ListView_GetItemCount(m_hwndMayuPaths);
if (count == 0)
;
else if (count == index)
setSelectedItem(index - 1);
else
setSelectedItem(index);
}
return TRUE;
}
case IDC_BUTTON_edit: {
Data data;
int index = getSelectedItem();
if (index < 0)
return TRUE;
getItem(index, &data);
if (DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_editSetting),
m_hwnd, dlgEditSetting_dlgProc, (LPARAM)&data)) {
setItem(index, data);
setSelectedItem(index);
}
return TRUE;
}
case IDOK: {
int count = ListView_GetItemCount(m_hwndMayuPaths);
int index;
for (index = 0; index < count; ++ index) {
_sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index);
Data data;
getItem(index, &data);
m_reg.write(buf, data.m_name + _T(";") +
data.m_filename + _T(";") + data.m_symbols);
}
for (; ; ++ index) {
_sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index);
if (!m_reg.remove(buf))
break;
}
index = getSelectedItem();
if (index < 0)
index = 0;
m_reg.write(_T(".mayuIndex"), index);
EndDialog(m_hwnd, 1);
return TRUE;
}
case IDCANCEL: {
CHECK_TRUE( EndDialog(m_hwnd, 0) );
return TRUE;
}
}
return FALSE;
}
};
//
#ifdef MAYU64
INT_PTR CALLBACK dlgSetting_dlgProc(
#else
BOOL CALLBACK dlgSetting_dlgProc(
#endif
HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam)
{
DlgSetting *wc;
getUserData(i_hwnd, &wc);
if (!wc)
switch (i_message) {
case WM_INITDIALOG:
wc = setUserData(i_hwnd, new DlgSetting(i_hwnd));
return wc->wmInitDialog(reinterpret_cast<HWND>(i_wParam), i_lParam);
}
else
switch (i_message) {
case WM_COMMAND:
return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam),
reinterpret_cast<HWND>(i_lParam));
case WM_CLOSE:
return wc->wmClose();
case WM_NCDESTROY:
delete wc;
return TRUE;
case WM_NOTIFY:
return wc->wmNotify(static_cast<int>(i_wParam),
reinterpret_cast<NMHDR *>(i_lParam));
default:
return wc->defaultWMHandler(i_message, i_wParam, i_lParam);
}
return FALSE;
}
<file_sep>############################################################## -*- Makefile -*-
#
# Makefile for setup
#
###############################################################################
!if "$(TARGETOS)" == "WINNT"
OS_SPECIFIC_DEFINES = -DUNICODE -D_UNICODE
DISTRIB_OS = nt
!endif
!if "$(TARGETOS)" == "WIN95"
OS_SPECIFIC_DEFINES = -D_MBCS
DISTRIB_OS = 9x
!endif
!if "$(TARGETOS)" == "BOTH"
!error Must specify TARGETOS=WIN95 or TARGETOS=WINNT
!endif
DEFINES = -DSTRICT -D_WIN32_IE=0x0400 $(OS_SPECIFIC_DEFINES) \
$(DEBUGDEFINES)
BOOST_DIR = ../../boost_$(BOOST_VER)_0
# setup.exe ###############################################################
TARGET_1 = $(OUT_DIR)\setup.exe
OBJS_1 = \
$(OUT_DIR)\setup.obj \
$(OUT_DIR)\installer.obj \
..\$(OUT_DIR)\registry.obj \
..\$(OUT_DIR)\stringtool.obj \
..\$(OUT_DIR)\windowstool.obj \
SRCS_1 = \
setup.cpp \
installer.cpp \
..\registry.cpp \
..\stringtool.cpp \
..\windowstool.cpp \
RES_1 = $(OUT_DIR)\setup.res
LIBS_1 = $(guixlibsmt) shell32.lib ole32.lib uuid.lib
# tools ###############################################################
MAKEDEPEND = perl ../tools/makedepend -o.obj
# rules ###############################################################
all: $(OUT_DIR) $(TARGET_1)
$(OUT_DIR):
if not exist "$(OUT_DIR)\\" $(MKDIR) $(OUT_DIR)
setup.cpp: strres.h
clean:
-$(RM) $(TARGET_1) strres.h
-$(RM) $(OUT_DIR)\*.obj $(OUT_DIR)\*.res $(OUT_DIR)\*.pdb *.pdb
-$(RM) *~ $(CLEAN)
-$(RMDIR) $(OUT_DIR)
depend::
$(MAKEDEPEND) -fsetup-common.mak \
-- $(DEPENDFLAGS) -- $(SRCS_1)
# DO NOT DELETE
$(OUT_DIR)\setup.obj: ../compiler_specific.h ../mayu.h ../misc.h \
../registry.h ../stringtool.h ../windowstool.h installer.h setuprc.h \
strres.h
$(OUT_DIR)\installer.obj: ../compiler_specific.h ../misc.h ../registry.h \
../stringtool.h ../windowstool.h installer.h
$(OUT_DIR)\..\registry.obj: ../compiler_specific.h ../misc.h \
../registry.cpp ../registry.h ../stringtool.h
$(OUT_DIR)\..\stringtool.obj: ../compiler_specific.h ../misc.h \
../stringtool.cpp ../stringtool.h
$(OUT_DIR)\..\windowstool.obj: ../compiler_specific.h ../misc.h \
../stringtool.h ../windowstool.cpp ../windowstool.h
<file_sep>############################################################## -*- Makefile -*-
#
# Makefile for mayu
#
###############################################################################
!if "$(VERSION)" == ""
VERSION = 0.02
!endif
!if "$(TARGETOS)" == "WINNT"
OS_SPECIFIC_DEFINES = -DUNICODE -D_UNICODE
DISTRIB_OS = xp
!endif
!if "$(TARGETOS)" == "WIN95"
OS_SPECIFIC_DEFINES = -D_MBCS
DISTRIB_OS = 9x
!endif
!if "$(TARGETOS)" == "BOTH"
!error You must specify TARGETOS=WINNT
!endif
COMMON_DEFINES = -DSTRICT -D_WIN32_IE=0x0500 $(OS_SPECIFIC_DEFINES)
BOOST_DIR = ../boost_$(BOOST_VER)_0($(MAYU_ARCH))
# yamy ###############################################################
TARGET_1 = $(OUT_DIR_EXE)\yamy$(MAYU_ARCH)
OBJS_1 = \
$(OUT_DIR)\compiler_specific_func.obj \
$(OUT_DIR)\dlgeditsetting.obj \
$(OUT_DIR)\dlginvestigate.obj \
$(OUT_DIR)\dlglog.obj \
$(OUT_DIR)\dlgsetting.obj \
$(OUT_DIR)\dlgversion.obj \
$(OUT_DIR)\engine.obj \
$(OUT_DIR)\focus.obj \
$(OUT_DIR)\function.obj \
$(OUT_DIR)\keyboard.obj \
$(OUT_DIR)\keymap.obj \
$(OUT_DIR)\layoutmanager.obj \
$(OUT_DIR)\mayu.obj \
$(OUT_DIR)\parser.obj \
$(OUT_DIR)\registry.obj \
$(OUT_DIR)\setting.obj \
$(OUT_DIR)\stringtool.obj \
$(OUT_DIR)\target.obj \
$(OUT_DIR)\vkeytable.obj \
$(OUT_DIR)\windowstool.obj \
SRCS_1 = \
compiler_specific_func.cpp \
dlgeditsetting.cpp \
dlginvestigate.cpp \
dlglog.cpp \
dlgsetting.cpp \
dlgversion.cpp \
engine.cpp \
focus.cpp \
function.cpp \
keyboard.cpp \
keymap.cpp \
layoutmanager.cpp \
mayu.cpp \
parser.cpp \
registry.cpp \
setting.cpp \
stringtool.cpp \
target.cpp \
vkeytable.cpp \
windowstool.cpp \
RES_1 = $(OUT_DIR)\mayu.res
LIBS_1 = \
$(guixlibsmt) \
shell32.lib \
comctl32.lib \
wtsapi32.lib \
$(OUT_DIR_EXE)\yamy$(MAYU_ARCH).lib \
EXTRADEP_1 = $(OUT_DIR_EXE)\yamy$(MAYU_ARCH).lib
# yamy.dll ###############################################################
TARGET_2 = $(OUT_DIR_EXE)\yamy$(MAYU_ARCH).dll
OBJS_2 = $(OUT_DIR)\hook.obj $(OUT_DIR)\stringtool.obj
SRCS_2 = hook.cpp stringtool.cpp
LIBS_2 = $(guixlibsmt) imm32.lib
# yamy.lib ###############################################################
TARGET_3 = $(OUT_DIR_EXE)\yamy$(MAYU_ARCH).lib
DLL_3 = $(OUT_DIR_EXE)\yamy$(MAYU_ARCH).dll
# yamyd ###############################################################
!if "$(MAYU_ARCH)" == "32"
TARGET_4 = $(OUT_DIR_EXE)\yamyd$(MAYU_ARCH)
OBJS_4 = $(OUT_DIR)\yamyd.obj
SRCS_4 = yamyd.cpp
LIBS_4 = user32.lib $(OUT_DIR_EXE)\yamy$(MAYU_ARCH).lib
EXTRADEP_4 = $(OUT_DIR_EXE)\yamy$(MAYU_ARCH).lib
!endif
# yamy.exe ###############################################################
!if "$(MAYU_ARCH)" == "32"
TARGET_5 = $(OUT_DIR_EXE)\yamy.exe
OBJS_5 = $(OUT_DIR)\yamy.obj
SRCS_5 = yamy.cpp
LIBS_5 = user32.lib
RES_5 = $(OUT_DIR)\mayu.res
!endif
# distribution ###############################################################
DISTRIB_SETTINGS = \
104.mayu \
104on109.mayu \
109.mayu \
109on104.mayu \
default.mayu \
emacsedit.mayu \
dot.mayu \
DISTRIB_MANUAL = \
doc\banner-ja.gif \
doc\CONTENTS-ja.html \
doc\CUSTOMIZE-ja.html \
doc\edit-setting-ja.png \
doc\investigate-ja.png \
doc\log-ja.png \
doc\MANUAL-ja.html \
doc\menu-ja.png \
doc\pause-ja.png \
doc\README-ja.html \
doc\README.css \
doc\setting-ja.png \
doc\syntax.txt \
doc\target.png \
doc\version-ja.png \
mayu-mode.el \
DISTRIB_CONTRIBS = \
contrib\109onAX.mayu \
contrib\mayu-settings.txt \
contrib\dvorak.mayu \
contrib\dvorak109.mayu \
contrib\keitai.mayu \
contrib\ax.mayu \
contrib\98x1.mayu \
contrib\DVORAKon109.mayu \
!if "$(TARGETOS)" == "WINNT"
DISTRIB_DRIVER = \
d\i386\mayud.sys \
d\rescue\i386\mayudrsc.sys \
d\nt4\i386\mayudnt4.sys
!endif
!if "$(TARGETOS)" == "WIN95"
DISTRIB_DRIVER = d_win9x\mayud.vxd
!endif
DISTRIB = \
$(TARGET_1) \
$(TARGET_2) \
$(TARGET_4) \
$(TARGET_5) \
s\$(OUT_DIR)\setup.exe \
$(DISTRIB_SETTINGS) \
$(DISTRIB_MANUAL) \
$(DISTRIB_CONTRIBS) \
$(DISTRIB_DRIVER) \
# tools ###############################################################
IEXPRESS = iexpress
DOCXX = doc++.exe
MAKEDEPEND = perl tools/makedepend -o.obj
DOS2UNIX = perl tools/dos2unix
UNIX2DOS = perl tools/unix2dos
MAKEFUNC = perl tools/makefunc
GETCVSFILES = perl tools/getcvsfiles
GENIEXPRESS = perl tools/geniexpress
# rules ###############################################################
all: boost $(OUT_DIR) $(OUT_DIR_EXE) $(TARGET_1) $(TARGET_2) $(TARGET_3) $(TARGET_4) $(TARGET_5)
$(OUT_DIR):
if not exist "$(OUT_DIR)\\" $(MKDIR) $(OUT_DIR)
$(OUT_DIR_EXE):
if not exist "$(OUT_DIR_EXE)\\" $(MKDIR) $(OUT_DIR_EXE)
functions.h: engine.h tools/makefunc
$(MAKEFUNC) < engine.h > functions.h
clean::
-$(RM) $(TARGET_1) $(TARGET_2) $(TARGET_3) $(TARGET_4) $(TARGET_5)
-$(RM) $(OUT_DIR)\*.obj
-$(RM) $(OUT_DIR)\*.res $(OUT_DIR_EXE)\*.exp
-$(RM) mayu.aps mayu.opt $(OUT_DIR_EXE)\*.pdb
-$(RM) *~ $(CLEAN)
-$(RMDIR) $(OUT_DIR)
depend::
$(MAKEDEPEND) -fmayu-common.mak \
-- $(DEPENDFLAGS) -- $(SRCS_1) $(SRCS_2)
distrib:
-@echo "we need cygwin tool"
-rm -f yamy-$(VERSION).zip
zip yamy-$(VERSION).zip yamy.ini 104.mayu 109.mayu default.mayu emacsedit.mayu 104on109.mayu 109on104.mayu dot.mayu workaround.mayu workaround.reg readme.txt
cd $(OUT_DIR_EXE)
zip ../yamy-$(VERSION).zip yamy.exe yamy32 yamy64 yamy32.dll yamy64.dll yamyd32
cd ..
srcdesc::
@$(ECHO) USE DOC++ 3.4.4 OR HIGHER
$(DOCXX) *.h
# DO NOT DELETE
$(OUT_DIR)\compiler_specific_func.obj: compiler_specific.h \
compiler_specific_func.h misc.h stringtool.h
$(OUT_DIR)\dlgeditsetting.obj: compiler_specific.h dlgeditsetting.h \
layoutmanager.h mayurc.h misc.h stringtool.h windowstool.h
$(OUT_DIR)\dlginvestigate.obj: compiler_specific.h d\ioctl.h \
dlginvestigate.h driver.h engine.h focus.h function.h functions.h hook.h \
keyboard.h keymap.h mayurc.h misc.h msgstream.h multithread.h parser.h \
setting.h stringtool.h target.h vkeytable.h windowstool.h
$(OUT_DIR)\dlglog.obj: compiler_specific.h dlglog.h layoutmanager.h mayu.h \
mayurc.h misc.h msgstream.h multithread.h registry.h stringtool.h \
windowstool.h
$(OUT_DIR)\dlgsetting.obj: compiler_specific.h d\ioctl.h dlgeditsetting.h \
driver.h function.h functions.h keyboard.h keymap.h layoutmanager.h mayu.h \
mayurc.h misc.h multithread.h parser.h registry.h setting.h stringtool.h \
windowstool.h
$(OUT_DIR)\dlgversion.obj: compiler_specific.h compiler_specific_func.h \
layoutmanager.h mayu.h mayurc.h misc.h stringtool.h windowstool.h
$(OUT_DIR)\engine.obj: compiler_specific.h d\ioctl.h driver.h engine.h \
errormessage.h function.h functions.h hook.h keyboard.h keymap.h mayurc.h \
misc.h msgstream.h multithread.h parser.h setting.h stringtool.h \
windowstool.h
$(OUT_DIR)\focus.obj: compiler_specific.h focus.h misc.h stringtool.h \
windowstool.h
$(OUT_DIR)\function.obj: compiler_specific.h d\ioctl.h driver.h engine.h \
function.h functions.h hook.h keyboard.h keymap.h mayu.h mayurc.h misc.h \
msgstream.h multithread.h parser.h registry.h setting.h stringtool.h \
vkeytable.h windowstool.h
$(OUT_DIR)\keyboard.obj: compiler_specific.h d\ioctl.h driver.h keyboard.h \
misc.h stringtool.h
$(OUT_DIR)\keymap.obj: compiler_specific.h d\ioctl.h driver.h \
errormessage.h function.h functions.h keyboard.h keymap.h misc.h \
multithread.h parser.h setting.h stringtool.h
$(OUT_DIR)\layoutmanager.obj: compiler_specific.h layoutmanager.h misc.h \
stringtool.h windowstool.h
$(OUT_DIR)\mayu.obj: compiler_specific.h compiler_specific_func.h d\ioctl.h \
dlginvestigate.h dlglog.h dlgsetting.h dlgversion.h driver.h engine.h \
errormessage.h focus.h function.h functions.h hook.h keyboard.h keymap.h \
mayu.h mayuipc.h mayurc.h misc.h msgstream.h multithread.h parser.h \
registry.h setting.h stringtool.h target.h windowstool.h vk2tchar.h
$(OUT_DIR)\parser.obj: compiler_specific.h errormessage.h misc.h parser.h \
stringtool.h
$(OUT_DIR)\registry.obj: array.h compiler_specific.h misc.h registry.h \
stringtool.h
$(OUT_DIR)\setting.obj: array.h compiler_specific.h d\ioctl.h dlgsetting.h \
driver.h errormessage.h function.h functions.h keyboard.h keymap.h mayu.h \
mayurc.h misc.h multithread.h parser.h registry.h setting.h stringtool.h \
vkeytable.h windowstool.h
$(OUT_DIR)\stringtool.obj: array.h compiler_specific.h misc.h stringtool.h
$(OUT_DIR)\target.obj: compiler_specific.h mayurc.h misc.h stringtool.h \
target.h windowstool.h
$(OUT_DIR)\vkeytable.obj: compiler_specific.h misc.h vkeytable.h
$(OUT_DIR)\windowstool.obj: array.h compiler_specific.h misc.h stringtool.h \
windowstool.h
$(OUT_DIR)\hook.obj: compiler_specific.h hook.h misc.h stringtool.h
$(OUT_DIR)\stringtool.obj: array.h compiler_specific.h misc.h stringtool.h
$(OUT_DIR)\yamyd.obj: mayu.h hook.h
<file_sep>!include $(NTMAKEENV)\makefile.def
clean:
-del buildfre.log
-del i386\mayudrsc.sys
-del i386\mayudrsc.pdb
-del obj\_objects.mac
-del objfre\i386\\mayudrsc.obj
-del *~
-rd i386
-rd obj
-rd objfre\i386
-rd objfre
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// windowstool.h
#ifndef _WINDOWSTOOL_H
# define _WINDOWSTOOL_H
# include "stringtool.h"
# include <windows.h>
/// instance handle of this application
extern HINSTANCE g_hInst;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// resource
/// load resource string
extern tstring loadString(UINT i_id);
/// load small icon resource (it must be deleted by DestroyIcon())
extern HICON loadSmallIcon(UINT i_id);
///load big icon resource (it must be deleted by DestroyIcon())
extern HICON loadBigIcon(UINT i_id);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// window
/// resize the window (it does not move the window)
extern bool resizeWindow(HWND i_hwnd, int i_w, int i_h, bool i_doRepaint);
/** get rect of the window in client coordinates.
@return rect of the window in client coordinates */
extern bool getChildWindowRect(HWND i_hwnd, RECT *o_rc);
/** set small icon to the specified window.
@return handle of previous icon or NULL */
extern HICON setSmallIcon(HWND i_hwnd, UINT i_id);
/** set big icon to the specified window.
@return handle of previous icon or NULL */
extern HICON setBigIcon(HWND i_hwnd, UINT i_id);
/// remove icon from a window that is set by setSmallIcon
extern void unsetSmallIcon(HWND i_hwnd);
/// remove icon from a window that is set by setBigIcon
extern void unsetBigIcon(HWND i_hwnd);
/// get toplevel (non-child) window
extern HWND getToplevelWindow(HWND i_hwnd, bool *io_isMDI);
/// move window asynchronously
extern void asyncMoveWindow(HWND i_hwnd, int i_x, int i_y);
/// move window asynchronously
extern void asyncMoveWindow(HWND i_hwnd, int i_x, int i_y, int i_w, int i_h);
/// resize asynchronously
extern void asyncResize(HWND i_hwnd, int i_w, int i_h);
/// get dll version
extern DWORD getDllVersion(const _TCHAR *i_dllname);
#define PACKVERSION(major, minor) MAKELONG(minor, major)
// workaround of SetForegroundWindow
extern bool setForegroundWindow(HWND i_hwnd);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// dialog
/// get/set GWL_USERDATA
template <class T> inline T getUserData(HWND i_hwnd, T *i_wc)
{
#ifdef MAYU64
return (*i_wc = reinterpret_cast<T>(GetWindowLongPtr(i_hwnd, GWLP_USERDATA)));
#else
return (*i_wc = reinterpret_cast<T>(GetWindowLong(i_hwnd, GWL_USERDATA)));
#endif
}
///
template <class T> inline T setUserData(HWND i_hwnd, T i_wc)
{
#ifdef MAYU64
SetWindowLongPtr(i_hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(i_wc));
#else
SetWindowLong(i_hwnd, GWL_USERDATA, reinterpret_cast<long>(i_wc));
#endif
return i_wc;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// RECT
///
inline int rcWidth(const RECT *i_rc)
{
return i_rc->right - i_rc->left;
}
///
inline int rcHeight(const RECT *i_rc)
{
return i_rc->bottom - i_rc->top;
}
///
inline bool isRectInRect(const RECT *i_rcin, const RECT *i_rcout)
{
return (i_rcout->left <= i_rcin->left &&
i_rcin->right <= i_rcout->right &&
i_rcout->top <= i_rcin->top &&
i_rcin->bottom <= i_rcout->bottom);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// edit control
/// returns bytes of text
extern size_t editGetTextBytes(HWND i_hwnd);
/// delete a line
extern void editDeleteLine(HWND i_hwnd, size_t i_n);
/// insert text at last
extern void editInsertTextAtLast(HWND i_hwnd, const tstring &i_text,
size_t i_threshold);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Windows2000/XP specific API
/// SetLayeredWindowAttributes API
typedef BOOL (WINAPI *SetLayeredWindowAttributes_t)
(HWND hwnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags);
extern SetLayeredWindowAttributes_t setLayeredWindowAttributes;
/// MonitorFromWindow API
extern HMONITOR (WINAPI *monitorFromWindow)(HWND hwnd, DWORD dwFlags);
/// GetMonitorInfo API
extern BOOL (WINAPI *getMonitorInfo)(HMONITOR hMonitor, LPMONITORINFO lpmi);
/// EnumDisplayMonitors API
extern BOOL (WINAPI *enumDisplayMonitors)
(HDC hdc, LPRECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// WindowsXP specific API
/// WTSRegisterSessionNotification API
typedef BOOL (WINAPI *WTSRegisterSessionNotification_t)
(HWND hWnd, DWORD dwFlags);
extern WTSRegisterSessionNotification_t wtsRegisterSessionNotification;
/// WTSUnRegisterSessionNotification API
typedef BOOL (WINAPI *WTSUnRegisterSessionNotification_t)(HWND hWnd);
extern WTSUnRegisterSessionNotification_t wtsUnRegisterSessionNotification;
/// WTSGetActiveConsoleSessionId API
typedef DWORD (WINAPI *WTSGetActiveConsoleSessionId_t)(void);
extern WTSGetActiveConsoleSessionId_t wtsGetActiveConsoleSessionId;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Utility
// PathRemoveFileSpec()
tstring pathRemoveFileSpec(const tstring &i_path);
// check Windows version i_major.i_minor or later
BOOL checkWindowsVersion(DWORD i_major, DWORD i_minor);
#endif // _WINDOWSTOOL_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// windowstool.cpp
#include "misc.h"
#include "windowstool.h"
#include "array.h"
#include <windowsx.h>
#include <malloc.h>
#include <shlwapi.h>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Global variables
// instance handle of this application
HINSTANCE g_hInst = NULL;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Functions
// load resource string
tstring loadString(UINT i_id)
{
_TCHAR buf[1024];
if (LoadString(g_hInst, i_id, buf, NUMBER_OF(buf)))
return tstring(buf);
else
return _T("");
}
// load small icon resource
HICON loadSmallIcon(UINT i_id)
{
return reinterpret_cast<HICON>(
LoadImage(g_hInst, MAKEINTRESOURCE(i_id), IMAGE_ICON, 16, 16, 0));
}
// load big icon resource
HICON loadBigIcon(UINT i_id)
{
return reinterpret_cast<HICON>(
LoadImage(g_hInst, MAKEINTRESOURCE(i_id), IMAGE_ICON, 32, 32, 0));
}
// set small icon to the specified window.
// @return handle of previous icon or NULL
HICON setSmallIcon(HWND i_hwnd, UINT i_id)
{
HICON hicon = (i_id == static_cast<UINT>(-1)) ? NULL : loadSmallIcon(i_id);
return reinterpret_cast<HICON>(
SendMessage(i_hwnd, WM_SETICON, static_cast<WPARAM>(ICON_SMALL),
reinterpret_cast<LPARAM>(hicon)));
}
// set big icon to the specified window.
// @return handle of previous icon or NULL
HICON setBigIcon(HWND i_hwnd, UINT i_id)
{
HICON hicon = (i_id == static_cast<UINT>(-1)) ? NULL : loadBigIcon(i_id);
return reinterpret_cast<HICON>(
SendMessage(i_hwnd, WM_SETICON, static_cast<WPARAM>(ICON_BIG),
reinterpret_cast<LPARAM>(hicon)));
}
// remove icon from a window that is set by setSmallIcon
void unsetSmallIcon(HWND i_hwnd)
{
HICON hicon = setSmallIcon(i_hwnd, -1);
if (hicon)
CHECK_TRUE( DestroyIcon(hicon) );
}
// remove icon from a window that is set by setBigIcon
void unsetBigIcon(HWND i_hwnd)
{
HICON hicon = setBigIcon(i_hwnd, -1);
if (hicon)
CHECK_TRUE( DestroyIcon(hicon) );
}
// resize the window (it does not move the window)
bool resizeWindow(HWND i_hwnd, int i_w, int i_h, bool i_doRepaint)
{
UINT flag = SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER;
if (!i_doRepaint)
flag |= SWP_NOREDRAW;
return !!SetWindowPos(i_hwnd, NULL, 0, 0, i_w, i_h, flag);
}
// get rect of the window in client coordinates
// @return rect of the window in client coordinates
bool getChildWindowRect(HWND i_hwnd, RECT *o_rc)
{
if (!GetWindowRect(i_hwnd, o_rc))
return false;
POINT p = { o_rc->left, o_rc->top };
HWND phwnd = GetParent(i_hwnd);
if (!phwnd)
return false;
if (!ScreenToClient(phwnd, &p))
return false;
o_rc->left = p.x;
o_rc->top = p.y;
p.x = o_rc->right;
p.y = o_rc->bottom;
ScreenToClient(phwnd, &p);
o_rc->right = p.x;
o_rc->bottom = p.y;
return true;
}
// get toplevel (non-child) window
HWND getToplevelWindow(HWND i_hwnd, bool *io_isMDI)
{
while (i_hwnd) {
#ifdef MAYU64
LONG_PTR style = GetWindowLongPtr(i_hwnd, GWL_STYLE);
#else
LONG style = GetWindowLong(i_hwnd, GWL_STYLE);
#endif
if ((style & WS_CHILD) == 0)
break;
if (io_isMDI && *io_isMDI) {
#ifdef MAYU64
LONG_PTR exStyle = GetWindowLongPtr(i_hwnd, GWL_EXSTYLE);
#else
LONG exStyle = GetWindowLong(i_hwnd, GWL_EXSTYLE);
#endif
if (exStyle & WS_EX_MDICHILD)
return i_hwnd;
}
i_hwnd = GetParent(i_hwnd);
}
if (io_isMDI)
*io_isMDI = false;
return i_hwnd;
}
// move window asynchronously
void asyncMoveWindow(HWND i_hwnd, int i_x, int i_y)
{
SetWindowPos(i_hwnd, NULL, i_x, i_y, 0, 0,
SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOSIZE | SWP_NOZORDER);
}
// move window asynchronously
void asyncMoveWindow(HWND i_hwnd, int i_x, int i_y, int i_w, int i_h)
{
SetWindowPos(i_hwnd, NULL, i_x, i_y, i_w, i_h,
SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER);
}
// resize asynchronously
void asyncResize(HWND i_hwnd, int i_w, int i_h)
{
SetWindowPos(i_hwnd, NULL, 0, 0, i_w, i_h,
SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOMOVE | SWP_NOZORDER);
}
// get dll version
DWORD getDllVersion(const _TCHAR *i_dllname)
{
DWORD dwVersion = 0;
if (HINSTANCE hinstDll = LoadLibrary(i_dllname)) {
DLLGETVERSIONPROC pDllGetVersion
= (DLLGETVERSIONPROC)GetProcAddress(hinstDll, "DllGetVersion");
/* Because some DLLs may not implement this function, you
* must test for it explicitly. Depending on the particular
* DLL, the lack of a DllGetVersion function may
* be a useful indicator of the version.
*/
if (pDllGetVersion) {
DLLVERSIONINFO dvi;
ZeroMemory(&dvi, sizeof(dvi));
dvi.cbSize = sizeof(dvi);
HRESULT hr = (*pDllGetVersion)(&dvi);
if (SUCCEEDED(hr))
dwVersion = PACKVERSION(dvi.dwMajorVersion, dvi.dwMinorVersion);
}
FreeLibrary(hinstDll);
}
return dwVersion;
}
// workaround of SetForegroundWindow
bool setForegroundWindow(HWND i_hwnd)
{
int nForegroundID = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
int nTargetID = GetWindowThreadProcessId(i_hwnd, NULL);
//if (!AttachThreadInput(nTargetID, nForegroundID, TRUE))
//return false;
AttachThreadInput(nTargetID, nForegroundID, TRUE);
DWORD sp_time;
SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &sp_time, 0);
SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (void *)0, 0);
SetForegroundWindow(i_hwnd);
SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (void *)sp_time, 0);
AttachThreadInput(nTargetID, nForegroundID, FALSE);
return true;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// edit control
// get edit control's text size
// @return bytes of text
size_t editGetTextBytes(HWND i_hwnd)
{
return Edit_GetTextLength(i_hwnd);
}
// delete a line
void editDeleteLine(HWND i_hwnd, size_t i_n)
{
int len = Edit_LineLength(i_hwnd, i_n);
if (len < 0)
return;
len += 2;
int index = Edit_LineIndex(i_hwnd, i_n);
Edit_SetSel(i_hwnd, index, index + len);
Edit_ReplaceSel(i_hwnd, _T(""));
}
// insert text at last
void editInsertTextAtLast(HWND i_hwnd, const tstring &i_text,
size_t i_threshold)
{
if (i_text.empty())
return;
size_t len = editGetTextBytes(i_hwnd);
if (i_threshold < len) {
Edit_SetSel(i_hwnd, 0, len / 3 * 2);
Edit_ReplaceSel(i_hwnd, _T(""));
editDeleteLine(i_hwnd, 0);
len = editGetTextBytes(i_hwnd);
}
Edit_SetSel(i_hwnd, len, len);
// \n -> \r\n
Array<_TCHAR> buf(i_text.size() * 2 + 1);
_TCHAR *d = buf.get();
const _TCHAR *str = i_text.c_str();
for (const _TCHAR *s = str; s < str + i_text.size(); ++ s) {
if (*s == _T('\n'))
*d++ = _T('\r');
*d++ = *s;
}
*d = _T('\0');
Edit_ReplaceSel(i_hwnd, buf.get());
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Windows2000/XP specific API
// initialize layerd window
static BOOL WINAPI initalizeLayerdWindow(
HWND i_hwnd, COLORREF i_crKey, BYTE i_bAlpha, DWORD i_dwFlags)
{
HMODULE hModule = GetModuleHandle(_T("user32.dll"));
if (!hModule) {
return FALSE;
}
SetLayeredWindowAttributes_t proc =
reinterpret_cast<SetLayeredWindowAttributes_t>(
GetProcAddress(hModule, "SetLayeredWindowAttributes"));
if (setLayeredWindowAttributes) {
setLayeredWindowAttributes = proc;
return setLayeredWindowAttributes(i_hwnd, i_crKey, i_bAlpha, i_dwFlags);
} else {
return FALSE;
}
}
// SetLayeredWindowAttributes API
SetLayeredWindowAttributes_t setLayeredWindowAttributes
= initalizeLayerdWindow;
// emulate MonitorFromWindow API
static HMONITOR WINAPI emulateMonitorFromWindow(HWND hwnd, DWORD dwFlags)
{
return reinterpret_cast<HMONITOR>(1); // dummy HMONITOR
}
// initialize MonitorFromWindow API
static HMONITOR WINAPI initializeMonitorFromWindow(HWND hwnd, DWORD dwFlags)
{
HMODULE hModule = GetModuleHandle(_T("user32.dll"));
if (!hModule)
return FALSE;
FARPROC proc = GetProcAddress(hModule, "MonitorFromWindow");
if (proc)
monitorFromWindow =
reinterpret_cast<HMONITOR (WINAPI *)(HWND, DWORD)>(proc);
else
monitorFromWindow = emulateMonitorFromWindow;
return monitorFromWindow(hwnd, dwFlags);
}
// MonitorFromWindow API
HMONITOR (WINAPI *monitorFromWindow)(HWND hwnd, DWORD dwFlags)
= initializeMonitorFromWindow;
// emulate GetMonitorInfo API
static BOOL WINAPI emulateGetMonitorInfo(HMONITOR hMonitor, LPMONITORINFO lpmi)
{
if (lpmi->cbSize != sizeof(MONITORINFO))
return FALSE;
lpmi->rcMonitor.left = 0;
lpmi->rcMonitor.top = 0;
lpmi->rcMonitor.right = GetSystemMetrics(SM_CXFULLSCREEN);
lpmi->rcMonitor.bottom = GetSystemMetrics(SM_CYFULLSCREEN);
SystemParametersInfo(SPI_GETWORKAREA, 0,
reinterpret_cast<PVOID>(&lpmi->rcWork), FALSE);
lpmi->dwFlags = MONITORINFOF_PRIMARY;
return TRUE;
}
// initialize GetMonitorInfo API
static
BOOL WINAPI initializeGetMonitorInfo(HMONITOR hMonitor, LPMONITORINFO lpmi)
{
HMODULE hModule = GetModuleHandle(_T("user32.dll"));
if (!hModule)
return FALSE;
FARPROC proc = GetProcAddress(hModule, "GetMonitorInfoA");
if (proc)
getMonitorInfo =
reinterpret_cast<BOOL (WINAPI *)(HMONITOR, LPMONITORINFO)>(proc);
else
getMonitorInfo = emulateGetMonitorInfo;
return getMonitorInfo(hMonitor, lpmi);
}
// GetMonitorInfo API
BOOL (WINAPI *getMonitorInfo)(HMONITOR hMonitor, LPMONITORINFO lpmi)
= initializeGetMonitorInfo;
// enumalte EnumDisplayMonitors API
static BOOL WINAPI emulateEnumDisplayMonitors(
HDC hdc, LPRECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData)
{
lpfnEnum(reinterpret_cast<HMONITOR>(1), hdc, lprcClip, dwData);
return TRUE;
}
// initialize EnumDisplayMonitors API
static BOOL WINAPI initializeEnumDisplayMonitors(
HDC hdc, LPRECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData)
{
HMODULE hModule = GetModuleHandle(_T("user32.dll"));
if (!hModule)
return FALSE;
FARPROC proc = GetProcAddress(hModule, "EnumDisplayMonitors");
if (proc)
enumDisplayMonitors =
reinterpret_cast<BOOL (WINAPI *)(HDC, LPRECT, MONITORENUMPROC, LPARAM)>
(proc);
else
enumDisplayMonitors = emulateEnumDisplayMonitors;
return enumDisplayMonitors(hdc, lprcClip, lpfnEnum, dwData);
}
// EnumDisplayMonitors API
BOOL (WINAPI *enumDisplayMonitors)
(HDC hdc, LPRECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData)
= initializeEnumDisplayMonitors;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Windows2000/XP specific API
static BOOL WINAPI
initializeWTSRegisterSessionNotification(HWND hWnd, DWORD dwFlags)
{
LoadLibrary(_T("wtsapi32.dll"));
HMODULE hModule = GetModuleHandle(_T("wtsapi32.dll"));
if (!hModule) {
return FALSE;
}
WTSRegisterSessionNotification_t proc =
reinterpret_cast<WTSRegisterSessionNotification_t>(
GetProcAddress(hModule, "WTSRegisterSessionNotification"));
if (proc) {
wtsRegisterSessionNotification = proc;
return wtsRegisterSessionNotification(hWnd, dwFlags);
} else {
return 0;
}
}
// WTSRegisterSessionNotification API
WTSRegisterSessionNotification_t wtsRegisterSessionNotification
= initializeWTSRegisterSessionNotification;
static BOOL WINAPI initializeWTSUnRegisterSessionNotification(HWND hWnd)
{
HMODULE hModule = GetModuleHandle(_T("wtsapi32.dll"));
if (!hModule) {
return FALSE;
}
WTSUnRegisterSessionNotification_t proc =
reinterpret_cast<WTSUnRegisterSessionNotification_t>(
GetProcAddress(hModule, "WTSUnRegisterSessionNotification"));
if (proc) {
wtsUnRegisterSessionNotification = proc;
return wtsUnRegisterSessionNotification(hWnd);
} else {
return 0;
}
}
// WTSUnRegisterSessionNotification API
WTSUnRegisterSessionNotification_t wtsUnRegisterSessionNotification
= initializeWTSUnRegisterSessionNotification;
static DWORD WINAPI initializeWTSGetActiveConsoleSessionId(void)
{
HMODULE hModule = GetModuleHandle(_T("kernel32.dll"));
if (!hModule) {
return FALSE;
}
WTSGetActiveConsoleSessionId_t proc =
reinterpret_cast<WTSGetActiveConsoleSessionId_t>(
GetProcAddress(hModule, "WTSGetActiveConsoleSessionId"));
if (proc) {
wtsGetActiveConsoleSessionId = proc;
return wtsGetActiveConsoleSessionId();
} else {
return 0;
}
}
// WTSGetActiveConsoleSessionId API
WTSGetActiveConsoleSessionId_t wtsGetActiveConsoleSessionId
= initializeWTSGetActiveConsoleSessionId;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Utility
// PathRemoveFileSpec()
tstring pathRemoveFileSpec(const tstring &i_path)
{
const _TCHAR *str = i_path.c_str();
const _TCHAR *b = _tcsrchr(str, _T('\\'));
const _TCHAR *s = _tcsrchr(str, _T('/'));
if (b && s)
return tstring(str, MIN(b, s));
if (b)
return tstring(str, b);
if (s)
return tstring(str, s);
if (const _TCHAR *c = _tcsrchr(str, _T(':')))
return tstring(str, c + 1);
return i_path;
}
BOOL checkWindowsVersion(DWORD i_major, DWORD i_minor)
{
DWORDLONG conditionMask = 0;
OSVERSIONINFOEX osvi;
memset(&osvi, 0, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
osvi.dwMajorVersion = i_major;
osvi.dwMinorVersion = i_minor;
VER_SET_CONDITION(conditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
VER_SET_CONDITION(conditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
// Perform the test.
return VerifyVersionInfo(&osvi, VER_MAJORVERSION | VER_MINORVERSION, conditionMask);
}
<file_sep>///////////////////////////////////////////////////////////////////////////////
// Rescue driver for Madotsukai no Yu^utsu for Windows2000/XP
#include <ntddk.h>
#pragma warning(3 : 4061 4100 4132 4701 4706)
///////////////////////////////////////////////////////////////////////////////
// Protorypes
NTSTATUS DriverEntry (IN PDRIVER_OBJECT, IN PUNICODE_STRING);
NTSTATUS mayuAddDevice (IN PDRIVER_OBJECT, IN PDEVICE_OBJECT);
VOID mayuUnloadDriver (IN PDRIVER_OBJECT);
NTSTATUS mayuGenericDispatch (IN PDEVICE_OBJECT, IN PIRP);
#ifdef ALLOC_PRAGMA
#pragma alloc_text( init, DriverEntry )
#endif // ALLOC_PRAGMA
///////////////////////////////////////////////////////////////////////////////
// Entry / Unload
// initialize driver
NTSTATUS DriverEntry(IN PDRIVER_OBJECT driverObject,
IN PUNICODE_STRING registryPath)
{
ULONG i;
UNREFERENCED_PARAMETER(registryPath);
// set major functions
driverObject->DriverUnload = mayuUnloadDriver;
driverObject->DriverExtension->AddDevice = mayuAddDevice;
for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++)
driverObject->MajorFunction[i] = mayuGenericDispatch;
driverObject->MajorFunction[IRP_MJ_PNP] = mayuGenericDispatch;
return STATUS_SUCCESS;
}
NTSTATUS mayuAddDevice(IN PDRIVER_OBJECT driverObject,
IN PDEVICE_OBJECT kbdClassDevObj)
{
UNREFERENCED_PARAMETER(driverObject);
UNREFERENCED_PARAMETER(kbdClassDevObj);
return STATUS_SUCCESS;
}
// unload driver
VOID mayuUnloadDriver(IN PDRIVER_OBJECT driverObject)
{
UNREFERENCED_PARAMETER(driverObject);
}
///////////////////////////////////////////////////////////////////////////////
// Dispatch Functions
// Generic Dispatcher
NTSTATUS mayuGenericDispatch(IN PDEVICE_OBJECT deviceObject, IN PIRP irp)
{
UNREFERENCED_PARAMETER(deviceObject);
UNREFERENCED_PARAMETER(irp);
return STATUS_SUCCESS;
}
<file_sep>############################################################## -*- Makefile -*-
#
# Makefile for setup (Visual C++)
#
# make release version: nmake nodebug=1
# make debug version: nmake
#
###############################################################################
!if "$(BOOST_VER)" == ""
BOOST_VER = 1_32
!endif
INCLUDES = -I$(BOOST_DIR) # why here ?
DEPENDIGNORE = --ignore=$(BOOST_DIR)
!if "$(MAYU_VC)" == ""
MAYU_VC = vc6
!endif
!if ( "$(MAYU_VC)" == "vct" )
MAYU_REGEX_VC = vc71
!else
MAYU_REGEX_VC = $(MAYU_VC)
!endif
!include <..\vc.mak>
!include <setup-common.mak>
LDFLAGS_1 = \
$(guilflags) \
/PDB:$(TARGET_1).pdb \
/LIBPATH:$(BOOST_DIR)/libs/regex/build/$(MAYU_REGEX_VC) \
$(TARGET_1): $(OBJS_1) $(RES_1) $(EXTRADEP_1)
$(link) -out:$@ $(ldebug) $(LDFLAGS_1) $(OBJS_1) $(LIBS_1) $(RES_1)
strres.h: setup.rc
grep IDS setup.rc | \
sed "s/\(IDS[a-zA-Z0-9_]*\)[^""]*\("".*\)$$/\1, _T(\2),/" | \
sed "s/""""/"") _T(""/g" > strres.h
batch:
!if "$(MAYU_VC)" != "vct"
-$(MAKE) -k -f setup-vc.mak MAYU_VC=$(MAYU_VC) TARGETOS=WINNT
!endif
-$(MAKE) -k -f setup-vc.mak MAYU_VC=$(MAYU_VC) TARGETOS=WINNT nodebug=1
batch_clean:
-$(MAKE) -k -f setup-vc.mak MAYU_VC=$(MAYU_VC) TARGETOS=WINNT nodebug=1 clean
-$(MAKE) -k -f setup-vc.mak MAYU_VC=$(MAYU_VC) TARGETOS=WINNT clean
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// layoutmanager.h
#ifndef _LAYOUTMANAGER_H
# define _LAYOUTMANAGER_H
# include "misc.h"
# include <list>
///
class LayoutManager
{
public:
///
enum Origin {
ORIGIN_LEFT_EDGE, ///
ORIGIN_TOP_EDGE = ORIGIN_LEFT_EDGE, ///
ORIGIN_CENTER, ///
ORIGIN_RIGHT_EDGE, ///
ORIGIN_BOTTOM_EDGE = ORIGIN_RIGHT_EDGE, ///
};
///
enum Restrict {
RESTRICT_NONE = 0, ///
RESTRICT_HORIZONTALLY = 1, ///
RESTRICT_VERTICALLY = 2, ///
RESTRICT_BOTH = RESTRICT_HORIZONTALLY | RESTRICT_VERTICALLY, ///
};
private:
///
class Item
{
public:
HWND m_hwnd; ///
HWND m_hwndParent; ///
RECT m_rc; ///
RECT m_rcParent; ///
Origin m_origin[4]; ///
};
///
class SmallestSize
{
public:
HWND m_hwnd; ///
SIZE m_size; ///
public:
///
SmallestSize() : m_hwnd(NULL) { }
};
typedef std::list<Item> Items; ///
protected:
HWND m_hwnd; ///
private:
Items m_items; ///
Restrict m_smallestRestriction; ///
SIZE m_smallestSize; ///
Restrict m_largestRestriction; ///
SIZE m_largestSize; ///
public:
///
LayoutManager(HWND i_hwnd);
/** restrict the smallest size of the window to the current size of it or
specified by i_size */
void restrictSmallestSize(Restrict i_restrict = RESTRICT_BOTH,
SIZE *i_size = NULL);
/** restrict the largest size of the window to the current size of it or
specified by i_size */
void restrictLargestSize(Restrict i_restrict = RESTRICT_BOTH,
SIZE *i_size = NULL);
///
bool addItem(HWND i_hwnd,
Origin i_originLeft = ORIGIN_LEFT_EDGE,
Origin i_originTop = ORIGIN_TOP_EDGE,
Origin i_originRight = ORIGIN_LEFT_EDGE,
Origin i_originBottom = ORIGIN_TOP_EDGE);
///
void adjust() const;
/// draw size box
virtual BOOL wmPaint();
/// size restriction
virtual BOOL wmSizing(int i_edge, RECT *io_rc);
/// hittest for size box
virtual BOOL wmNcHitTest(int i_x, int i_y);
/// WM_SIZE
virtual BOOL wmSize(DWORD /* i_fwSizeType */, short /* i_nWidth */,
short /* i_nHeight */);
/// forward message
virtual BOOL defaultWMHandler(UINT i_message, WPARAM i_wParam,
LPARAM i_lParam);
};
#endif // !_LAYOUTMANAGER_H
<file_sep>///////////////////////////////////////////////////////////////////////////////
// installer.h
#ifndef _INSTALLER_H
# define _INSTALLER_H
namespace Installer
{
/////////////////////////////////////////////////////////////////////////////
// SetupFile
// files to copy
namespace SetupFile {
enum Kind {
File,
Dir,
Dll,
};
enum OS {
ALL,
W9x, // W95, W98,
NT, NT4, W2k, // W2k includes XP
};
enum Destination {
ToDest,
ToDriver,
};
enum Flag {
Normal = 1,
};
struct Data {
Kind m_kind;
OS m_os;
u_int32 m_flags; /// user defined flags
const _TCHAR *m_from;
Destination m_destination;
const _TCHAR *m_to;
};
}
/////////////////////////////////////////////////////////////////////////////
// Locale / StringResource
enum Locale {
LOCALE_Japanese_Japan_932 = 0,
LOCALE_C = 1,
};
struct StringResource {
UINT m_id;
_TCHAR *m_str;
};
class Resource
{
const StringResource *m_stringResources;
Locale m_locale;
public:
// constructor
Resource(const StringResource *i_stringResources);
Resource(const StringResource *i_stringResources, Locale i_locale)
: m_stringResources(i_stringResources), m_locale(i_locale) { }
// get resource string
const _TCHAR *loadString(UINT i_id);
// locale
Locale getLocale() const {
return m_locale;
}
};
/////////////////////////////////////////////////////////////////////////////
// Utility Functions
// createLink - uses the shell's IShellLink and IPersistFile interfaces
// to create and store a shortcut to the specified object.
HRESULT createLink(LPCTSTR i_pathObj, LPCTSTR i_pathLink, LPCTSTR i_desc,
LPCTSTR i_workingDirectory = NULL);
// create file extension information
void createFileExtension(const tstringi &i_ext, const tstring &i_contentType,
const tstringi &i_fileType,
const tstring &i_fileTypeName,
const tstringi &i_iconPath,
const tstring &i_command);
// remove file extension information
void removeFileExtension(const tstringi &i_ext, const tstringi &i_fileType);
// create uninstallation information
void createUninstallInformation(const tstringi &i_name,
const tstring &i_displayName,
const tstring &i_commandLine);
// remove uninstallation information
void removeUninstallInformation(const tstringi &i_name);
// normalize path
tstringi normalizePath(tstringi i_path);
// create deep directory
bool createDirectories(const _TCHAR *i_folder);
// get driver directory
tstringi getDriverDirectory();
// get current directory
tstringi getModuleDirectory();
// get start menu name
tstringi getStartMenuName(const tstringi &i_shortcutName);
// get start up name
tstringi getStartUpName(const tstringi &i_shortcutName);
// create driver service
DWORD createDriverService(const tstringi &i_serviceName,
const tstring &i_serviceDescription,
const tstringi &i_driverPath,
const _TCHAR *i_preloadedGroups,
bool forUsb);
// remove driver service
DWORD removeDriverService(const tstringi &i_serviceName);
// check operating system
bool checkOs(SetupFile::OS i_os);
// install files
bool installFiles(const SetupFile::Data *i_setupFiles,
size_t i_setupFilesSize, u_int32 i_flags,
const tstringi &i_srcDir, const tstringi &i_destDir);
// remove files from src
bool removeSrcFiles(const SetupFile::Data *i_setupFiles,
size_t i_setupFilesSize, u_int32 i_flags,
const tstringi &i_srcDir);
// remove files
void removeFiles(const SetupFile::Data *i_setupFiles,
size_t i_setupFilesSize, u_int32 i_flags,
const tstringi &i_destDir);
// uninstall step1
int uninstallStep1(const _TCHAR *i_uninstallOption);
// uninstall step2
// (after this function, we cannot use any resource)
void uninstallStep2(const _TCHAR *i_argByStep1);
}
#endif // _INSTALLER_H
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// setting.cpp
#include "keyboard.h"
#include <algorithm>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Key
// add a name or an alias of key
void Key::addName(const tstringi &i_name)
{
m_names.push_back(i_name);
}
// add a scan code
void Key::addScanCode(const ScanCode &i_sc)
{
ASSERT(m_scanCodesSize < MAX_SCAN_CODES_SIZE);
m_scanCodes[m_scanCodesSize ++] = i_sc;
}
// initializer
Key &Key::initialize()
{
m_names.clear();
m_isPressed = false;
m_isPressedOnWin32 = false;
m_isPressedByAssign = false;
m_scanCodesSize = 0;
return *this;
}
// equation by name
bool Key::operator==(const tstringi &i_name) const
{
return std::find(m_names.begin(), m_names.end(), i_name) != m_names.end();
}
// is the scan code of this key ?
bool Key::isSameScanCode(const Key &i_key) const
{
if (m_scanCodesSize != i_key.m_scanCodesSize)
return false;
return isPrefixScanCode(i_key);
}
// is the key's scan code the prefix of this key's scan code ?
bool Key::isPrefixScanCode(const Key &i_key) const
{
for (size_t i = 0; i < i_key.m_scanCodesSize; ++ i)
if (m_scanCodes[i] != i_key.m_scanCodes[i])
return false;
return true;
}
// stream output
tostream &operator<<(tostream &i_ost, const Key &i_mk)
{
return i_ost << i_mk.getName();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Modifier
Modifier::Modifier()
: m_modifiers(0),
m_dontcares(0)
{
ASSERT(Type_end <= (sizeof(MODIFIERS) * 8));
static const Type defaultDontCare[] = {
Type_Up, Type_Down, Type_Repeat,
Type_ImeLock, Type_ImeComp, Type_NumLock, Type_CapsLock, Type_ScrollLock,
Type_KanaLock,
Type_Maximized, Type_Minimized, Type_MdiMaximized, Type_MdiMinimized,
Type_Touchpad, Type_TouchpadSticky,
Type_Lock0, Type_Lock1, Type_Lock2, Type_Lock3, Type_Lock4,
Type_Lock5, Type_Lock6, Type_Lock7, Type_Lock8, Type_Lock9,
};
for (size_t i = 0; i < NUMBER_OF(defaultDontCare); ++ i)
dontcare(defaultDontCare[i]);
}
// add m's modifiers where this dontcare
void Modifier::add(const Modifier &i_m)
{
for (int i = 0; i < Type_end; ++ i) {
if (isDontcare(static_cast<Modifier::Type>(i)))
if (!i_m.isDontcare(static_cast<Modifier::Type>(i)))
if (i_m.isPressed(static_cast<Modifier::Type>(i)))
press(static_cast<Modifier::Type>(i));
else
release(static_cast<Modifier::Type>(i));
}
}
// stream output
tostream &operator<<(tostream &i_ost, const Modifier &i_m)
{
struct Mods {
Modifier::Type m_mt;
const _TCHAR *m_symbol;
};
const static Mods mods[] = {
{ Modifier::Type_Up, _T("U-") }, { Modifier::Type_Down, _T("D-") },
{ Modifier::Type_Shift, _T("S-") }, { Modifier::Type_Alt, _T("A-") },
{ Modifier::Type_Control, _T("C-") }, { Modifier::Type_Windows, _T("W-") },
{ Modifier::Type_Repeat, _T("R-") },
{ Modifier::Type_ImeLock, _T("IL-") },
{ Modifier::Type_ImeComp, _T("IC-") },
{ Modifier::Type_ImeComp, _T("I-") },
{ Modifier::Type_NumLock, _T("NL-") },
{ Modifier::Type_CapsLock, _T("CL-") },
{ Modifier::Type_ScrollLock, _T("SL-") },
{ Modifier::Type_KanaLock, _T("KL-") },
{ Modifier::Type_Maximized, _T("MAX-") },
{ Modifier::Type_Minimized, _T("MIN-") },
{ Modifier::Type_MdiMaximized, _T("MMAX-") },
{ Modifier::Type_MdiMinimized, _T("MMIN-") },
{ Modifier::Type_Touchpad, _T("T-") },
{ Modifier::Type_TouchpadSticky, _T("TS-") },
{ Modifier::Type_Mod0, _T("M0-") }, { Modifier::Type_Mod1, _T("M1-") },
{ Modifier::Type_Mod2, _T("M2-") }, { Modifier::Type_Mod3, _T("M3-") },
{ Modifier::Type_Mod4, _T("M4-") }, { Modifier::Type_Mod5, _T("M5-") },
{ Modifier::Type_Mod6, _T("M6-") }, { Modifier::Type_Mod7, _T("M7-") },
{ Modifier::Type_Mod8, _T("M8-") }, { Modifier::Type_Mod9, _T("M9-") },
{ Modifier::Type_Lock0, _T("L0-") }, { Modifier::Type_Lock1, _T("L1-") },
{ Modifier::Type_Lock2, _T("L2-") }, { Modifier::Type_Lock3, _T("L3-") },
{ Modifier::Type_Lock4, _T("L4-") }, { Modifier::Type_Lock5, _T("L5-") },
{ Modifier::Type_Lock6, _T("L6-") }, { Modifier::Type_Lock7, _T("L7-") },
{ Modifier::Type_Lock8, _T("L8-") }, { Modifier::Type_Lock9, _T("L9-") },
};
for (size_t i = 0; i < NUMBER_OF(mods); ++ i)
if (!i_m.isDontcare(mods[i].m_mt) && i_m.isPressed(mods[i].m_mt))
i_ost << mods[i].m_symbol;
#if 0
else if (!i_m.isDontcare(mods[i].m_mt) && i_m.isPressed(mods[i].m_mt))
i_ost << _T("~") << mods[i].m_symbol;
else
i_ost << _T("*") << mods[i].m_symbol;
#endif
return i_ost;
}
/// stream output
tostream &operator<<(tostream &i_ost, Modifier::Type i_type)
{
const _TCHAR *modNames[] = {
_T("Shift"),
_T("Alt"),
_T("Control"),
_T("Windows"),
_T("Up"),
_T("Down"),
_T("Repeat"),
_T("ImeLock"),
_T("ImeComp"),
_T("NumLock"),
_T("CapsLock"),
_T("ScrollLock"),
_T("KanaLock"),
_T("Maximized"),
_T("Minimized"),
_T("MdiMaximized"),
_T("MdiMinimized"),
_T("Touchpad"),
_T("TouchpadSticky"),
_T("Mod0"),
_T("Mod1"),
_T("Mod2"),
_T("Mod3"),
_T("Mod4"),
_T("Mod5"),
_T("Mod6"),
_T("Mod7"),
_T("Mod8"),
_T("Mod9"),
_T("Lock0"),
_T("Lock1"),
_T("Lock2"),
_T("Lock3"),
_T("Lock4"),
_T("Lock5"),
_T("Lock6"),
_T("Lock7"),
_T("Lock8"),
_T("Lock9"),
};
int i = static_cast<int>(i_type);
if (0 <= i && i < NUMBER_OF(modNames))
i_ost << modNames[i];
return i_ost;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ModifiedKey
// stream output
tostream &operator<<(tostream &i_ost, const ModifiedKey &i_mk)
{
if (i_mk.m_key)
i_ost << i_mk.m_modifier << *i_mk.m_key;
return i_ost;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Keyboard::KeyIterator
Keyboard::KeyIterator::KeyIterator(Keys *i_hashedKeys, size_t i_hashedKeysSize)
: m_hashedKeys(i_hashedKeys),
m_hashedKeysSize(i_hashedKeysSize),
m_i((*m_hashedKeys).begin())
{
if ((*m_hashedKeys).empty()) {
do {
-- m_hashedKeysSize;
++ m_hashedKeys;
} while (0 < m_hashedKeysSize && (*m_hashedKeys).empty());
if (0 < m_hashedKeysSize)
m_i = (*m_hashedKeys).begin();
}
}
void Keyboard::KeyIterator::next()
{
if (m_hashedKeysSize == 0)
return;
++ m_i;
if (m_i == (*m_hashedKeys).end()) {
do {
-- m_hashedKeysSize;
++ m_hashedKeys;
} while (0 < m_hashedKeysSize && (*m_hashedKeys).empty());
if (0 < m_hashedKeysSize)
m_i = (*m_hashedKeys).begin();
}
}
Key *Keyboard::KeyIterator::operator *()
{
if (m_hashedKeysSize == 0)
return NULL;
return &*m_i;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Keyboard
Keyboard::Keys &Keyboard::getKeys(const Key &i_key)
{
ASSERT(1 <= i_key.getScanCodesSize());
return m_hashedKeys[i_key.getScanCodes()->m_scan % HASHED_KEYS_SIZE];
}
// add a key
void Keyboard::addKey(const Key &i_key)
{
getKeys(i_key).push_front(i_key);
}
// add a key name alias
void Keyboard::addAlias(const tstringi &i_aliasName, Key *i_key)
{
m_aliases.insert(Aliases::value_type(i_aliasName, i_key));
}
// add substitute
void Keyboard::addSubstitute(const ModifiedKey &i_mkeyFrom,
const ModifiedKey &i_mkeyTo)
{
m_substitutes.push_front(Substitute(i_mkeyFrom, i_mkeyTo));
}
// add a modifier key
void Keyboard::addModifier(Modifier::Type i_mt, Key *i_key)
{
ASSERT((int)i_mt < (int)Modifier::Type_BASIC);
if (std::find(m_mods[i_mt].begin(), m_mods[i_mt].end(), i_key)
!= m_mods[i_mt].end())
return; // already added
m_mods[i_mt].push_back(i_key);
}
// search a key
Key *Keyboard::searchKey(const Key &i_key)
{
Keys &keys = getKeys(i_key);
for (Keys::iterator i = keys.begin(); i != keys.end(); ++ i)
if ((*i).isSameScanCode(i_key))
return &*i;
return NULL;
}
// search a key (of which the key's scan code is the prefix)
Key *Keyboard::searchPrefixKey(const Key &i_key)
{
Keys &keys = getKeys(i_key);
for (Keys::iterator i = keys.begin(); i != keys.end(); ++ i)
if ((*i).isPrefixScanCode(i_key))
return &*i;
return NULL;
}
// search a key by name
Key *Keyboard::searchKey(const tstringi &i_name)
{
Aliases::iterator i = m_aliases.find(i_name);
if (i != m_aliases.end())
return (*i).second;
return searchKeyByNonAliasName(i_name);
}
// search a key by non-alias name
Key *Keyboard::searchKeyByNonAliasName(const tstringi &i_name)
{
for (int j = 0; j < HASHED_KEYS_SIZE; ++ j) {
Keys &keys = m_hashedKeys[j];
Keys::iterator i = std::find(keys.begin(), keys.end(), i_name);
if (i != keys.end())
return &*i;
}
return NULL;
}
/// search a substitute
ModifiedKey Keyboard::searchSubstitute(const ModifiedKey &i_mkey)
{
for (Substitutes::const_iterator
i = m_substitutes.begin(); i != m_substitutes.end(); ++ i)
if (i->m_mkeyFrom.m_key == i_mkey.m_key &&
i->m_mkeyFrom.m_modifier.doesMatch(i_mkey.m_modifier))
return i->m_mkeyTo;
return ModifiedKey(); // not found (.m_mkey is NULL)
}
<file_sep>//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// multithread.h
#ifndef _MULTITHREAD_H
# define _MULTITHREAD_H
# include <windows.h>
///
class SyncObject
{
public:
///
virtual void acquire() = 0;
///
virtual void acquire(int ) {
acquire();
}
///
virtual void release() = 0;
};
///
class CriticalSection : public SyncObject
{
CRITICAL_SECTION m_cs; ///
public:
///
CriticalSection() {
InitializeCriticalSection(&m_cs);
}
///
~CriticalSection() {
DeleteCriticalSection(&m_cs);
}
///
void acquire() {
EnterCriticalSection(&m_cs);
}
///
void release() {
LeaveCriticalSection(&m_cs);
}
};
///
class Acquire
{
SyncObject *m_so; ///
public:
///
Acquire(SyncObject *i_so) : m_so(i_so) {
m_so->acquire();
}
///
Acquire(SyncObject *i_so, int i_n) : m_so(i_so) {
m_so->acquire(i_n);
}
///
~Acquire() {
m_so->release();
}
};
#endif // !_MULTITHREAD_H
<file_sep>#include "fixscancodemap.h"
#include "misc.h"
#include "windowstool.h"
#include <tchar.h>
#include <tlhelp32.h>
#include <process.h>
#pragma runtime_checks( "", off )
static DWORD WINAPI invokeFunc(InjectInfo *info)
{
BOOL ret;
HANDLE hToken;
HMODULE hAdvapi32;
DWORD result = 0;
FpImpersonateLoggedOnUser pImpersonateLoggedOnUser;
FpRevertToSelf pRevertToSelf;
FpOpenProcessToken pOpenProcessToken;
hAdvapi32 = info->pGetModuleHandle(info->advapi32_);
pImpersonateLoggedOnUser = (FpImpersonateLoggedOnUser)info->pGetProcAddress(hAdvapi32, info->impersonateLoggedOnUser_);
pRevertToSelf = (FpRevertToSelf)info->pGetProcAddress(hAdvapi32, info->revertToSelf_);
pOpenProcessToken = (FpOpenProcessToken)info->pGetProcAddress(hAdvapi32, info->openProcessToken_);
HANDLE hProcess = info->pOpenProcess(PROCESS_QUERY_INFORMATION, FALSE, info->pid_);
if (hProcess == NULL) {
result = YAMY_ERROR_ON_OPEN_YAMY_PROCESS;
goto exit;
}
ret = pOpenProcessToken(hProcess, TOKEN_QUERY | TOKEN_DUPLICATE , &hToken);
if (ret == FALSE) {
result = YAMY_ERROR_ON_OPEN_YAMY_TOKEN;
goto exit;
}
ret = pImpersonateLoggedOnUser(hToken);
if (ret == FALSE) {
result = YAMY_ERROR_ON_IMPERSONATE;
goto exit;
}
if (info->isVistaOrLater_) {
info->pUpdate4(1);
} else {
info->pUpdate8(0, 1);
}
ret = pRevertToSelf();
if (ret == FALSE) {
result = YAMY_ERROR_ON_REVERT_TO_SELF;
goto exit;
}
exit:
if (hToken != NULL) {
info->pCloseHandle(hToken);
}
if (hProcess != NULL) {
info->pCloseHandle(hProcess);
}
return result;
}
static int afterFunc(int arg)
{
// dummy operation
// if this function empty, optimizer unify this with other empty functions.
// following code avoid it.
arg *= 710810; // non-sense operation
return arg;
}
#pragma runtime_checks( "", restore )
const DWORD FixScancodeMap::s_fixEntryNum = 4;
const DWORD FixScancodeMap::s_fixEntry[] = {
0x003ae03a,
0x0029e029,
0x0070e070,
0x007be07b,
};
int FixScancodeMap::acquirePrivileges()
{
int ret = 0;
HANDLE hToken = NULL;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) {
ret = YAMY_ERROR_ON_OPEN_CURRENT_PROCESS;
goto exit;
}
LUID luid;
if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid)) {
ret = YAMY_ERROR_ON_LOOKUP_PRIVILEGE;
goto exit;
}
TOKEN_PRIVILEGES tk_priv;
tk_priv.PrivilegeCount = 1;
tk_priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
tk_priv.Privileges[0].Luid = luid;
if (!AdjustTokenPrivileges(hToken, FALSE, &tk_priv, 0, NULL, NULL)) {
ret = YAMY_ERROR_ON_ADJUST_PRIVILEGE;
goto exit;
}
exit:
if (hToken != NULL) {
CloseHandle(hToken);
}
return ret;
}
DWORD FixScancodeMap::getWinLogonPid()
{
DWORD pid = 0;
DWORD mySessionId = 0;
if (ProcessIdToSessionId(GetCurrentProcessId(), &mySessionId) == FALSE) {
return 0;
}
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE) {
return 0;
}
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
BOOL bResult = Process32First(hSnap, &pe);
while (bResult){
if (!_tcsicmp(pe.szExeFile, _T("winlogon.exe"))) {
DWORD sessionId;
if (ProcessIdToSessionId(pe.th32ProcessID, &sessionId) != FALSE) {
if (sessionId == mySessionId) {
pid = pe.th32ProcessID;
break;
}
}
}
bResult = Process32Next(hSnap, &pe);
}
CloseHandle(hSnap);
return pid;
}
bool FixScancodeMap::clean(WlInfo wl)
{
int ret = 0;
if (wl.m_hThread != NULL) {
DWORD result;
if (WaitForSingleObject(wl.m_hThread, 5000) == WAIT_TIMEOUT) {
return false;
}
GetExitCodeThread(wl.m_hThread, &result);
CloseHandle(wl.m_hThread);
if (wl.m_remoteMem != NULL && wl.m_hProcess != NULL) {
VirtualFreeEx(wl.m_hProcess, wl.m_remoteMem, 0, MEM_RELEASE);
}
if (wl.m_remoteInfo != NULL && wl.m_hProcess != NULL) {
VirtualFreeEx(wl.m_hProcess, wl.m_remoteInfo, 0, MEM_RELEASE);
}
if (wl.m_hProcess != NULL) {
CloseHandle(wl.m_hProcess);
}
}
return true;
}
int FixScancodeMap::injectThread(DWORD dwPID)
{
int ret = 0;
DWORD err = 0;
BOOL wFlag;
WlInfo wi;
wi.m_hProcess = NULL;
wi.m_remoteMem = NULL;
wi.m_remoteInfo = NULL;
wi.m_hThread = NULL;
ULONG_PTR invokeFuncAddr = (ULONG_PTR)invokeFunc;
ULONG_PTR afterFuncAddr = (ULONG_PTR)afterFunc;
SIZE_T memSize = afterFuncAddr - invokeFuncAddr;
if ((wi.m_hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID)) == NULL) {
ret = YAMY_ERROR_ON_OPEN_WINLOGON_PROCESS;
goto exit;
}
wi.m_remoteMem = VirtualAllocEx(wi.m_hProcess, NULL, memSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (wi.m_remoteMem == NULL) {
ret = YAMY_ERROR_ON_VIRTUALALLOCEX;
err = GetLastError();
goto exit;
}
wFlag = WriteProcessMemory(wi.m_hProcess, wi.m_remoteMem, (char*)invokeFunc, memSize, (SIZE_T*)0);
if (wFlag == FALSE) {
ret = YAMY_ERROR_ON_WRITEPROCESSMEMORY;
goto exit;
}
wi.m_remoteInfo = VirtualAllocEx(wi.m_hProcess, NULL, sizeof(m_info), MEM_COMMIT, PAGE_READWRITE);
if (wi.m_remoteInfo == NULL) {
ret = YAMY_ERROR_ON_VIRTUALALLOCEX;
err = GetLastError();
goto exit;
}
wFlag = WriteProcessMemory(wi.m_hProcess, wi.m_remoteInfo, (char*)&m_info, sizeof(m_info), (SIZE_T*)0);
if (wFlag == FALSE) {
ret = YAMY_ERROR_ON_WRITEPROCESSMEMORY;
goto exit;
}
wi.m_hThread = CreateRemoteThread(wi.m_hProcess, NULL, 0,
(LPTHREAD_START_ROUTINE)wi.m_remoteMem, wi.m_remoteInfo, 0, NULL);
if (wi.m_hThread == NULL) {
ret = YAMY_ERROR_ON_CREATEREMOTETHREAD;
goto exit;
}
if (WaitForSingleObject(wi.m_hThread, 5000) == WAIT_TIMEOUT) {
ret = YAMY_ERROR_TIMEOUT_INJECTION;
m_wlTrash.push_back(wi);
goto dirty_exit;
}
DWORD result = -1;
GetExitCodeThread(wi.m_hThread, &result);
ret = result;
CloseHandle(wi.m_hThread);
wi.m_hThread = NULL;
exit:
if (wi.m_remoteMem != NULL && wi.m_hProcess != NULL) {
VirtualFreeEx(wi.m_hProcess, wi.m_remoteMem, 0, MEM_RELEASE);
wi.m_remoteMem = NULL;
}
if (wi.m_remoteInfo != NULL && wi.m_hProcess != NULL) {
VirtualFreeEx(wi.m_hProcess, wi.m_remoteInfo, 0, MEM_RELEASE);
wi.m_remoteInfo = NULL;
}
if (wi.m_hProcess != NULL) {
CloseHandle(wi.m_hProcess);
wi.m_hProcess = NULL;
}
dirty_exit:
return ret;
}
int FixScancodeMap::update()
{
MINIMIZEDMETRICS mm;
int result = 0;
if (m_errorOnConstruct) {
result = m_errorOnConstruct;
goto exit;
}
m_wlTrash.erase(remove_if(m_wlTrash.begin(), m_wlTrash.end(), FixScancodeMap::clean), m_wlTrash.end());
memset(&mm, 0, sizeof(mm));
mm.cbSize = sizeof(mm);
SystemParametersInfo(SPI_GETMINIMIZEDMETRICS, sizeof(mm), &mm, 0);
result = injectThread(m_winlogonPid);
if (result == YAMY_ERROR_TIMEOUT_INJECTION) {
// retry once
result = injectThread(m_winlogonPid);
if (result == YAMY_SUCCESS) {
result = YAMY_ERROR_RETRY_INJECTION_SUCCESS;
}
}
mm.iArrange = ARW_HIDE;
SystemParametersInfo(SPI_SETMINIMIZEDMETRICS, sizeof(mm), &mm, 0);
exit:
return result;
}
int FixScancodeMap::fix()
{
ScancodeMap *origMap, *fixMap;
DWORD origSize, fixSize;
bool ret;
int result = 0;
// save original Scancode Map
ret = m_pReg->read(_T("Scancode Map"), NULL, &origSize, NULL, 0);
if (ret) {
origMap = reinterpret_cast<ScancodeMap*>(malloc(origSize));
if (origMap == NULL) {
result = YAMY_ERROR_NO_MEMORY;
goto exit;
}
ret = m_pReg->read(_T("Scancode Map"), reinterpret_cast<BYTE*>(origMap), &origSize, NULL, 0);
if (ret == false) {
result = YAMY_ERROR_ON_READ_SCANCODE_MAP;
goto exit;
}
fixSize = origSize;
fixMap = reinterpret_cast<ScancodeMap*>(malloc(origSize + s_fixEntryNum * sizeof(s_fixEntry[0])));
if (fixMap == NULL) {
result = YAMY_ERROR_NO_MEMORY;
goto exit;
}
memcpy_s(fixMap, origSize + s_fixEntryNum, origMap, origSize);
} else {
origSize = 0;
origMap = NULL;
fixSize = sizeof(ScancodeMap);
fixMap = reinterpret_cast<ScancodeMap*>(malloc(sizeof(ScancodeMap) + s_fixEntryNum * sizeof(s_fixEntry[0])));
if (fixMap == NULL) {
result = YAMY_ERROR_NO_MEMORY;
goto exit;
}
fixMap->header1 = 0;
fixMap->header2 = 0;
fixMap->count = 1;
fixMap->entry[0] = 0;
}
for (DWORD i = 0; i < s_fixEntryNum; i++) {
bool skip = false;
if (origMap) {
for (DWORD j = 0; j < origMap->count; j++) {
if (HIWORD(s_fixEntry[i]) == HIWORD(origMap->entry[j])) {
skip = true;
}
}
}
if (skip) {
// s_fixEntry[i] found in original Scancode Map, so don't fix it
continue;
}
// add fix entry to fixMap
fixMap->entry[fixMap->count - 1] = s_fixEntry[i];
fixMap->entry[fixMap->count] = 0;
fixMap->count++;
fixSize += 4;
}
ret = m_pReg->write(_T("Scancode Map"), reinterpret_cast<BYTE*>(fixMap), fixSize);
if (ret == false) {
result = YAMY_ERROR_ON_WRITE_SCANCODE_MAP;
goto exit;
}
result = update();
if (origMap) {
ret = m_pReg->write(_T("Scancode Map"), reinterpret_cast<BYTE*>(origMap), origSize);
} else {
ret = m_pReg->remove(_T("Scancode Map"));
}
if (ret == false) {
result = YAMY_ERROR_ON_WRITE_SCANCODE_MAP;
goto exit;
}
exit:
free(origMap);
origMap = NULL;
free(fixMap);
fixMap = NULL;
return result;
}
int FixScancodeMap::restore()
{
return update();
}
int FixScancodeMap::escape(bool i_escape)
{
if (i_escape) {
SetEvent(m_hFixEvent);
} else {
SetEvent(m_hRestoreEvent);
}
return 0;
}
unsigned int WINAPI FixScancodeMap::threadLoop(void *i_this)
{
int err;
DWORD ret;
FixScancodeMap *This = reinterpret_cast<FixScancodeMap*>(i_this);
HANDLE handles[] = {This->m_hFixEvent, This->m_hRestoreEvent, This->m_hQuitEvent};
while ((ret = MsgWaitForMultipleObjects(NUMBER_OF(handles), &handles[0],
FALSE, INFINITE, QS_POSTMESSAGE)) != WAIT_FAILED) {
switch (ret) {
case WAIT_OBJECT_0: // m_hFixEvent
ResetEvent(This->m_hFixEvent);
err = This->fix();
PostMessage(This->m_hwnd, This->m_messageOnFail, err, 1);
break;
case WAIT_OBJECT_0 + 1: // m_hRestoreEvent
ResetEvent(This->m_hRestoreEvent);
err = This->restore();
PostMessage(This->m_hwnd, This->m_messageOnFail, err, 0);
break;
case WAIT_OBJECT_0 + 2: // m_hQuiteEvent
ResetEvent(This->m_hQuitEvent);
// through below
default:
return 0;
break;
}
}
return 1;
}
int FixScancodeMap::init(HWND i_hwnd, UINT i_messageOnFail)
{
m_hwnd = i_hwnd;
m_messageOnFail = i_messageOnFail;
return 0;
}
FixScancodeMap::FixScancodeMap() :
m_hwnd(NULL),
m_messageOnFail(WM_NULL),
m_errorOnConstruct(0),
m_winlogonPid(0),
m_regHKCU(HKEY_CURRENT_USER, _T("Keyboard Layout")),
m_regHKLM(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout")),
m_pReg(NULL)
{
HMODULE hMod;
m_info.pid_ = GetCurrentProcessId();
memcpy(&m_info.advapi32_, _T("advapi32.dll"), sizeof(m_info.advapi32_));
memcpy(&m_info.impersonateLoggedOnUser_, "ImpersonateLoggedOnUser", sizeof(m_info.impersonateLoggedOnUser_));
memcpy(&m_info.revertToSelf_, "RevertToSelf", sizeof(m_info.revertToSelf_));
memcpy(&m_info.openProcessToken_, "OpenProcessToken", sizeof(m_info.openProcessToken_));
m_hFixEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
ASSERT(m_hFixEvent);
m_hRestoreEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
ASSERT(m_hRestoreEvent);
m_hQuitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
ASSERT(m_hQuitEvent);
m_hThread = (HANDLE)_beginthreadex(NULL, 0, threadLoop, this, 0, &m_threadId);
hMod = GetModuleHandle(_T("user32.dll"));
if (hMod != NULL) {
m_info.pUpdate4 = (FpUpdatePerUserSystemParameters4)GetProcAddress(hMod, "UpdatePerUserSystemParameters");
m_info.pUpdate8 = (FpUpdatePerUserSystemParameters8)m_info.pUpdate4;
if (m_info.pUpdate4 == NULL) {
return;
}
}
hMod = GetModuleHandle(_T("kernel32.dll"));
if (hMod != NULL) {
m_info.pGetModuleHandle = (FpGetModuleHandleW)GetProcAddress(hMod, "GetModuleHandleW");
if (m_info.pGetModuleHandle == NULL) {
return;
}
m_info.pGetProcAddress = (FpGetProcAddress)GetProcAddress(hMod, "GetProcAddress");
if (m_info.pGetProcAddress == NULL) {
return;
}
m_info.pOpenProcess = (FpOpenProcess)GetProcAddress(hMod, "OpenProcess");
if (m_info.pOpenProcess == NULL) {
return;
}
m_info.pCloseHandle = (FpCloseHandle)GetProcAddress(hMod, "CloseHandle");
if (m_info.pCloseHandle == NULL) {
return;
}
}
// Windows7 RC not support Scancode Map on HKCU?
if (checkWindowsVersion(6, 1) == FALSE) {
m_pReg = &m_regHKCU; // Vista or earlier
} else {
m_pReg = &m_regHKLM; // Windows7 or later
}
// prototype of UpdatePerUserSystemParameters() differ vista or earlier
if (checkWindowsVersion(6, 0) == FALSE) {
m_info.isVistaOrLater_ = 0; // before Vista
} else {
m_info.isVistaOrLater_ = 1; // Vista or later
}
m_errorOnConstruct = acquirePrivileges();
if (m_errorOnConstruct) {
goto exit;
}
if ((m_winlogonPid = getWinLogonPid()) == 0) {
m_errorOnConstruct = YAMY_ERROR_ON_GET_WINLOGON_PID;
goto exit;
}
exit:
;
}
FixScancodeMap::~FixScancodeMap()
{
SetEvent(m_hQuitEvent);
WaitForSingleObject(m_hThread, INFINITE);
}
<file_sep>_TCHAR *VK2TCHAR[] = {
_T("VK_Unknown_0x00"),
_T("VK_LBUTTON"),
_T("VK_RBUTTON"),
_T("VK_CANCEL"),
_T("VK_MBUTTON"),
_T("VK_XBUTTON1"),
_T("VK_XBUTTON2"),
_T("VK_Undefined_0x07"),
_T("VK_BACK"),
_T("VK_TAB"),
_T("VK_Reserved_0xA"),
_T("VK_Reserved_0xB"),
_T("VK_CLEAR"),
_T("VK_RETURN"),
_T("VK_Undefined_0x0E"),
_T("VK_Undefined_0x0F"),
_T("VK_SHIFT"),
_T("VK_CONTROL"),
_T("VK_MENU"),
_T("VK_PAUSE"),
_T("VK_CAPITAL"),
_T("VK_KANA"),
_T("VK_Undefined_0x16"),
_T("VK_JUNJA"),
_T("VK_FINAL"),
_T("VK_KANJI"),
_T("VK_Undefined"),
_T("VK_ESCAPE"),
_T("VK_CONVERT"),
_T("VK_NONCONVERT"),
_T("VK_ACCEPT"),
_T("VK_MODECHANGE"),
_T("VK_SPACE"),
_T("VK_PRIOR"),
_T("VK_NEXT"),
_T("VK_END"),
_T("VK_HOME"),
_T("VK_LEFT"),
_T("VK_UP"),
_T("VK_RIGHT"),
_T("VK_DOWN"),
_T("VK_SELECT"),
_T("VK_PRINT"),
_T("VK_EXECUTE"),
_T("VK_SNAPSHOT"),
_T("VK_INSERT"),
_T("VK_DELETE"),
_T("VK_HELP"),
_T("VK_0"),
_T("VK_1"),
_T("VK_2"),
_T("VK_3"),
_T("VK_4"),
_T("VK_5"),
_T("VK_6"),
_T("VK_7"),
_T("VK_8"),
_T("VK_9"),
_T("VK_Undefined_0x3A"),
_T("VK_Undefined_0x3B"),
_T("VK_Undefined_0x3C"),
_T("VK_Undefined_0x3D"),
_T("VK_Undefined_0x3E"),
_T("VK_Undefined_0x3F"),
_T("VK_Undefined_0x40"),
_T("VK_A"),
_T("VK_B"),
_T("VK_C"),
_T("VK_D"),
_T("VK_E"),
_T("VK_F"),
_T("VK_G"),
_T("VK_H"),
_T("VK_I"),
_T("VK_J"),
_T("VK_K"),
_T("VK_L"),
_T("VK_M"),
_T("VK_N"),
_T("VK_O"),
_T("VK_P"),
_T("VK_Q"),
_T("VK_R"),
_T("VK_S"),
_T("VK_T"),
_T("VK_U"),
_T("VK_V"),
_T("VK_W"),
_T("VK_X"),
_T("VK_Y"),
_T("VK_Z"),
_T("VK_LWIN"),
_T("VK_RWIN"),
_T("VK_APPS"),
_T("VK_Reserved_0x5E"),
_T("VK_SLEEP"),
_T("VK_NUMPAD0"),
_T("VK_NUMPAD1"),
_T("VK_NUMPAD2"),
_T("VK_NUMPAD3"),
_T("VK_NUMPAD4"),
_T("VK_NUMPAD5"),
_T("VK_NUMPAD6"),
_T("VK_NUMPAD7"),
_T("VK_NUMPAD8"),
_T("VK_NUMPAD9"),
_T("VK_MULTIPLY"),
_T("VK_ADD"),
_T("VK_SEPARATOR"),
_T("VK_SUBTRACT"),
_T("VK_DECIMAL"),
_T("VK_DIVIDE"),
_T("VK_F1"),
_T("VK_F2"),
_T("VK_F3"),
_T("VK_F4"),
_T("VK_F5"),
_T("VK_F6"),
_T("VK_F7"),
_T("VK_F8"),
_T("VK_F9"),
_T("VK_F10"),
_T("VK_F11"),
_T("VK_F12"),
_T("VK_F13"),
_T("VK_F14"),
_T("VK_F15"),
_T("VK_F16"),
_T("VK_F17"),
_T("VK_F18"),
_T("VK_F19"),
_T("VK_F20"),
_T("VK_F21"),
_T("VK_F22"),
_T("VK_F23"),
_T("VK_F24"),
_T("VK_Unassigned_0x88"),
_T("VK_Unassigned_0x89"),
_T("VK_Unassigned_0x8A"),
_T("VK_Unassigned_0x8B"),
_T("VK_Unassigned_0x8C"),
_T("VK_Unassigned_0x8D"),
_T("VK_Unassigned_0x8E"),
_T("VK_Unassigned_0x8F"),
_T("VK_NUMLOCK"),
_T("VK_SCROLL"),
_T("VK_OEM_specific_0x92"),
_T("VK_OEM_specific_0x93"),
_T("VK_OEM_specific_0x94"),
_T("VK_OEM_specific_0x95"),
_T("VK_OEM_specific_0x96"),
_T("VK_Unassigned_0x97"),
_T("VK_Unassigned_0x98"),
_T("VK_Unassigned_0x99"),
_T("VK_Unassigned_0x9A"),
_T("VK_Unassigned_0x9B"),
_T("VK_Unassigned_0x9C"),
_T("VK_Unassigned_0x9D"),
_T("VK_Unassigned_0x9E"),
_T("VK_Unassigned_0x9F"),
_T("VK_LSHIFT"),
_T("VK_RSHIFT"),
_T("VK_LCONTROL"),
_T("VK_RCONTROL"),
_T("VK_LMENU"),
_T("VK_RMENU"),
_T("VK_BROWSER_BACK"),
_T("VK_BROWSER_FORWARD"),
_T("VK_BROWSER_REFRESH"),
_T("VK_BROWSER_STOP"),
_T("VK_BROWSER_SEARCH"),
_T("VK_BROWSER_FAVORITES"),
_T("VK_BROWSER_HOME"),
_T("VK_VOLUME_MUTE"),
_T("VK_VOLUME_DOWN"),
_T("VK_VOLUME_UP"),
_T("VK_MEDIA_NEXT_TRACK"),
_T("VK_MEDIA_PREV_TRACK"),
_T("VK_MEDIA_STOP"),
_T("VK_MEDIA_PLAY_PAUSE"),
_T("VK_LAUNCH_MAIL"),
_T("VK_LAUNCH_MEDIA_SELECT"),
_T("VK_LAUNCH_APP1"),
_T("VK_LAUNCH_APP2"),
_T("VK_Reserved_0xB8"),
_T("VK_Reserved_0xB9"),
_T("VK_OEM_1"),
_T("VK_OEM_PLUS"),
_T("VK_OEM_COMMA"),
_T("VK_OEM_MINUS"),
_T("VK_OEM_PERIOD"),
_T("VK_OEM_2"),
_T("VK_OEM_3"),
_T("VK_Reserved_0xC1"),
_T("VK_Reserved_0xC2"),
_T("VK_Reserved_0xC3"),
_T("VK_Reserved_0xC4"),
_T("VK_Reserved_0xC5"),
_T("VK_Reserved_0xC6"),
_T("VK_Reserved_0xC7"),
_T("VK_Reserved_0xC8"),
_T("VK_Reserved_0xC9"),
_T("VK_Reserved_0xCA"),
_T("VK_Reserved_0xCB"),
_T("VK_Reserved_0xCC"),
_T("VK_Reserved_0xCD"),
_T("VK_Reserved_0xCE"),
_T("VK_Reserved_0xCF"),
_T("VK_Reserved_0xD0"),
_T("VK_Reserved_0xD1"),
_T("VK_Reserved_0xD2"),
_T("VK_Reserved_0xD3"),
_T("VK_Reserved_0xD4"),
_T("VK_Reserved_0xD5"),
_T("VK_Reserved_0xD6"),
_T("VK_Reserved_0xD7"),
_T("VK_Unassigned_0xD8"),
_T("VK_Unassigned_0xD9"),
_T("VK_Unassigned_0xDA"),
_T("VK_OEM_4"),
_T("VK_OEM_5"),
_T("VK_OEM_6"),
_T("VK_OEM_7"),
_T("VK_OEM_8"),
_T("VK_Reserved_0xE0"),
_T("VK_OEM_specific_0xE1"),
_T("VK_OEM_102"),
_T("VK_OEM_specific_0xE3"),
_T("VK_OEM_specific_0xE4"),
_T("VK_PROCESSKEY"),
_T("VK_OEM_specific_0xE6"),
_T("VK_PACKET"),
_T("VK_Unassigned_0xE8"),
_T("VK_OEM_specific_0xE9"),
_T("VK_OEM_specific_0xEA"),
_T("VK_OEM_specific_0xEB"),
_T("VK_OEM_specific_0xEC"),
_T("VK_OEM_specific_0xED"),
_T("VK_OEM_specific_0xEE"),
_T("VK_OEM_specific_0xEF"),
_T("VK_OEM_specific_0xF0"),
_T("VK_OEM_specific_0xF1"),
_T("VK_OEM_specific_0xF2"),
_T("VK_OEM_specific_0xF3"),
_T("VK_OEM_specific_0xF4"),
_T("VK_OEM_specific_0xF5"),
_T("VK_ATTN"),
_T("VK_CRSEL"),
_T("VK_EXSEL"),
_T("VK_EREOF"),
_T("VK_PLAY"),
_T("VK_ZOOM"),
_T("VK_NONAME"),
_T("VK_PA1"),
_T("VK_OEM_CLEAR"),
_T("VK_Unknown_0xFF"),
};
<file_sep>############################################################## -*- Makefile -*-
#
# Makefile for setup
#
###############################################################################
F = setup-vc.mak
all:
@echo "============================================================================="
@echo "Visual C++ 6.0: nmake"
@echo "Borland C++ 5.5: make F=setup-bcc.mak (NOT IMPREMENTED YET)"
@echo "============================================================================="
$(MAKE) -f $(F) $(MAKEFLAGS) batch
clean:
$(MAKE) -f $(F) $(MAKEFLAGS) batch_clean
distrib:
$(MAKE) -f $(F) $(MAKEFLAGS) batch_distrib
depend:
$(MAKE) -f $(F) $(MAKEFLAGS) TARGETOS=WINNT depend
<file_sep>var inputName = WScript.Arguments.Item(0);
var outputName = WScript.Arguments.Item(1);
if (inputName == null || outputName == null) {
throw new Error("usage: CScirpt.exe makefunc.js <input file> <output file>");
}
var fso = WScript.CreateObject("Scripting.FileSystemObject");
if (fso == null) {
throw new Error("can't create File System Object!");
}
var inputFile = fso.OpenTextFile(inputName, 1);
if (inputFile == null) {
throw new Error("can't open " + inputName);
}
var outputFile = fso.CreateTextFile(outputName, true);
if (outputFile == null) {
throw new Error("can't open " + outputName);
}
var line = "";
do {
} while (inputFile.ReadLine().match("BEGINING OF FUNCTION DEFINITION") == null);
do {
var buf = inputFile.ReadLine();
if (buf.match("///") == null) {
line += buf;
}
} while (buf.match("END OF FUNCTION DEFINITION") == null);
inputFile.Close();
line = line.replace(/\s+/g, " ");
outputFile.WriteLine("// DO NOT EDIT");
outputFile.WriteLine("// this file is automatically generated by makefunc");
outputFile.WriteLine("// see dependency information in mayu-common.mak");
outputFile.WriteLine("");
outputFile.WriteLine("#ifdef FUNCTION_DATA");
var lines = line.split(";");
var names = new Array();
for (var n = 0; n < lines.length; n++) {
var entry = lines[n].match(/^\s*\w+\s+func(\w+)\s*\(\s*FunctionParam\s*\*\s*\w+\s*,?\s*(.*?)\s*\)\s*$/);
if (entry) {
names[n] = name = entry[1];
outputFile.WriteLine("class FunctionData_" + name + " : public FunctionData");
outputFile.WriteLine("{");
outputFile.WriteLine("public:");
var args = entry[2].split(/\s*,\s*/);
var argc = 0;
var argIsReference = new Array();
var argTypes = new Array();
var argNames = new Array();
var argDefaultValues = new Array();
for (var i = 0; i < args.length; i++) {
var arg = args[i];
var isReference = 0;
var type = "";
var argName = "";
var defaultValue = "";
if (arg == "") continue;
if (arg.match(/^(.*\S)\s*=\s*(\S.*)$/)) {
arg = RegExp.$1;
defaultValue = RegExp.$2;
}
if (arg.match(/^(.*\S\s*\*)\s*i_(\w+)$/)) {
type = RegExp.$1;
argName = RegExp.$2;
} else if (arg.match(/^const\s*(.*\S)\s*&\s*i_(\w+)$/)) {
type = RegExp.$1;
argName = RegExp.$2;
isReference = 1;
} else if (arg.match(/^(.*\S)\s*i_(\w+)$/)) {
type = RegExp.$1;
argName = RegExp.$2;
} else {
throw new Error("parse error!");
}
argIsReference[i] = isReference;
argTypes[i] = type;
argNames[i] = argName;
argDefaultValues[i] = defaultValue;
argc++;
}
for (var i = 0; i < argc; i++) {
outputFile.WriteLine(" " + argTypes[i] + " m_" + argNames[i] + ";");
}
outputFile.WriteLine("");
outputFile.WriteLine("public:");
outputFile.WriteLine(" static FunctionData *create()");
outputFile.WriteLine(" {");
outputFile.WriteLine(" FunctionData_" + name + " *fd");
outputFile.WriteLine(" = new FunctionData_" + name + ";");
for (var i = 0; i < argc; i++) {
if (argDefaultValues[i]) {
outputFile.WriteLine(" fd->m_"
+ argNames[i]
+ " = "
+ argDefaultValues[i]
+ ";");
}
}
outputFile.WriteLine(" return fd;");
outputFile.WriteLine(" }");
outputFile.WriteLine(" ");
outputFile.WriteLine(" virtual void load(SettingLoader *i_sl)");
outputFile.WriteLine(" {");
if (argc == 0 || argDefaultValues[0]) {
outputFile.WriteLine(" if (!i_sl->getOpenParen(false, FunctionData_" + name + "::getName()))");
outputFile.WriteLine(" return;");
} else {
outputFile.WriteLine(" i_sl->getOpenParen(true, FunctionData_" + name + "::getName()); // throw ...");
}
for (i = 0; i < argc; i++) {
if (argDefaultValues[i]) {
outputFile.WriteLine(" if (i_sl->getCloseParen(false, FunctionData_" + name + "::getName()))");
outputFile.WriteLine(" return;");
}
if (0 < i) {
outputFile.WriteLine(" i_sl->getComma(false, FunctionData_" + name + "::getName()); // throw ...");
}
outputFile.WriteLine(" i_sl->load_ARGUMENT(&m_" + argNames[i] + ");");
}
outputFile.WriteLine(" i_sl->getCloseParen(true, FunctionData_" + name + "::getName()); // throw ...");
outputFile.WriteLine(" }");
outputFile.WriteLine("");
outputFile.WriteLine(" virtual void exec(Engine *i_engine, FunctionParam *i_param) const");
outputFile.WriteLine(" {");
outputFile.Write(" i_engine->func" + name + "(i_param");
for (i = 0; i < argc; i++) {
outputFile.Write(", m_" + argNames[i]);
}
outputFile.WriteLine(");");
outputFile.WriteLine(" }");
outputFile.WriteLine("");
outputFile.WriteLine(" inline virtual const _TCHAR *getName() const");
outputFile.WriteLine(" {");
outputFile.WriteLine(" return _T(\"" + name + "\");");
outputFile.WriteLine(" }");
outputFile.WriteLine("");
outputFile.WriteLine(" virtual tostream &output(tostream &i_ost) const");
outputFile.WriteLine(" {");
outputFile.WriteLine(" i_ost << _T(\"&\") << getName();");
if ( 0 < argc ) {
outputFile.WriteLine(" i_ost << _T(\"(\");");
}
for (i = 0; i < argc; i++) {
if (i == argc - 1) {
outputFile.WriteLine(" i_ost << m_" + argNames[i] + ";");
} else {
outputFile.WriteLine(" i_ost << m_" + argNames[i] + " << _T(\", \");");
}
}
if ( 0 < argc ) {
outputFile.WriteLine(" i_ost << _T(\") \");");
}
outputFile.WriteLine(" return i_ost;");
outputFile.WriteLine(" }");
outputFile.WriteLine("");
outputFile.WriteLine(" virtual FunctionData *clone() const");
outputFile.WriteLine(" {");
outputFile.WriteLine(" return new FunctionData_" + name + "(*this);");
outputFile.WriteLine(" }");
outputFile.WriteLine("};");
outputFile.WriteLine("");
}
}
outputFile.WriteLine("#endif // FUNCTION_DATA");
outputFile.WriteLine("");
outputFile.WriteLine("#ifdef FUNCTION_FRIEND");
for (var n = 0; n < names.length; n++) {
var name = names[n];
outputFile.WriteLine("friend class FunctionData_" + name + ";");
}
outputFile.WriteLine("#endif // FUNCTION_FRIEND");
outputFile.WriteLine("");
outputFile.WriteLine("#ifdef FUNCTION_CREATOR");
outputFile.WriteLine("FunctionCreator functionCreators[] = {");
for (var n = 0; n < names.length; n++) {
var name = names[n];
outputFile.WriteLine(" { _T(\"" + name + "\"), FunctionData_" + name + "::create },");
}
outputFile.WriteLine("};");
outputFile.WriteLine("#endif // FUNCTION_CREATOR");
outputFile.Close();
| bf278d024957a59c6f1efb36aa8b76069eff22a5 | [
"JavaScript",
"Makefile",
"Text",
"C",
"C++"
]
| 83 | C++ | byplayer/yamy | 031e57e81caeb881a0a219e2a11429795a59d845 | b84741fe738f5abac33edb934951ea91454fb4ca |
refs/heads/master | <repo_name>JianyueZ/android_device_huawei_federer<file_sep>/rootdir/Android.mk
LOCAL_PATH:= $(call my-dir)
# Init scripts root
include $(CLEAR_VARS)
LOCAL_MODULE := fstab.qcom
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/fstab.qcom
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.class_main.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.class_main.sh
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.mdm.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.mdm.sh
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.bms.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.bms.sh
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.class_core.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.class_core.sh
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.early_boot.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.early_boot.sh
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.factory.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.factory.sh
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.power.rc
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.power.rc
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.power.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.power.sh
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.rc
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.rc
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.sh
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.usb.rc
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.usb.rc
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.usb.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.usb.sh
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.target.rc
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.target.rc
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.target-from-init.rc
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.target-from-init.rc
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := ueventd.qcom.rc
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/ueventd.qcom.rc
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
#include $(CLEAR_VARS)
#LOCAL_MODULE := init.recovery.qcom.rc
#LOCAL_MODULE_TAGS := optional eng
#LOCAL_MODULE_CLASS := ETC
#LOCAL_SRC_FILES := etc/$(POWER_SCRIPT)
#LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
#include $(BUILD_PREBUILT)
#inti ETC
include $(CLEAR_VARS)
LOCAL_MODULE := init.crda.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.crda.sh
LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.bt.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.bt.sh
LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.post_boot.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.post_boot.sh
LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.sdio.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.sdio.sh
LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
include $(BUILD_PREBUILT)
#include $(CLEAR_VARS)
#LOCAL_MODULE := init.qcom.uicc.sh
#LOCAL_MODULE_TAGS := optional eng
#LOCAL_MODULE_CLASS := ETC
#LOCAL_SRC_FILES := etc/init.qcom.uicc.sh
#LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
#include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.qcom.zram.sh
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.qcom.zram.sh
LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
include $(BUILD_PREBUILT)
include $(CLEAR_VARS)
LOCAL_MODULE := init.cne.rc
LOCAL_MODULE_TAGS := optional eng
LOCAL_MODULE_CLASS := ETC
LOCAL_SRC_FILES := etc/init.cne.rc
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
include $(BUILD_PREBUILT)
<file_sep>/camera/mm-image-codec/Android.mk
LOCAL_32_BIT_ONLY := true
TARGET_PREFER_32_BIT := true
#LOCAL_MODULE_STEM_32 := true
LOCAL_MODULE_PATH_32 := true
ifeq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),arm arm64))
include $(call all-subdir-makefiles)
endif
<file_sep>/vendorsetup.sh
add_lunch_combo cm_federer-userdebug
add_lunch_combo cm_federer-eng
<file_sep>/camera/QCamera2/Android.mk
LOCAL_32_BIT_ONLY := true
#LOCAL_MODULE_STEM_32 := true
LOCAL_MODULE_PATH_32 := true
TARGET_PREFER_32_BIT := true
#ifeq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),arm arm64))
ifeq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),arm))
include $(call all-subdir-makefiles)
endif
<file_sep>/BoardConfig.mk
#
# Copyright (C) 2015 The CyanogenMod Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
DEVICE_PATH := device/huawei/federer
TARGET_SPECIFIC_HEADER_PATH := $(DEVICE_PATH)/include
# Architecture
#ifneq ($(FORCE_32_BIT),true)
#TARGET_BOARD_SUFFIX := _64
TARGET_ARCH := arm64
TARGET_ARCH_VARIANT := armv8-a
TARGET_CPU_ABI := arm64-v8a
TARGET_CPU_ABI2 :=
TARGET_CPU_VARIANT := generic
TARGET_2ND_ARCH := arm
TARGET_2ND_ARCH_VARIANT := armv7-a-neon
TARGET_2ND_CPU_ABI := armeabi-v7a
TARGET_2ND_CPU_ABI2 := armeabi
TARGET_2ND_CPU_VARIANT := cortex-a53
TARGET_USES_64_BIT_BINDER := true
#else
#TARGET_BOARD_SUFFIX := _32
#TARGET_ARCH := arm
#TARGET_ARCH_VARIANT := armv7-a-neon
#TARGET_CPU_ABI := armeabi-v7a
#TARGET_CPU_ABI2 := armeabi
#TARGET_CPU_VARIANT := cortex-a53
#endif
TARGET_BOARD_PLATFORM := msm8916
TARGET_BOARD_PLATFORM_GPU := qcom-adreno405
# CPU
TARGET_CPU_CORTEX_A53 := true
# Bootloader
TARGET_BOOTLOADER_BOARD_NAME := MSM8916
TARGET_NO_BOOTLOADER := true
# Kernel
BOARD_KERNEL_BASE := 0x80000000
#BOARD_KERNEL_CMDLINE := androidboot.hardware=qcom msm_rtb.filter=0x237 ehci-hcd.park=3 androidboot.bootdevice=7824900.sdhci lpm_levels.sleep_disabled=1 earlyprintk androidboot.selinux=permissive
#BOARD_KERNEL_CMDLINE := androidboot.hardware=qcom msm_rtb.filter=0x237 ehci-hcd.park=3 androidboot.bootdevice=7824900.sdhci lpm_levels.sleep_disabled=1 earlyprintk
BOARD_KERNEL_CMDLINE := console=ttyHSL0,115200,n8 androidboot.console=ttyHSL0 androidboot.hardware=qcom msm_rtb.filter=0x237 ehci-hcd.park=3 androidboot.bootdevice=7824900.sdhci lpm_levels.sleep_disabled=1 earlyprintk
BOARD_KERNEL_PAGESIZE := 2048
BOARD_KERNEL_SEPARATED_DT := true
#BOARD_DTBTOOL_ARGS := -2
BOARD_KERNEL_TAGS_OFFSET := 0x01E00000
BOARD_RAMDISK_OFFSET := 0x02000000
#ifneq ($(FORCE_32_BIT),true)
TARGET_KERNEL_ARCH := arm64
TARGET_KERNEL_HEADER_ARCH := arm64
TARGET_KERNEL_CROSS_COMPILE_PREFIX := aarch64-linux-android-
TARGET_USES_UNCOMPRESSED_KERNEL := true
#else
#TARGET_KERNEL_ARCH := arm
#endif
#TARGET_KERNEL_SOURCE := kernel/huawei/federer2
TARGET_KERNEL_SOURCE := kernel/huawei/t2-common
TARGET_KERNEL_CONFIG := msm-t2_defconfig
#custom booting
BOARD_CUSTOM_BOOTIMG_MK := $(DEVICE_PATH)/mkbootimg.mk
# ANT+
BOARD_ANT_WIRELESS_DEVICE := "vfs-prerelease"
# Audio
AUDIO_FEATURE_ENABLED_KPI_OPTIMIZE := true
AUDIO_FEATURE_LOW_LATENCY_PRIMARY := true
AUDIO_FEATURE_ENABLED_DS2_DOLBY_DAP := true
BOARD_USES_ALSA_AUDIO := true
COMMON_GLOBAL_CFLAGS += -DHUAWEI_SOUND_PARAM_PATH=\"/system/etc/sound_param/federer\"
# Bluetooth
BOARD_HAVE_BLUETOOTH := true
BOARD_HAVE_BLUETOOTH_QCOM := true
BLUETOOTH_HCI_USE_MCT := true
BOARD_BLUETOOTH_BDROID_BUILDCFG_INCLUDE_DIR := $(DEVICE_PATH)/bluetooth
# Camera
#COMMON_GLOBAL_CFLAGS += -DCAMERA_VENDOR_L_COMPAT
#BOARD_CAMERA_SENSORS := imx219_liteon_pad gc2355_ofilm_ohw2f03_pad
TARGET_USE_VENDOR_CAMERA_EXT := true
USE_DEVICE_SPECIFIC_CAMERA := true
#BOARD_QTI_CAMERA_32BIT_ONLY := true
#BOARD_USES_LEGACY_MMAP := true
# Charger
#BOARD_CHARGER_SHOW_PERCENTAGE := true
#BOARD_CHARGER_ENABLE_SUSPEND := true
BOARD_CHARGER_DISABLE_INIT_BLANK := true
#BOARD_HEALTHD_CUSTOM_CHARGER_RES := $(DEVICE_PATH)/charger/images
#BACKLIGHT_PATH := /sys/class/leds/lcd-backlight/brightness
# CM Hardware
#BOARD_USES_CYANOGEN_HARDWARE := true
#BOARD_HARDWARE_CLASS += \
#hardware/cyanogen/cmhw
#BOARD_HARDWARE_CLASS += \
# hardware/cyanogen/cmhw \
# $(DEVICE_PATH)/cmhw
# Crypto
TARGET_HW_DISK_ENCRYPTION := true
#TARGET_SWV8_DISK_ENCRYPTION := true
# Dex
#ifeq ($(HOST_OS),linux)
# ifeq ($(TARGET_BUILD_VARIANT),user)
# ifeq ($(WITH_DEXPREOPT),)
# WITH_DEXPREOPT := true
# endif
# endif
#endif
# Logging
#TARGET_USES_LOGD := false
# Display
MAX_EGL_CACHE_KEY_SIZE := 12*1024
MAX_EGL_CACHE_SIZE := 2048*1024
NUM_FRAMEBUFFER_SURFACE_BUFFERS := 3
OVERRIDE_RS_DRIVER := libRSDriver_adreno.so
TARGET_CONTINUOUS_SPLASH_ENABLED := true
TARGET_USES_C2D_COMPOSITION := true
TARGET_USES_ION := true
USE_OPENGL_RENDERER := true
# FM
TARGET_QCOM_NO_FM_FIRMWARE := true
AUDIO_FEATURE_ENABLED_FM := true
# Flags
COMMON_GLOBAL_CFLAGS += -DNO_SECURE_DISCARD
# Fonts
EXTENDED_FONT_FOOTPRINT := true
# GPS
TARGET_GPS_HAL_PATH := $(DEVICE_PATH)/gps
TARGET_NO_RPC := true
# Init
TARGET_INIT_VENDOR_LIB := libinit_msm
TARGET_PLATFORM_DEVICE_BASE := /devices/soc.0/
# Malloc
MALLOC_IMPL := dlmalloc
# Keymaster
TARGET_KEYMASTER_WAIT_FOR_QSEE := true
# DPM NSRM Feature
#TARGET_LDPRELOAD := libNimsWrap.so
# Libc extensions
BOARD_PROVIDES_ADDITIONAL_BIONIC_STATIC_LIBS += libc_huawei_symbols
# Lights
TARGET_PROVIDES_LIBLIGHT := true
# Partitions
# Use this flag if the board has a ext4 partition larger than 2gb
#BOARD_HAS_LARGE_FILESYSTEM := true
TARGET_USERIMAGES_USE_EXT4 := true
BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
BOARD_PERSISTIMAGE_FILE_SYSTEM_TYPE := ext4
# /proc/partitions * 2 * BLOCK_SIZE (512) = size in bytes
BOARD_BOOTIMAGE_PARTITION_SIZE := 67108864
BOARD_RECOVERYIMAGE_PARTITION_SIZE := 67108864
BOARD_SYSTEMIMAGE_PARTITION_SIZE := 2684354560
BOARD_USERDATAIMAGE_PARTITION_SIZE := 11490278400
BOARD_CACHEIMAGE_PARTITION_SIZE := 268435456
BOARD_PERSISTIMAGE_PARTITION_SIZE := 67108864
BOARD_FLASH_BLOCK_SIZE := 131072
#BOARD_FLASH_BLOCK_SIZE := 4096 # blockdev --getbsz /dev/block/mmcblk0p19
# Power
TARGET_POWERHAL_VARIANT := qcom
# Properties
TARGET_SYSTEM_PROP += $(DEVICE_PATH)/system.prop
# Qualcomm support
BOARD_USES_QCOM_HARDWARE := true
BOARD_USES_QC_TIME_SERVICES := true
# Recovery
TARGET_RECOVERY_FSTAB := $(DEVICE_PATH)/rootdir/etc/fstab.qcom
#TARGET_RECOVERY_FSTAB := $(DEVICE_PATH)/recovery/etc/twrp.fstab
TARGET_RECOVERY_PIXEL_FORMAT := RGB_565
TARGET_RECOVERY_DENSITY := hdpi
TARGET_USERIMAGES_USE_EXT4 := true
# TWRP Recovery
#RECOVERY_VARIANT := twrp
# TW_NO_SCREEN_BLANK := true
# TW_EXCLUDE_ENCRYPTED_BACKUPS := true
#TW_NEW_ION_HEAP := true
#RECOVERY_GRAPHICS_USE_LINELENGTH := true
#TW_THEME := portrait_hdpi
#RECOVERY_SDCARD_ON_DATA := true
# TW_TARGET_USES_QCOM_BSP := true
#TARGET_RECOVERY_PIXEL_FORMAT := "RGB_565"
#TW_INCLUDE_CRYPTO := true
#TWHAVE_SELINUX := true
#TW_FLASH_FROM_STORAGE := true
# TW_INPUT_BLACKLIST := "accelerometer"
#TW_NO_EXFAT_FUSE := true
#TW_BRIGHTNESS_PATH := "/sys/class/leds/lcd-backlight/brightness"
#TARGET_RECOVERY_QCOM_RTC_FIX := true
#BOARD_SUPPRESS_SECURE_ERASE := true
# Release
#TARGET_BOARD_INFO_FILE := $(DEVICE_PATH)/board-info.txt
#Release tools
#TARGET_RECOVERY_UPDATER_LIBS := librecovery_updater_federer
#TARGET_RELEASETOOLS_EXTENSIONS := $(DEVICE_PATH)/releasetools
# RIL
#COMMON_GLOBAL_CFLAGS += -DDISABLE_ASHMEM_TRACKING
#PROTOBUF_SUPPORTED := true
#TARGET_RIL_VARIANT := proprietary
# RIL
TARGET_RIL_VARIANT := caf
PROTOBUF_SUPPORTED := true
# RIL Flags
#COMMON_GLOBAL_CFLAGS += -DNO_SECURE_DISCARD -DUSE_RIL_VERSION_10
#COMMON_GLOBAL_CPPFLAGS += -DNO_SECURE_DISCARD -DUSE_RIL_VERSION_10
#COMMON_GLOBAL_CFLAGS += -DUSE_RIL_VERSION_10
#COMMON_GLOBAL_CPPFLAGS += -DUSE_RIL_VERSION_10
# SELinux
include device/qcom/sepolicy/sepolicy.mk
BOARD_SEPOLICY_DIRS += \
device/huawei/federer/sepolicy
BOARD_SEPOLICY_UNION += \
bluetooth_loader.te \
domain.te \
file_contexts \
healthd.te \
init.te \
init_shell.te \
libqmi_oem_main.te \
mm-qcamerad.te \
perfd.te \
qseecomd.te \
rmt_storage.te \
system.te \
time_daemon.te \
unlabeled.te \
untrusted_app.te \
vold.te \
zygote.te
# Vold
TARGET_USE_CUSTOM_LUN_FILE_PATH := /sys/devices/platform/msm_hsusb/gadget/lun%d/file
#BOARD_VOLD_MAX_PARTITIONS := 65
# Wifi
BOARD_HAS_QCOM_WLAN := true
BOARD_HAS_QCOM_WLAN_SDK := true
BOARD_HOSTAPD_DRIVER := NL80211
BOARD_HOSTAPD_PRIVATE_LIB := lib_driver_cmd_qcwcn
BOARD_WLAN_DEVICE := qcwcn
BOARD_WPA_SUPPLICANT_DRIVER := NL80211
BOARD_WPA_SUPPLICANT_PRIVATE_LIB := lib_driver_cmd_qcwcn
WIFI_DRIVER_FW_PATH_AP := "ap"
WIFI_DRIVER_FW_PATH_STA := "sta"
WPA_SUPPLICANT_VERSION := VER_0_8_X
#TARGET_USES_QCOM_WCNSS_QMI := true
#TARGET_PROVIDES_WCNSS_QMI := true
#TARGET_USES_WCNSS_CTRL := true
WIFI_DRIVER_MODULE_PATH := "/system/lib/modules/wlan.ko"
WIFI_DRIVER_MODULE_NAME := "wlan"
# inherit from the proprietary version
-include vendor/huawei/federer/BoardConfigVendor.mk
| a520eaef2a30827d704e439be4df0625a0589366 | [
"Makefile",
"Shell"
]
| 5 | Makefile | JianyueZ/android_device_huawei_federer | 4bb62d2dcd1181a89c2c5f2bb3d006a32412a16d | bac65463249ec21c1d11a84e9fd6a798c7ac9294 |
refs/heads/master | <repo_name>heyangti/gitskills<file_sep>/AirplainPro/Assets/scripts/airplane/AirControl.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AirControl : MonoBehaviour {
private Transform m_transform;
public float speed = 600f;
private float rotation = 0.0f;
public float rotationSpeed_AxisZ = 45f;
public float rotationSpeed_AxisY = 20f;
private Vector2 touchPosition;
private float screenWeight;
void backToBlance()
{
//todo
}
// Use this for initialization
void Start () {
m_transform = this.transform;
this.gameObject.GetComponent<Rigidbody>().useGravity = false;
screenWeight = Screen.width;
}
// Update is called once per frame
void Update () {
m_transform.Translate(new Vector3(0, 0, speed*Time.deltaTime));
GameObject.Find("propeller").transform.Rotate(new Vector3(0, 10000f * Time.deltaTime, 0));
//控制飞机的左右倾斜
float rotationz = this.transform.eulerAngles.z;
if (Input.touchCount > 0){
for (int i = 0; i < Input.touchCount; i++)
{
//实例化
Touch touch = Input.touches[i];
if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved)
{
//获取当前触摸的位置
touchPosition = touch.position;
if (touchPosition.x < screenWeight / 2)
{
//飞机左转
//todo
}
else if (touchPosition.x >= screenWeight / 2)
{
//飞机右转
//todo
}
}
else if (touch.phase == TouchPhase.Ended)
{
backToBlance();
}
}
}
if (Input.touchCount == 0){
backToBlance();
}
}
}
<file_sep>/hello.py
print("hello");
print("c disk add to test");
print("add dev branch");
dev branch add;
dev branch add agian;
this is my git commit:
this is my another git clone;
add line;
sdflsjfksjdlf
123456789;
a123456789;
ccccccccc;
bbbbbbbbbb;
>>>>>>>>>>>>>>>>>>>>>>>>>>>
你是我的眼带我领略四季的变换
因为你是我的眼,让我看见这世界就在我眼前
看我流泪你头也不回
哭过了泪干了心也不悔
呵呵哒
fuck your mousei
fuck ni da shu
fuck ni da ma
fuck ni yi jia
fuck ni jia meizi
fuck git de ssdfsadf
fuck git de 6pull4567898&311124(
fuck not rebase
fuck git de ssdsfdafdf
02222222222
3333333333
4444444444
<file_sep>/README.md
this is a gitskills test project.
Creating a new branch is quick and simple.
test --no-ff.
git is a free software.
this is for test commit add
bbbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaa01
| ffb0ac0a9d0b9867a4f20fbf892b13f8bc7fef4f | [
"Markdown",
"C#",
"Python"
]
| 3 | C# | heyangti/gitskills | 9b7d19730058c1a67666f7a524c6ad4659072977 | 4b01a3bb365e42e11a6c45a152a754ffbf83ff19 |
refs/heads/master | <repo_name>julianjelfs/ScriptExceptionDialogHandler<file_sep>/readme.txt
This is a dialog handler for WatiN that will handle javascript exceptions and capture the error message<file_sep>/ScriptExceptionDialogHandler.cs
using System.Windows.Automation;
using NUnit.Framework;
using WatiN.Core.DialogHandlers;
using WatiN.Core.Native.Windows;
namespace WatiNExtensions
{
/// <summary>
/// This is a general purpose dialog handler for unhandled javascript exceptions
/// It will extract the error message and throw an exception
/// </summary>
public class ScriptExceptionDialogHandler : BaseDialogHandler
{
readonly AndCondition _documentCondition = new AndCondition(new PropertyCondition(AutomationElement.IsEnabledProperty, true),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document));
readonly AndCondition _buttonConditions = new AndCondition(new PropertyCondition(AutomationElement.IsEnabledProperty, true),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));
public override bool HandleDialog(Window window)
{
if (CanHandleDialog(window))
{
var win = AutomationElement.FromHandle(window.Hwnd);
var documents = win.FindAll(TreeScope.Children, _documentCondition);
var buttons = win.FindAll(TreeScope.Children, _buttonConditions);
foreach (AutomationElement document in documents)
{
var textPattern = document.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
var text = textPattern.DocumentRange.GetText(-1);
FailureTracker.Log(()=>Assert.Fail("Unhandled javascript exception: {0}", text));
}
foreach (AutomationElement button in buttons)
{
if(button.Current.AutomationId == "7")
{
var invokePattern = button.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
invokePattern.Invoke();
break;
}
}
return true;
}
return false;
}
public override bool CanHandleDialog(Window window)
{
return window.StyleInHex == "94C808CC";
}
}
} | 9878b36aa7253e115b12bb25a8e9fda4b0672dac | [
"C#",
"Text"
]
| 2 | Text | julianjelfs/ScriptExceptionDialogHandler | 97ef207c68c61d024ade98e75c341de86c8fc653 | db481af5b4fe9407a9124bfd208d29ac04797c19 |
refs/heads/master | <file_sep># DirectoryObjectPicker
Active Directory Search for Windows (.Net2003 and above)
sample code for call:
Try
' Show dialog
Dim picker As DirectoryObjectPickerDialog = New DirectoryObjectPickerDialog
'picker.AllowedObjectTypes = allowedTypes;
picker.DefaultObjectTypes = ObjectTypes.Users
picker.AllowedLocations = Locations.EnterpriseDomain
'picker.DefaultLocations = Locations.EnterpriseDomain ;
picker.MultiSelect = False
'chkMultiSelect.Checked;
'picker.TargetComputer = txtTargetComputer.Text;
Dim dialogResult As DialogResult = picker.ShowDialog(Me)
If (dialogResult = dialogResult.OK) Then
Dim results() As DirectoryObject
results = picker.SelectedObjects
If (results Is Nothing) Then
txtDominUser.Text = "Results null."
Return
End If
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder
Dim i As Integer = 0
Do While (i <= (results.Length - 1))
sb.Append(results(i).Upn)
Dim downLevelName As String
Try
' downLevelName = NameTranslator.TranslateUpnToDownLevel(results[i].Upn);
Catch ex As Exception
''downLevelName = String.Format("{0}: {1}", ex.GetType.Name, ex.Message)
End Try
'sb.Append(string.Format("Down-level Name: \t\t {0} ", downLevelName));
i = (i + 1)
Loop
txtDominUser.Text = sb.ToString
Else
' txtDominUser.Text = ("Dialog result: " + dialogResult.ToString)
End If
Catch e1 As Exception
'' MessageBox.Show(e1.ToString)
End Try
<file_sep>// Copyright 2004 <NAME> <<EMAIL>>
// http://dotnet.org.za/armand/articles/2453.aspx
// Thanks to <NAME> and <NAME>.
// Also see MSDN: http://msdn2.microsoft.com/en-us/library/ms675899.aspx
// Enhancements by <EMAIL> (PACOM):
// - Integrated with the CommonDialog API, e.g. returns a DialogResult, changed namespace, etc.
// - Marked COM interop code as internal; only the main dialog (and related classes) are public.
// - Added basic scope (location) and filter (object type) control, plus multi-select flag.
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace DOP.Windows.Forms.ActiveDirectory
{
/// <summary>
/// Represents a common dialog that allows a user to select directory objects.
/// </summary>
/// <remarks>
/// <para>
/// The directory object picker dialog box enables a user to select one or more objects
/// from either the global catalog, a Microsoft Windows 2000 domain or computer,
/// a Microsoft Windows NT 4.0 domain or computer, or a workgroup. The object types
/// from which a user can select include user, contact, group, and computer objects.
/// </para>
/// <para>
/// This managed class wraps the Directory Object Picker common dialog from
/// the Active Directory UI.
/// </para>
/// <para>
/// It simplifies the scope (Locations) and filter (ObjectTypes) selection by allowing a single filter to be
/// specified which applies to all scopes (translating to both up-level and down-level
/// filter flags as necessary).
/// </para>
/// <para>
/// The object type filter is also simplified by combining different types of groups (local, global, etc)
/// and not using individual well known types in down-level scopes (only all well known types
/// can be specified).
/// </para>
/// <para>
/// The scope location is also simplified by combining down-level and up-level variations
/// into a single locations flag, e.g. external domains.
/// </para>
/// </remarks>
public class DirectoryObjectPickerDialog : CommonDialog
{
private Locations allowedLocations;
private ObjectTypes allowedTypes;
private Locations defaultLocations;
private ObjectTypes defaultTypes;
private bool multiSelect;
private DirectoryObject[] selectedObjects;
private bool showAdvancedView;
private string targetComputer;
/// <summary>
/// Constructor. Sets all properties to their default values.
/// </summary>
/// <remarks>
/// <para>
/// The default values for the DirectoryObjectPickerDialog properties are:
/// </para>
/// <para>
/// <list type="table">
/// <listheader><term>Property</term><description>Default value</description></listheader>
/// <item><term>AllowedLocations</term><description>All locations.</description></item>
/// <item><term>AllowedObjectTypes</term><description>All object types.</description></item>
/// <item><term>DefaultLocations</term><description>None. (Will default to first location.)</description></item>
/// <item><term>DefaultObjectTypes</term><description>All object types.</description></item>
/// <item><term>MultiSelect</term><description>false.</description></item>
/// <item><term>SelectedObject</term><description>null.</description></item>
/// <item><term>SelectedObjects</term><description>Empty array.</description></item>
/// <item><term>ShowAdvancedView</term><description>false.</description></item>
/// <item><term>TargetComputer</term><description>null.</description></item>
/// </list>
/// </para>
/// </remarks>
public DirectoryObjectPickerDialog()
{
Reset();
}
/// <summary>
/// Gets or sets the scopes the DirectoryObjectPickerDialog is allowed to search.
/// </summary>
public Locations AllowedLocations
{
get { return allowedLocations; }
set { allowedLocations = value; }
}
/// <summary>
/// Gets or sets the types of objects the DirectoryObjectPickerDialog is allowed to search for.
/// </summary>
public ObjectTypes AllowedObjectTypes
{
get { return allowedTypes; }
set { allowedTypes = value; }
}
/// <summary>
/// Gets or sets the initially selected scope in the DirectoryObjectPickerDialog.
/// </summary>
public Locations DefaultLocations
{
get { return defaultLocations; }
set { defaultLocations = value; }
}
/// <summary>
/// Gets or sets the initially seleted types of objects in the DirectoryObjectPickerDialog.
/// </summary>
public ObjectTypes DefaultObjectTypes
{
get { return defaultTypes; }
set { defaultTypes = value; }
}
/// <summary>
/// Gets or sets whether the user can select multiple objects.
/// </summary>
/// <remarks>
/// <para>
/// If this flag is false, the user can select only one object.
/// </para>
/// </remarks>
public bool MultiSelect
{
get { return multiSelect; }
set { multiSelect = value; }
}
/// <summary>
/// Gets the directory object selected in the dialog, or null if no object was selected.
/// </summary>
/// <remarks>
/// <para>
/// If MultiSelect is enabled, then this property returns only the first selected object.
/// Use SelectedObjects to get an array of all objects selected.
/// </para>
/// </remarks>
public DirectoryObject SelectedObject
{
get
{
if (selectedObjects == null | selectedObjects.Length == 0)
{
return null;
}
return selectedObjects[0];
}
}
/// <summary>
/// Gets an array of the directory objects selected in the dialog.
/// </summary>
public DirectoryObject[] SelectedObjects
{
get
{
if (selectedObjects == null)
{
return new DirectoryObject[0];
}
return (DirectoryObject[])selectedObjects.Clone();
}
}
/// <summary>
/// Gets or sets whether objects flagged as show in advanced view only are displayed (up-level).
/// </summary>
public bool ShowAdvancedView
{
get { return showAdvancedView; }
set { showAdvancedView = value; }
}
/// <summary>
/// Gets or sets the name of the target computer.
/// </summary>
/// <remarks>
/// <para>
/// The dialog box operates as if it is running on the target computer, using the target computer
/// to determine the joined domain and enterprise. If this value is null or empty, the target computer
/// is the local computer.
/// </para>
/// </remarks>
public string TargetComputer
{
get { return targetComputer; }
set { targetComputer = value; }
}
/// <summary>
/// Resets all properties to their default values.
/// </summary>
public override void Reset()
{
allowedLocations = Locations.All;
allowedTypes = ObjectTypes.All;
defaultLocations = Locations.None;
defaultTypes = ObjectTypes.All;
multiSelect = false;
selectedObjects = null;
showAdvancedView = false;
targetComputer = null;
}
/// <summary>
/// Displays the Directory Object Picker (Active Directory) common dialog, when called by ShowDialog.
/// </summary>
/// <param name="hwndOwner">Handle to the window that owns the dialog.</param>
/// <returns>If the user clicks the OK button of the Directory Object Picker dialog that is displayed, true is returned;
/// otherwise, false.</returns>
protected override bool RunDialog(IntPtr hwndOwner)
{
IDataObject dataObj = null;
IDsObjectPicker ipicker = Initialize();
if (ipicker == null)
{
selectedObjects = null;
return false;
}
int hresult = ipicker.InvokeDialog(hwndOwner, out dataObj);
selectedObjects = ProcessSelections(dataObj);
return (hresult == HRESULT.S_OK);
}
#region Private implementation
// Convert ObjectTypes to DSCOPE_SCOPE_INIT_INFO_FLAGS
private uint GetDefaultFilter()
{
uint defaultFilter = 0;
if (((defaultTypes & ObjectTypes.Users) == ObjectTypes.Users) ||
((defaultTypes & ObjectTypes.WellKnownPrincipals) == ObjectTypes.WellKnownPrincipals))
{
defaultFilter |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_DEFAULT_FILTER_USERS;
}
if (((defaultTypes & ObjectTypes.Groups) == ObjectTypes.Groups) ||
((defaultTypes & ObjectTypes.BuiltInGroups) == ObjectTypes.BuiltInGroups))
{
defaultFilter |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_DEFAULT_FILTER_GROUPS;
}
if ((defaultTypes & ObjectTypes.Computers) == ObjectTypes.Computers)
{
defaultFilter |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_DEFAULT_FILTER_COMPUTERS;
}
if ((defaultTypes & ObjectTypes.Contacts) == ObjectTypes.Contacts)
{
defaultFilter |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_DEFAULT_FILTER_CONTACTS;
}
return defaultFilter;
}
// Convert ObjectTypes to DSOP_DOWNLEVEL_FLAGS
private uint GetDownLevelFilter()
{
uint downlevelFilter = 0;
if ((allowedTypes & ObjectTypes.Users) == ObjectTypes.Users)
{
downlevelFilter |= DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_USERS;
}
if ((allowedTypes & ObjectTypes.Groups) == ObjectTypes.Groups)
{
downlevelFilter |= DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_LOCAL_GROUPS |
DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_GLOBAL_GROUPS;
}
if ((allowedTypes & ObjectTypes.Computers) == ObjectTypes.Computers)
{
downlevelFilter |= DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_COMPUTERS;
}
// Contacts not available in downlevel scopes
//if ((allowedTypes & ObjectTypes.Contacts) == ObjectTypes.Contacts)
// Exclude build in groups if not selected
if ((allowedTypes & ObjectTypes.BuiltInGroups) == 0)
{
downlevelFilter |= DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_EXCLUDE_BUILTIN_GROUPS;
}
if ((allowedTypes & ObjectTypes.WellKnownPrincipals) == ObjectTypes.WellKnownPrincipals)
{
downlevelFilter |= DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_ALL_WELLKNOWN_SIDS;
// This includes all the following:
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_WORLD |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_AUTHENTICATED_USER |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_ANONYMOUS |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_BATCH |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_CREATOR_OWNER |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_CREATOR_GROUP |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_DIALUP |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_INTERACTIVE |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_NETWORK |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_SERVICE |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_SYSTEM |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_TERMINAL_SERVER |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_LOCAL_SERVICE |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_NETWORK_SERVICE |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_REMOTE_LOGON;
}
return downlevelFilter;
}
// Convert Locations to DSOP_SCOPE_TYPE_FLAGS
private static uint GetScope( Locations locations )
{
uint scope = 0;
if ((locations & Locations.LocalComputer) == Locations.LocalComputer)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_TARGET_COMPUTER;
}
if ((locations & Locations.JoinedDomain) == Locations.JoinedDomain)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_DOWNLEVEL_JOINED_DOMAIN |
DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_UPLEVEL_JOINED_DOMAIN;
}
if ((locations & Locations.EnterpriseDomain) == Locations.EnterpriseDomain)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_ENTERPRISE_DOMAIN;
}
if ((locations & Locations.GlobalCatalog) == Locations.GlobalCatalog)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_GLOBAL_CATALOG;
}
if ((locations & Locations.ExternalDomain) == Locations.ExternalDomain)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_EXTERNAL_DOWNLEVEL_DOMAIN |
DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_EXTERNAL_UPLEVEL_DOMAIN;
}
if ((locations & Locations.Workgroup) == Locations.Workgroup)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_WORKGROUP;
}
if ((locations & Locations.UserEntered) == Locations.UserEntered)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_USER_ENTERED_DOWNLEVEL_SCOPE |
DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_USER_ENTERED_UPLEVEL_SCOPE;
}
return scope;
}
// Convert scope for allowed locations other than the default
private uint GetOtherScope()
{
Locations otherLocations = allowedLocations & (~defaultLocations);
return GetScope(otherLocations);
}
// Convert scope for default locations
private uint GetStartingScope()
{
return GetScope(defaultLocations);
}
// Convert ObjectTypes to DSOP_FILTER_FLAGS_FLAGS
private uint GetUpLevelFilter()
{
uint uplevelFilter = 0;
if ((allowedTypes & ObjectTypes.Users) == ObjectTypes.Users)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_USERS;
}
if ((allowedTypes & ObjectTypes.Groups) == ObjectTypes.Groups)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_UNIVERSAL_GROUPS_DL |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_UNIVERSAL_GROUPS_SE |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_GLOBAL_GROUPS_DL |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_GLOBAL_GROUPS_SE |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_DOMAIN_LOCAL_GROUPS_DL |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_DOMAIN_LOCAL_GROUPS_SE;
}
if ((allowedTypes & ObjectTypes.Computers) == ObjectTypes.Computers)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_COMPUTERS;
}
if ((allowedTypes & ObjectTypes.Contacts) == ObjectTypes.Contacts)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_CONTACTS;
}
if ((allowedTypes & ObjectTypes.BuiltInGroups) == ObjectTypes.BuiltInGroups)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_BUILTIN_GROUPS;
}
if ((allowedTypes & ObjectTypes.WellKnownPrincipals) == ObjectTypes.WellKnownPrincipals)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_WELL_KNOWN_PRINCIPALS;
}
if( showAdvancedView )
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_INCLUDE_ADVANCED_VIEW;
}
return uplevelFilter;
}
private IDsObjectPicker Initialize()
{
DSObjectPicker picker = new DSObjectPicker();
IDsObjectPicker ipicker = (IDsObjectPicker)picker;
System.Collections.ArrayList scopeInitInfoList = new System.Collections.ArrayList ();
//List<DSOP_SCOPE_INIT_INFO> scopeInitInfoList = new List<DSOP_SCOPE_INIT_INFO>();
// Note the same default and filters are used by all scopes
uint defaultFilter = GetDefaultFilter();
uint upLevelFilter = GetUpLevelFilter();
uint downLevelFilter = GetDownLevelFilter();
// Internall, use one scope for the default (starting) locations.
uint startingScope = GetStartingScope();
if (startingScope > 0)
{
DSOP_SCOPE_INIT_INFO startingScopeInfo = new DSOP_SCOPE_INIT_INFO();
startingScopeInfo.cbSize = (uint)Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO));
startingScopeInfo.flType = startingScope;
startingScopeInfo.flScope = DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_STARTING_SCOPE | defaultFilter;
startingScopeInfo.FilterFlags.Uplevel.flBothModes = upLevelFilter;
startingScopeInfo.FilterFlags.flDownlevel = downLevelFilter;
startingScopeInfo.pwzADsPath = null;
startingScopeInfo.pwzDcName = null;
startingScopeInfo.hr = 0;
scopeInitInfoList.Add(startingScopeInfo);
}
// And another scope for all other locations (AllowedLocation values not in DefaultLocation)
uint otherScope = GetOtherScope();
if (otherScope > 0)
{
DSOP_SCOPE_INIT_INFO otherScopeInfo = new DSOP_SCOPE_INIT_INFO();
otherScopeInfo.cbSize = (uint)Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO));
otherScopeInfo.flType = otherScope;
otherScopeInfo.flScope = defaultFilter;
otherScopeInfo.FilterFlags.Uplevel.flBothModes = upLevelFilter;
otherScopeInfo.FilterFlags.flDownlevel = downLevelFilter;
otherScopeInfo.pwzADsPath = null;
otherScopeInfo.pwzDcName = null;
otherScopeInfo.hr = 0;
scopeInitInfoList.Add(otherScopeInfo);
}
System.Collections.ArrayList scopeInitInfo = new System.Collections.ArrayList ();
scopeInitInfo = scopeInitInfoList;
//DSOP_SCOPE_INIT_INFO[] scopeInitInfo = scopeInitInfoList.ToArray();
// TODO: Scopes for alternate ADs, alternate domains, alternate computers, etc
// Allocate memory from the unmananged mem of the process, this should be freed later!??
IntPtr refScopeInitInfo = Marshal.AllocHGlobal
(Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO)) * scopeInitInfo.Count );
// Marshal structs to pointers
for (int index = 0; index < scopeInitInfo.Count ; index++)
{
//Marshal.StructureToPtr(scopeInitInfo[0],
// refScopeInitInfo, true);
//Marshal.StructureToPtr(scopeInitInfo[index],
// (IntPtr)((int)refScopeInitInfo + index * Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO))), true);
Marshal.StructureToPtr(scopeInitInfo[index],refScopeInitInfo,false);
}
// Initialize structure with data to initialize an object picker dialog box.
DSOP_INIT_INFO initInfo = new DSOP_INIT_INFO ();
initInfo.cbSize = (uint) Marshal.SizeOf (initInfo);
//initInfo.pwzTargetComputer = null; // local computer
initInfo.pwzTargetComputer = targetComputer;
initInfo.cDsScopeInfos = (uint)scopeInitInfo.Count ;
initInfo.aDsScopeInfos = refScopeInitInfo;
// Flags that determine the object picker options.
uint flOptions = 0;
// Only set DSOP_INIT_INFO_FLAGS.DSOP_FLAG_SKIP_TARGET_COMPUTER_DC_CHECK
// if we know target is not a DC (which then saves initialization time).
if (multiSelect)
{
flOptions |= DSOP_INIT_INFO_FLAGS.DSOP_FLAG_MULTISELECT;
}
initInfo.flOptions = flOptions;
// We're not retrieving any additional attributes
//string[] attributes = new string[] { "sAMaccountName" };
//initInfo.cAttributesToFetch = (uint)attributes.Length;
//initInfo.apwzAttributeNames = Marshal.StringToHGlobalUni( attributes[0] );
initInfo.cAttributesToFetch = 0;
initInfo.apwzAttributeNames = IntPtr.Zero;
// Initialize the Object Picker Dialog Box with our options
int hresult = ipicker.Initialize (ref initInfo);
if (hresult != HRESULT.S_OK)
{
return null;
}
return ipicker;
}
private DirectoryObject[] ProcessSelections(IDataObject dataObj)
{
if(dataObj == null)
return null;
DirectoryObject[] selections = null;
// The STGMEDIUM structure is a generalized global memory handle used for data transfer operations
STGMEDIUM stg = new STGMEDIUM();
stg.tymed = (uint)TYMED.TYMED_HGLOBAL;
stg.hGlobal = IntPtr.Zero;
stg.pUnkForRelease = null;
// The FORMATETC structure is a generalized Clipboard format.
FORMATETC fe = new FORMATETC();
fe.cfFormat = System.Windows.Forms.DataFormats.GetFormat(CLIPBOARD_FORMAT.CFSTR_DSOP_DS_SELECTION_LIST).Id;
// The CFSTR_DSOP_DS_SELECTION_LIST clipboard format is provided by the IDataObject obtained
// by calling IDsObjectPicker::InvokeDialog
fe.ptd = IntPtr.Zero;
fe.dwAspect = 1; //DVASPECT_CONTENT = 1,
fe.lindex = -1; // all of the data
fe.tymed = (uint)TYMED.TYMED_HGLOBAL; //The storage medium is a global memory handle (HGLOBAL)
dataObj.GetData(ref fe, ref stg);
IntPtr pDsSL = PInvoke.GlobalLock(stg.hGlobal);
try
{
// the start of our structure
IntPtr current = pDsSL;
// get the # of items selected
int cnt = Marshal.ReadInt32(current);
// if we selected at least 1 object
if (cnt > 0)
{
selections = new DirectoryObject[cnt];
// increment the pointer so we can read the DS_SELECTION structure
current = (IntPtr)((int)current + (Marshal.SizeOf(typeof(uint))*2));
// now loop through the structures
for (int i = 0; i < cnt; i++)
{
// marshal the pointer to the structure
DS_SELECTION s = (DS_SELECTION)Marshal.PtrToStructure(current, typeof(DS_SELECTION));
Marshal.DestroyStructure(current, typeof(DS_SELECTION));
// increment the position of our pointer by the size of the structure
current = (IntPtr)((int)current + Marshal.SizeOf(typeof(DS_SELECTION)));
string name = s.pwzName;
string path = s.pwzADsPath;
string schemaClassName = s.pwzClass;
string upn = s.pwzUPN;
//string temp = Marshal.PtrToStringUni( s.pvarFetchedAttributes );
selections[i] = new DirectoryObject( name, path, schemaClassName, upn );
}
}
}
finally
{
PInvoke.GlobalUnlock(pDsSL);
}
return selections;
}
#endregion
}
}
<file_sep>using System;
using System.Text;
namespace CubicOrange.Windows.Forms.ActiveDirectory
{
/// <summary>
/// Active Directory name translation.
/// </summary>
/// <remarks>
/// <para>
/// Translates names between Active Directory formats, e.g. from down-level NT4
/// style names ("ACME\alice") to User Principal Name ("<EMAIL>").
/// </para>
/// <para>
/// This utility class encapsulates the ActiveDs.dll COM library.
/// </para>
/// </remarks>
public class NameTranslator
{
const int NameTypeUpn = (int)ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_USER_PRINCIPAL_NAME;
const int NameTypeNt4 = (int)ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_NT4;
const int NameTypeDn = (int)ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_1779;
/// <summary>
/// Convert from a down-level NT4 style name to an Active Directory User Principal Name (UPN).
/// </summary>
public static string TranslateDownLevelToUpn(string downLevelNt4Name)
{
string userPrincipalName;
ActiveDs.NameTranslate nt = new ActiveDs.NameTranslate();
nt.Set(NameTypeNt4, downLevelNt4Name);
userPrincipalName = nt.Get(NameTypeUpn);
return userPrincipalName;
}
/// <summary>
/// Convert from an Active Directory User Principal Name (UPN) to a down-level NT4 style name.
/// </summary>
public static string TranslateUpnToDownLevel(string userPrincipalName)
{
string downLevelName;
ActiveDs.NameTranslate nt = new ActiveDs.NameTranslate();
nt.Set(NameTypeUpn, userPrincipalName);
downLevelName = nt.Get(NameTypeNt4);
return downLevelName;
}
}
}
<file_sep>using System;
using System.Runtime.InteropServices;
namespace DOP.Windows.Forms.ActiveDirectory
{
/// <summary>
/// The object picker dialog box.
/// </summary>
[ComImport, Guid("17D6CCD8-3B7B-11D2-B9E0-00C04FD8DBF7")]
internal class DSObjectPicker
{
}
/// <summary>
/// The IDsObjectPicker interface is used by an application to initialize and display an object picker dialog box.
/// </summary>
[ComImport, Guid("0C87E64E-3B7A-11D2-B9E0-00C04FD8DBF7"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IDsObjectPicker
{
[PreserveSig()]
int Initialize(ref DSOP_INIT_INFO pInitInfo);
[PreserveSig()]
int InvokeDialog(IntPtr HWND, out IDataObject lpDataObject);
}
/// <summary>
/// Interface to enable data transfers
/// </summary>
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("0000010e-0000-0000-C000-000000000046")]
internal interface IDataObject
{
[PreserveSig()]
int GetData(ref FORMATETC pFormatEtc, ref STGMEDIUM b);
void GetDataHere(ref FORMATETC pFormatEtc, ref STGMEDIUM b);
[PreserveSig()]
int QueryGetData(IntPtr a);
[PreserveSig()]
int GetCanonicalFormatEtc(IntPtr a, IntPtr b);
[PreserveSig()]
int SetData(IntPtr a, IntPtr b, int c);
[PreserveSig()]
int EnumFormatEtc(uint a, IntPtr b);
[PreserveSig()]
int DAdvise(IntPtr a, uint b, IntPtr c, ref uint d);
[PreserveSig()]
int DUnadvise(uint a);
[PreserveSig()]
int EnumDAdvise(IntPtr a);
}
}
<file_sep>using System;
namespace DOP.Windows.Forms.ActiveDirectory
{
/// <summary>
/// Details of a directory object selected in the DirectoryObjectPickerDialog.
/// </summary>
public class DirectoryObject
{
private string adsPath;
private string className;
private string name;
private string upn;
public DirectoryObject(string name, string path, string schemaClass, string upn)
{
this.name = name;
this.adsPath = path;
this.className = schemaClass;
this.upn = upn;
}
/// <summary>
/// Gets the Active Directory path for this directory object.
/// </summary>
/// <remarks>
/// <para>
/// The format of this string depends on the options specified in the DirectoryObjectPickerDialog
/// from which this object was selected.
/// </para>
/// </remarks>
public string Path
{
get
{
return adsPath;
}
}
/// <summary>
/// Gets the name of the schema class for this directory object (objectClass attribute).
/// </summary>
public string SchemaClassName
{
get
{
return className;
}
}
/// <summary>
/// Gets the directory object's relative distinguished name (RDN).
/// </summary>
public string Name
{
get
{
return name;
}
}
/// <summary>
/// Gets the objects user principal name (userPrincipalName attribute).
/// </summary>
/// <remarks>
/// <para>
/// If the object does not have a userPrincipalName value, this property is an empty string.
/// </para>
/// </remarks>
public string Upn
{
get
{
return upn;
}
}
}
}
| dbd57703b8949687e30fbbd7e13e7e92ff9b3311 | [
"Markdown",
"C#"
]
| 5 | Markdown | ehsan2022002/DirectoryObjectPicker | 65dc60e55cb676fdcdc28b1a6cf9e2fd4c68f769 | 9c231e8a8ec6fa41c6abedfc2c48fd57e07002b4 |
refs/heads/master | <file_sep>import React, {Component} from 'react';
import {Redirect} from 'react-router-dom';
import './Home.css';
import {PostData} from '../../services/PostData';
import OrderFeed from "../OrderFeed/OrderFeed";
import '../../styles/react-confirm-alert.css';
import Badge from 'react-bootstrap/Badge'
import Table from 'react-bootstrap/Table'
class Order extends Component {
constructor(props) {
super(props);
this.state = {
data:[],
redirectToReferrer: false,
name:'',
};
this.getOrderFeed = this.getOrderFeed.bind(this);
this.onChange = this.onChange.bind(this);
this.logout = this.logout.bind(this);
}
componentWillMount() {
if(sessionStorage.getItem("userData")){
this.getOrderFeed();
}
else{
this.setState({redirectToReferrer: true});
}
}
editFeed(e){
alert("j");
}
getOrderFeed() {
let data = JSON.parse(sessionStorage.getItem("userData"));
this.setState({name:data.userData.name});
let postData = { user_id: data.userData.user_id};
if (data) {
PostData('OrderFeed', postData).then((result) => {
let responseJson = result;
if(responseJson.OrderfeedData){
this.setState({data: responseJson.OrderfeedData});
}
});
}
}
onChange(e){
this.setState({userFeed:e.target.value});
}
logout(){
sessionStorage.setItem("userData",'');
sessionStorage.clear();
this.setState({redirectToReferrer: true});
}
render() {
if (this.state.redirectToReferrer) {
return (<Redirect to={'/login'}/>)
}
return (
<div >
<br/><br/><br/>
<h1>
<Badge pill variant="success">My Order</Badge>
</h1>
<br/>
<Table striped bordered hover variant="success">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Time</th>
<th>Date</th>
<th>Payment</th>
</tr>
</thead>
</Table>
<OrderFeed OrderfeedData = {this.state.data}/>
</div>
);
}
}
export default Order;<file_sep><?php
use \Mailjet\Resources;
$type = $_GET['tp'];
if($type=='signup') signup();
elseif($type=='login') login();
elseif($type=='feed') feed();
elseif($type=='OrderFeed') OrderFeed();
elseif($type=='Checkout') Checkout();
elseif($type=='feedTotal') feedTotal();
elseif($type=='feedUpdate') feedUpdate();
elseif($type=='feedDelete') feedDelete();
function login()
{
require 'config.php';
$json = json_decode(file_get_contents('php://input'), true);
$username = $json['username']; $password = $json['<PASSWORD>'];
$userData =''; $query = "select * from users where username='$username' and password='$<PASSWORD>'";
$result= $db->query($query);
$rowCount=$result->num_rows;
if($rowCount>0)
{
$userData = $result->fetch_object();
$user_id=$userData->user_id;
$userData = json_encode($userData);
echo '{"userData":'.$userData.'}';
}
else
{
echo '{"error":"Wrong username and password"}';
}
}
function signup() {
require 'config.php';
$json = json_decode(file_get_contents('php://input'), true);
$username = $json['username'];
$password = $json['<PASSWORD>'];
$email = $json['email'];
$name = $json['name'];
$username_check = preg_match("/^[A-Za-z0-9_]{4,10}$/i", $username);
$email_check = preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/i', $email);
$password_check = preg_match('/^[A-Za-z0-9!@#$%^&*()_]{4,20}$/i', $password);
if($username_check==0)
echo '{"error":"Invalid username"}';
elseif($email_check==0)
echo '{"error":"Invalid email"}';
elseif($password_check ==0)
echo '{"error":"Invalid password"}';
elseif (strlen(trim($username))>0 && strlen(trim($password))>0 && strlen(trim($email))>0 &&
$email_check>0 && $username_check>0 && $password_check>0)
{
$userData = '';
$result = $db->query("select * from users where username='$username' or email='$email'");
$rowCount=$result->num_rows;
//echo '{"text": "'.$rowCount.'"}';
if($rowCount==0)
{
$db->query("INSERT INTO users(username,password,email,name)
VALUES('$username','$password','$email','$name')");
$userData ='';
$query = "select * from users where username='$username' and password='$<PASSWORD>'";
$result= $db->query($query);
$userData = $result->fetch_object();
$user_id=$userData->user_id;
$userData = json_encode($userData);
echo '{"userData":'.$userData.'}';
}
else {
echo '{"error":"username or email exists"}';
}
}
else{
echo '{"text":"Enter valid data2"}';
}
}
function feed(){
require 'config.php';
$json = json_decode(file_get_contents('php://input'), true);
$user_id=$json['user_id'];
$query = "SELECT * FROM feed WHERE user_id=$user_id AND status=1 ORDER BY feed_id ASC LIMIT 10";
//$query = "SELECT * FROM feed ";
$result = $db->query($query);
$feedData = mysqli_fetch_all($result,MYSQLI_ASSOC);
$feedData=json_encode($feedData);
echo '{"feedData":'.$feedData.'}';
}
function OrderFeed(){
require 'config.php';
$json = json_decode(file_get_contents('php://input'), true);
$user_id=$json['user_id'];
$query = "SELECT * FROM feed WHERE user_id=$user_id AND status=2;";
//$query = "SELECT * FROM feed ";
$result = $db->query($query);
$OrderfeedData = mysqli_fetch_all($result,MYSQLI_ASSOC);
$OrderfeedData=json_encode($OrderfeedData);
echo '{"OrderfeedData":'.$OrderfeedData.'}';
}
function feedUpdate(){
require 'config.php';
$json = json_decode(file_get_contents('php://input'), true);
$user_id=$json['user_id'];
$feed=$json['feed'];
$price=$json['price'];
$feedData = '';
$status=1;
if($user_id !=0)
{
$query = "INSERT INTO feed (feed,user_id,price,status) VALUES ('$feed','$user_id','$price','$status');";
$db->query($query);
}
$query = "SELECT * FROM feed WHERE user_id=$user_id ORDER BY feed_id ASC LIMIT 10";
$result = $db->query($query);
$feedData = mysqli_fetch_all($result,MYSQLI_ASSOC);
$feedData=json_encode($feedData);
echo '{"feedData":'.$feedData.'}';
}
function feedDelete(){
require 'config.php';
$json = json_decode(file_get_contents('php://input'), true);
$user_id=$json['user_id'];
$feed_id=$json['feed_id'];
$query = "Delete FROM feed WHERE user_id=$user_id AND feed_id=$feed_id AND status=1;";
$result = $db->query($query);
if($result)
{
echo '{"success":"Feed deleted"}';
} else{
echo '{"error":"Delete error"}';
}
}
function feedTotal(){
require 'config.php';
$json = json_decode(file_get_contents('php://input'), true);
$user_id=$json['user_id'];
$Total='';
$query = "SELECT SUM(price) AS Total FROM feed WHERE user_id=$user_id And status=1;";
$result = $db->query($query);
$Total = $result->fetch_object();
$Total=$Total->Total;
$Total = json_encode($Total);
echo '{"Total":'.$Total.'}';
}
function Checkout(){
require 'vendor/autoload.php';
require 'config.php';
$json = json_decode(file_get_contents('php://input'), true);
$user=$json['user_id'];
$email=$json['email'];
$name=$json['name'];
$query ="UPDATE feed SET date=CURDATE(),time=CURTIME(),status=2 WHERE user_id=$user AND status=1;";
$result = $db->query($query);
$mj = new \Mailjet\Client('898278dd4d3a9ea4d2bc9eda6439414d','cb6e505cde49d3e21afad0275ecd8a6e',true,['version' => 'v3.1']);
$body = [
'Messages' => [
[
'From' => [
'Email' => "<EMAIL>",
'Name' => "Krittiya"
],
'To' => [
[
'Email' => $email,
'Name' => $name
]
],
'Subject' => "Thank you for shopping with us.",
'TextPart' => "My first Mailjet email",
'HTMLPart' => "<h3>Dear $name</h3><br/><h3>Thank you for shopping with us.</h3>",
'CustomID' => "AppGettingStartedTest"
]
]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
if($result)
{
echo '{"success":"Order Successfully"}';
} else{
echo '{"error":"Something Wrong !!!"}';
}
}
?><file_sep>import React, {Component} from 'react';
import './Home.css';
import '../../styles/react-confirm-alert.css';
import fenix6 from "./fenix-6-detail.jpg";
import Badge from 'react-bootstrap/Badge'
import Button from 'react-bootstrap/Button'
import Accordion from 'react-bootstrap/Accordion'
import Card from 'react-bootstrap/Card'
class fenix extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<br/><br/><br/><br/>
<h1>
<Badge pill variant="success">Fenix 6X PRO Solar</Badge>
</h1><br/>
<img src={fenix6} width="600px" height="350px"/>
<br/><br/>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
OVERVIEW
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>
- SURF-READY FEATURES<br/>
- VARIOUS SPORTS APPS<br/>
- BODY BATTERY ENERGY MEASUREMENT<br/>
- ON-SCREEN WORKOUT ANIMATION<br/>
- SOLAR CHARGER<br/>
- POWER MANAGER<br/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
SPECS
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>
<b>LENS MATERIAL:</b><br/>
Power Glass™<br/><br/>
<b>BEZEL MATERIAL</b>:<br/>
stainless steel or Diamond-Like Carbon (DLC) coated titanium<br/><br/>
<b>CASE MATERIAL</b>:<br/>fiber-reinforced polymer with metal rear cover<br/><br/>
<b>QUICKFIT™ WATCH BAND COMPATIBLE</b>:<br/>
included (22 mm)<br/><br/>
<b>STRAP MATERIAL:</b><br/>
silicone or titanium<br/><br/>
<b>PHYSICAL SIZE:</b><br/>
47 x 47 x 15.1 mm<br/>
Fits wrists with the following circumference:<br/>
Silicone band: 125-208 mm<br/>
Leather band: 132-210 mm<br/>
Fabric band: 132-210 mm<br/>
Metal band: 132-215 mm<br/><br/>
<b>DISPLAY SIZE:</b> 1.3” (33.02 mm) diameter<br/><br/>
<b>DISPLAY RESOLUTION:</b> 260 x 260 pixels<br/><br/>
<b>DISPLAY TYPE:</b> sunlight-visible, transflective memory-in-pixel (MIP)<br/><br/>
<b>WEIGHT:</b>
Steel: 85 g (case only: 62 g)<br/>
Titanium: 72 g (case only: 48 g)<br/><br/>
<b>BATTERY LIFE:</b> <br/>
Smartwatch: Up to 14 days/16 days with solar*<br/>
Battery Saver Watch Mode: Up to 48 days/80 days with solar*<br/>
GPS: Up to 36 hours/40 hours with solar**<br/>
GPS + Music: Up to 10 hours<br/>
Max Battery GPS Mode: Up to 72 hours/93 hours with solar**<br/>
Expedition GPS Activity: Up to 28 days/36 days with solar*<br/><br/>
*Solar charging, assuming all-day wear with 3 hours per day outside in 50,000 lux conditions<br/>
**Solar charging, assuming use in 50,000 lux conditions<br/><br/>
WATER RATING 10 ATM<br/>
MEMORY/HISTORY 32 GB<br/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
Sensors
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>
-GPS <br/>
-GLONASS <br/>
-GALILEO <br/>
-GARMIN ELEVATE™ WRIST HEART RATE MONITOR <br/>
-BAROMETRIC ALTIMETER <br/>
-COMPASS <br/>
-GYROSCOPE <br/>
-ACCELEROMETER <br/>
-THERMOMETER <br/>
-PULSE OX BLOOD OXYGEN SATURATION MONITOR : Yes (with Acclimation)
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
Activity Tracking Features
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>
-STEP COUNTER <br/>
-MOVE BAR (DISPLAYS ON DEVICE AFTER A PERIOD OF INACTIVITY; WALK FOR A COUPLE OF MINUTES TO RESET IT) <br/>
-AUTO GOAL (LEARNS YOUR ACTIVITY LEVEL AND ASSIGNS A DAILY STEP GOAL) <br/>
-CALORIES BURNED <br/>
-FLOORS CLIMBED <br/>
-DISTANCE TRAVELED <br/>
-INTENSITY MINUTES <br/>
-TRUEUP™ <br/>
-MOVE IQ™<br/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
Tactical Features
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body><b>DUAL GRID COORDINATES</b></Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
In the box
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>
-fēnix 6 Pro Solar<br/>
-Charging/data cable<br/>
-Documentation<br/><br/>
<b>Fenix 6 Pro Solar - Titanium Carbon Gray DLC with Titanium DLC Band Version Only</b><br/><br/>
-fēnix 6 Pro Solar<br/>
-Black silicone watch band<br/>
-Charging/data cable<br/>
-Documentation<br/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion><br/>
<Button href="/home" variant="outline-primary">Back to Shop</Button>
</div>
);
}
}
export default fenix ;<file_sep>import React, {Component} from 'react';
import './Home.css';
import '../../styles/react-confirm-alert.css';
import SE from "./se2.png";
import Badge from 'react-bootstrap/Badge'
import Button from 'react-bootstrap/Button'
import Accordion from 'react-bootstrap/Accordion'
import Card from 'react-bootstrap/Card'
class wacthse extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div >
<br/><br/><br/><br/>
<h1>
<Badge pill variant="success">Apple Watch SE</Badge>
</h1><br/>
<img src={SE} width="600px" height="200px"/>
<br/><br/>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
OVERVIEW
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>- Music<br/>
- Heartrate<br/>
- OX pulse</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
SPECS
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>
<b>NETWORK</b><br/>
Technology GSM / HSPA / LTE<br/><br/>
<b>BODY</b><br/>
Dimensions 44 x 38 x 10.4 mm (1.73 x 1.50 x 0.41 in)<br/><br/>
<b>Weight</b><br/>
36.4 g (1.27 oz)<br/><br/>
<b>Build</b><br/>
Glass front, ceramic/sapphire crystal back, aluminum frame<br/><br/>
<b>DISPLAY</b><br/>
Retina LTPO OLED, 1000 nits (peak)<br/><br/>
<b>Size</b><br/>
1.78 inches, 10.0 cm2 (~60.0% screen-to-body ratio)<br/><br/>
<b>Resolution</b><br/>
448 x 368 pixels (~326 ppi density)<br/><br/>
<b>PLATFORM</b><br/>
OS watchOS 7.0, upgradable to 7.1<br/><br/>
<b>CPU</b><br/>
Dual-core<br/><br/>
<b>GPU</b><br/>
PowerVR<br/><br/>
<b>Internal</b><br/>
32GB 1GB RAM<br/><br/>
<b>COMMS WLAN</b><br/>
Wi-Fi 802.11 b/g/n<br/><br/>
<b>Bluetooth</b><br/>
5.0, A2DP, LE<br/><br/>
<b>GPS</b><br/>
Yes, with A-GPS, GLONASS<br/><br/>
<b>FEATURES</b><br/>
Sensors Accelerometer, gyro, heart rate (2nd gen), barometer, always-on altimeter, compass<br/><br/>
<b>MISC</b><br/>
Colors Silver, Gold, Space Gray<br/><br/>
<b>Models</b><br/>
A2353, A2354, A2355, A2356, A2351, A2352<br/><br/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
Chip
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body><b>Chipset</b><br/>
Apple S5<br/><br/></Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
BATTERY
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>
<b>BATTERY Type</b><br/>
Li-Ion, non-removable<br/><br/>
<b>Charging</b><br/>
Wireless charging<br/><br/>
<b>Stand-by</b><br/>
Up to 18 h (mixed usage)<br/><br/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
Cellular
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>- <b>SIM</b><br/>
eSIM 50m water resistant<br/><br/></Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<br/>
<Button href="/home" variant="outline-primary">Back to Shop</Button>
</div>
);
}
}
export default wacthse;<file_sep>import React, {Component} from 'react';
import {Redirect} from 'react-router-dom';
import './Home.css';
import {PostData} from '../../services/PostData';
import { confirmAlert } from 'react-confirm-alert';
import '../../styles/react-confirm-alert.css';
import se2 from "./se2.png";
import watch from "./watch.png";
import fenix6s from "./fenix67.jpg";
import Mk2ii from "./Mk2.jpg";
import mk from "./Garmindescent.png";
import venu from "./venu.png";
import venu1 from "./venu1.jpg";
import fenix6b from "./fenix66.jpg"
import hermes from "./hermes.png"
import hermes1 from "./hermes.jpg"
import watch6 from "./apple-watch-6.jpg"
import se from "./apple-watch-se.jpg"
import 'bootstrap/dist/css/bootstrap.min.css';
import Button from 'react-bootstrap/Button';
import {Row, Col} from 'react-bootstrap';
import Carousel from 'react-bootstrap/Carousel'
import Container from 'react-bootstrap/Container'
import Image from 'react-bootstrap/Image'
import Card from 'react-bootstrap/Card'
import Badge from 'react-bootstrap/Badge'
class Home extends Component {
constructor(props) {
super(props);
this.state = {
data:[],
redirectToReferrer: false,
userFeed1:'Apple Watch Hermes',
userFeed2:'Apple Watch SE',
userFeed3:'Apple Watch Series 6',
userFeed4:'Garmin fenix 6X',
userFeed5: 'Garmin descent MK',
userFeed6: 'Garmin Venu',
price1:25000,
price2:30000,
price3:12000,
price4:22000,
price5:42000,
price6:12000,
name:'',
};
this.getUserFeed = this.getUserFeed.bind(this);
this.addcart = this.addcart.bind(this);
this.feedUpdate1 = this.feedUpdate1.bind(this);
this.feedUpdate2 = this.feedUpdate2.bind(this);
this.feedUpdate3 = this.feedUpdate3.bind(this);
this.feedUpdate4 = this.feedUpdate4.bind(this);
this.feedUpdate5 = this.feedUpdate5.bind(this);
this.feedUpdate6 = this.feedUpdate6.bind(this);
this.logout = this.logout.bind(this);
}
componentWillMount() {
if(sessionStorage.getItem("userData")){
this.getUserFeed();
}
else{
this.setState({redirectToReferrer: true});
}
}
//---------------------------Add Product----------------------------
addcart(){
confirmAlert({
title: 'ADD TO CART',
message: 'Product have been added to your cart.',
buttons: [{ label: 'CONTINUE'},{ label: 'GO TO CART',onClick: () => window.location.href = "/cart"}]});
}
feedUpdate1(e) {
e.preventDefault();
let data = JSON.parse(sessionStorage.getItem("userData"));
let postData = { user_id: data.userData.user_id, feed: this.state.userFeed1,price: this.state.price1};
if (this.state.userFeed1) {
PostData('feedUpdate', postData).then((result) => {
let responseJson = result;
this.setState({data: responseJson.feedData});
});
}
}
feedUpdate2(e) {
e.preventDefault();
let data = JSON.parse(sessionStorage.getItem("userData"));
let postData = { user_id: data.userData.user_id, feed: this.state.userFeed2,price: this.state.price2 };
if (this.state.userFeed2) {
PostData('feedUpdate', postData).then((result) => {
let responseJson = result;
this.setState({data: responseJson.feedData});
});
}
}
feedUpdate3(e) {
e.preventDefault();
let data = JSON.parse(sessionStorage.getItem("userData"));
let postData = { user_id: data.userData.user_id, feed: this.state.userFeed3,price: this.state.price3};
if (this.state.userFeed5) {
PostData('feedUpdate', postData).then((result) => {
let responseJson = result;
this.setState({data: responseJson.feedData});
});
}
}
feedUpdate4(e) {
e.preventDefault();
let data = JSON.parse(sessionStorage.getItem("userData"));
let postData = { user_id: data.userData.user_id, feed: this.state.userFeed4,price: this.state.price4};
if (this.state.userFeed5) {
PostData('feedUpdate', postData).then((result) => {
let responseJson = result;
this.setState({data: responseJson.feedData});
});
}
}
feedUpdate5(e) {
e.preventDefault();
let data = JSON.parse(sessionStorage.getItem("userData"));
let postData = { user_id: data.userData.user_id, feed: this.state.userFeed5,price: this.state.price5};
if (this.state.userFeed5) {
PostData('feedUpdate', postData).then((result) => {
let responseJson = result;
this.setState({data: responseJson.feedData});
});
}
}
feedUpdate6(e) {
e.preventDefault();
let data = JSON.parse(sessionStorage.getItem("userData"));
let postData = { user_id: data.userData.user_id, feed: this.state.userFeed6,price: this.state.price6};
if (this.state.userFeed6) {
PostData('feedUpdate', postData).then((result) => {
let responseJson = result;
this.setState({data: responseJson.feedData});
});
}
}
//---------------------------------------------------------
getUserFeed() {
let data = JSON.parse(sessionStorage.getItem("userData"));
this.setState({name:data.userData.name});
let postData = { user_id: data.userData.user_id};
if (data) {
PostData('feed', postData).then((result) => {
let responseJson = result;
if(responseJson.feedData){
this.setState({data: responseJson.feedData});
}
});
}
}
logout(){
sessionStorage.setItem("userData",'');
sessionStorage.clear();
this.setState({redirectToReferrer: true});
}
render() {
if (this.state.redirectToReferrer) {
return (<Redirect to={'/login'}/>)
}
return (
<div>
<br/><br/><br/>
<Carousel style={{marginLeft:'200px',width:'70%',height:'100%'}}>
<Carousel.Item>
<Image style={{width:'100%',height:'400px'}} src={hermes} fluid />
<br/>
<Carousel.Caption>
<Button href="/hermes" variant="outline-dark">Hermes</Button>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<Image src={se2} style={{width:'100%',height:'400px'}} fluid/>
<br/>
<Carousel.Caption>
<Button href="/watchse" variant="outline-dark">Apple Watch SE</Button>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<Image style={{width:'100%',height:'400px'}} src={watch} fluid/>
<br/>
<Carousel.Caption>
<Button href="/applewatch" variant="outline-dark">Apple Watch Series 6</Button>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<Image style={{width:'100%',height:'400px'}} src={fenix6b} fluid/>
<br/>
<Carousel.Caption>
<Button href="/Fenix" variant="outline-dark">Garmin Fenix 6X</Button>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<Image style={{width:'100%',height:'400px'}} src={Mk2ii} fluid/>
<br/>
<Carousel.Caption>
<Button href="/descent" variant="outline-dark">Garmin Mk</Button>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<Image style={{width:'100%',height:'400px'}} src={venu} fluid/>
<br/>
<Carousel.Caption>
<Button href="/venu" variant="outline-dark">Garmin Venu</Button>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
<br/>
<h1>
<Badge pill variant="outline-primary" style={{marginLeft:'200px'}}>APPLE WATCH</Badge>
</h1>
<br/>
<Container>
<Row>
<Col xs><Card style={{ width: '18rem' }}>
<Card.Img variant="top" src={hermes1} />
<Card.Body>
<Card.Title>Apple Watch Hermes</Card.Title>
<Card.Text>
The iPhone X was Apple's flagship 10th anniversary iPhone featuring a 5.8-inch OLED display, facial recognition and 3D camera functionality, a glass body, and an A11 Bionic processor.
</Card.Text>
<form onSubmit={this.feedUpdate1} method="post">
<Card.Title>Price : ฿ {this.state.price1}</Card.Title>
<Button href="/hermes" variant="success" >Detail</Button>
<Button variant="outline-primary" type="submit" onClick={this.addcart}>Add to Cart</Button>
</form>
</Card.Body>
</Card></Col>
<Col xs={{ order: 12 }}><Card style={{ width: '18rem' }}>
<Card.Img variant="top" src={watch6} />
<Card.Body>
<Card.Title>Apple Watch Series 6</Card.Title>
<Card.Text>
The new Series 6 runs on a new Apple S5 chip inside: 64-bit dual-core S5 processor, up to 2x faster than S3 processor (includes W3 wireless chip). Apple Watch bands now include purchasable gold.
</Card.Text>
<form onSubmit={this.feedUpdate3} method="post">
<Card.Title>Price : ฿ {this.state.price3}</Card.Title>
<Button href="/applewatch" variant="success">Detail</Button>
<Button variant="outline-primary" type="submit" onClick={this.addcart}>Add to Cart</Button>
</form>
</Card.Body>
</Card></Col>
<Col xs={{ order: 1 }}><Card style={{ width: '18rem' }}>
<Card.Img variant="top" src={se} />
<Card.Body>
<Card.Title>Apple Watch SE</Card.Title>
<Card.Text>
Apple in October introduced upgraded 11-inch and 12.9-inch iPad Pro models that feature edge-to-edge displays that do away with the Home button, slim bezels all the way around.
</Card.Text>
<form onSubmit={this.feedUpdate2} method="post">
<Card.Title>Price : ฿ {this.state.price2}</Card.Title>
<Button href="/watchse" variant="success">Detail</Button>
<Button variant="outline-primary" type="submit" onClick={this.addcart}>Add to Cart</Button>
</form>
</Card.Body>
</Card></Col>
</Row>
</Container>
<h2>
<Badge pill variant="outline-primary" style={{marginLeft:'200px',marginTop:'20px'}}>GARMIN</Badge>
</h2>
<br/>
<Container>
<Row>
<Col xs><Card style={{ width: '18rem' }}>
<Card.Img variant="top" src={fenix6s} />
<Card.Body>
<Card.Title><NAME> 6X</Card.Title>
<Card.Text>
The iPhone X was Apple's flagship 10th anniversary iPhone featuring a 5.8-inch OLED display, facial recognition and 3D camera functionality, a glass body, and an A11 Bionic processor.
</Card.Text>
<form onSubmit={this.feedUpdate4} method="post">
<Card.Title>Price : ฿ {this.state.price4}</Card.Title>
<Button href="/fenix" variant="success" >Detail</Button>
<Button variant="outline-primary" type="submit" onClick={this.addcart}>Add to Cart</Button>
</form>
</Card.Body>
</Card></Col>
<Col xs={{ order: 1 }}><Card style={{ width: '18rem' }}>
<Card.Img variant="top" src={mk} />
<Card.Body>
<Card.Title><NAME> MK</Card.Title>
<Card.Text>
The new Series 5 runs on a new Apple S5 chip inside: 64-bit dual-core S5 processor, up to 2x faster than S3 processor (includes W3 wireless chip). Apple Watch bands now include purchasable gold.
</Card.Text>
<form onSubmit={this.feedUpdate5} method="post">
<Card.Title>Price : ฿ {this.state.price5}</Card.Title>
<Button href="/descent" variant="success">Detail</Button>
<Button variant="outline-primary" type="submit" onClick={this.addcart}>Add to Cart</Button>
</form>
</Card.Body>
</Card></Col>
<Col xs={{ order: 12 }}><Card style={{ width: '18rem' }}>
<Card.Img variant="top" src={venu1} />
<Card.Body>
<Card.Title><NAME></Card.Title>
<Card.Text>
Apple in October introduced upgraded 11-inch and 12.9-inch iPad Pro models that feature edge-to-edge displays that do away with the Home button, slim bezels all the way around.
</Card.Text>
<form onSubmit={this.feedUpdate6} method="post">
<Card.Title>Price : ฿ {this.state.price2}</Card.Title>
<Button href="/venu" variant="success">Detail</Button>
<Button variant="outline-primary" type="submit" onClick={this.addcart}>Add to Cart</Button>
</form>
</Card.Body>
</Card></Col>
</Row>
</Container>
</div>
);
}
}
export default Home;<file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Nov 24, 2019 at 08:03 PM
-- Server version: 10.4.6-MariaDB
-- PHP Version: 7.3.9
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `reactdb`
--
-- --------------------------------------------------------
--
-- Table structure for table `feed`
--
CREATE TABLE `feed` (
`feed_id` int(11) NOT NULL,
`feed` text DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`price` int(11) NOT NULL,
`date` date NOT NULL,
`time` time NOT NULL,
`status` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `orderlist`
--
CREATE TABLE `orderlist` (
`order_id` int(100) NOT NULL,
`order_user` int(100) NOT NULL,
`order_product` varchar(100) NOT NULL,
`order_price` int(100) NOT NULL,
`date` date NOT NULL,
`time` time NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `orderlist`
--
INSERT INTO `orderlist` (`order_id`, `order_user`, `order_product`, `order_price`, `date`, `time`) VALUES
(38, 1, 'iPhoneX', 25000, '2019-11-18', '03:13:44'),
(39, 1, 'AppleWatch', 12000, '2019-11-18', '03:13:44'),
(40, 1, 'iPhoneX', 25000, '2019-11-18', '03:13:44');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`username` varchar(50) DEFAULT NULL,
`password` varchar(300) DEFAULT NULL,
`name` varchar(200) DEFAULT NULL,
`email` varchar(300) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`user_id`, `username`, `password`, `name`, `email`) VALUES
(1, 'omza', '<PASSWORD>', '<PASSWORD>', '<EMAIL>'),
(2, 'omzaza', '123456', 'Ohmmy', '<EMAIL>');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `feed`
--
ALTER TABLE `feed`
ADD PRIMARY KEY (`feed_id`);
--
-- Indexes for table `orderlist`
--
ALTER TABLE `orderlist`
ADD PRIMARY KEY (`order_id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `feed`
--
ALTER TABLE `feed`
MODIFY `feed_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=117;
--
-- AUTO_INCREMENT for table `orderlist`
--
ALTER TABLE `orderlist`
MODIFY `order_id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=41;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>import React, {Component} from 'react';
import Linkify from 'react-linkify';
import './Home.css';
import {Bootstrap, Grid, Row, Col} from 'react-bootstrap';
import Container from 'react-bootstrap/Container'
import 'bootstrap/dist/css/bootstrap.min.css';
import Button from 'react-bootstrap/Button'
import iPhoneX from "./iphonex.png";
//import TimeAgo from 'react-timeago';
class UserFeed extends Component {
constructor(props){
super(props);
}
render() {
let UserFeed = this.props.feedData
.map(function (feedData, index) {
return (
<div key={index}>
<Container>
<Row >
<Col><Linkify>{feedData.feed_id}</Linkify></Col>
<Col><Linkify><a href={feedData.feed}>{feedData.feed}</a></Linkify></Col>
<Col><Linkify>฿ {feedData.price}</Linkify></Col>
<Col>
<Button id="del" variant="outline-danger" onClick={this.props.deleteFeed} data={feedData.feed_id} value={this.props.index}>DELETE</Button>
</Col>
</Row>
</Container>
<br/>
</div>
)
}, this);
return (
<div>
{UserFeed}
</div>
);
}
}
export default UserFeed;<file_sep>import React, {Component} from 'react';
import Linkify from 'react-linkify';
import './UserFeedshop.css';
//import TimeAgo from 'react-timeago';
class UserFeedshop extends Component {
constructor(props){
super(props);
}
render() {
let userFeedshop = this.props.feedDatashop
.map(function (feedDatashop, index) {
return (
<div className="medium-12 columns" key={index}>
<div className="people-you-might-know">
<div className="row add-people-section">
<div className="small-12 medium-10 columns about-people">
<div className="about-people-author">
<p className="author-name">
<Linkify>{feedDatashop.p_name}</Linkify>
<br/>
<Linkify>{feedDatashop.p_price}</Linkify>
</p>
</div>
</div>
<div className="small-12 medium-2 columns add-friend">
<div className="add-friend-action">
<button id="del" className="button small btn-color" onClick={this.props.addCart} data={feedDatashop.p_name} value={this.props.index} >
<i className="fa fa-user-times" aria-hidden="true"></i> Add to Cart
</button>
</div>
</div>
</div>
</div>
</div>
)
}, this);
return (
<div>
{userFeedshop}
</div>
);
}
}
export default UserFeedshop;<file_sep>import React, {Component} from 'react';
import Linkify from 'react-linkify';
import './Home.css';
import {Bootstrap, Grid, Row, Col} from 'react-bootstrap';
import Container from 'react-bootstrap/Container'
import 'bootstrap/dist/css/bootstrap.min.css';
import Button from 'react-bootstrap/Button'
import correct from "./correct.png";
//import TimeAgo from 'react-timeago';
class OrderFeed extends Component {
constructor(props){
super(props);
}
render() {
let Feedorder = this.props.OrderfeedData.map(function (OrderfeedData) {
return (
<div>
<Container>
<Row >
<Col><Linkify> <a href={OrderfeedData.feed}>{OrderfeedData.feed}</a></Linkify></Col>
<Col><Linkify> ฿ {OrderfeedData.price}</Linkify></Col>
<Col><Linkify> {OrderfeedData.time}</Linkify></Col>
<Col><Linkify>{OrderfeedData.date}</Linkify></Col>
<Col> <Button variant="outline-success"><img src={correct} width="30px"/></Button></Col>
</Row>
</Container>
<br/>
</div>
)
}, this);
return (
<div>
{Feedorder}
</div>
);
}
}
export default OrderFeed;<file_sep>import React, {Component} from 'react';
import {Redirect} from 'react-router-dom';
import './Home.css';
import {PostData} from '../../services/PostData';
import UserFeed from "../UserFeed/UserFeed";
import { confirmAlert } from 'react-confirm-alert';
import '../../styles/react-confirm-alert.css';
import Table from 'react-bootstrap/Table'
import Badge from 'react-bootstrap/Badge'
import Button from 'react-bootstrap/Button'
import Accordion from 'react-bootstrap/Accordion'
import Card from 'react-bootstrap/Card'
class Cart extends Component {
constructor(props) {
super(props);
this.state = {
data:[],
T:'',
redirectToReferrer: false,
name:'',
email:'',
};
this.Checkout = this.Checkout.bind(this);
this.getUserFeed = this.getUserFeed.bind(this);
this.getFeedTotal = this.getFeedTotal.bind(this);
this.deleteFeed = this.deleteFeed.bind(this);
this.deleteFeedAction = this.deleteFeedAction.bind(this);
this.logout = this.logout.bind(this);
this.confirmcheck = this.confirmcheck.bind(this);
}
UNSAFE_componentWillMount() {
if(sessionStorage.getItem("userData")){
this.getUserFeed();
this.getFeedTotal();
}
else{
this.setState({redirectToReferrer: true});
}
}
deleteFeed(e){
confirmAlert({
title: 'Delete Product',
message: 'Are you sure to delete this product from cart.',
buttons: [{label: 'YES',onClick: () => this.deleteFeedAction(e)},{label: 'NO',}]});}
deleteFeedAction(e){
let updateIndex=e.target.getAttribute('value');
let feed_id=document.getElementById("del").getAttribute("data");
let data = JSON.parse(sessionStorage.getItem("userData"));
let postData = { user_id: data.userData.user_id,feed_id: feed_id };
if (postData) {
PostData('feedDelete', postData).then((result) => {
this.state.data.splice(updateIndex,1);
this.setState({data:this.state.data});
if(result.success){
window.location.href = "/cart";
}
else
alert(result.error);
});
}
}
//-----------------------Show product in cart-------------------
getUserFeed() {
let data = JSON.parse(sessionStorage.getItem("userData"));
this.setState({name:data.userData.name});
this.setState({email:data.userData.email});
let postData = { user_id: data.userData.user_id};
if (data) {
PostData('feed', postData).then((result) => {
let responseJson = result;
if(responseJson.feedData){
this.setState({data: responseJson.feedData});
}
});
}
//--------------------Show total price from database------------------------
}
getFeedTotal() {
let data = JSON.parse(sessionStorage.getItem("userData"));
this.setState({name:data.userData.name});
let postData = { user_id: data.userData.user_id};
if (data) {
PostData('feedTotal', postData).then((result) => {
let responseJson = result;
this.setState({T: responseJson.Total});
});
}
}
//-------------------Check out product-----------------------------
Checkout() {
let data = JSON.parse(sessionStorage.getItem("userData"));
let postData = {user_id: data.userData.user_id,email: data.userData.email,name: data.userData.name};
if (postData) {
PostData('Checkout', postData).then((result) => {
if (result.success){
alert("sucess")
}
});
}
}
//-------------------------------------
confirmcheck(){
confirmAlert({
title: 'CONFIRM',
message: 'Are you sure to check out this Shopping Cart.',
buttons: [{ label: 'OK',onClick: () => this.Checkout()},{ label: 'NO'},]});
}
//----------------------------------------
logout(){
sessionStorage.setItem("userData",'');
sessionStorage.clear();
this.setState({redirectToReferrer: true});
}
render() {
if (this.state.redirectToReferrer) {
return (<Redirect to={'/login'}/>)
}
return (
<div>
<br/><br/><br/>
<h1>
<Badge pill variant="primary">Shopping Cart</Badge>
</h1>
<br/>
<Table striped bordered hover variant="primary">
<thead>
<tr>
<th>No.</th>
<th>Product</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
</Table>
<UserFeed feedData = {this.state.data} deleteFeed = {this.deleteFeed} name={this.state.name}/><hr/>
<h4>Total Price : {this.state.T}฿</h4><hr/>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
<Button variant="outline-success">PROCEED TO CHECKOUT</Button>
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>
<input type="text" placeholder="Address" required/>
<input type="text" placeholder="Tel." required/>
<input type="text" placeholder="Credit Card" required/>
<Button variant="success" onClick={this.confirmcheck}>CONFIRM</Button>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
</div>
);
}
}
export default Cart;<file_sep>import React, {Component} from 'react';
import './Home.css';
import '../../styles/react-confirm-alert.css';
import watch from "./ipaddetail.png";
import Badge from 'react-bootstrap/Badge'
import Button from 'react-bootstrap/Button'
import Accordion from 'react-bootstrap/Accordion'
import Card from 'react-bootstrap/Card'
class iPad extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div >
<br/><br/><br/><br/>
<h1>
<Badge pill variant="success">iPad Pro 2019</Badge>
</h1><br/>
<img src={watch} width="600px" height="200px"/>
<br/><br/>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
Capacity
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>- 64GB<br/>
- 256GB<br/>
- 512GB<br/>
- 1TB</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
Display
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>- Liquid Retina display<br/>
- 11-inch (diagonal) LED-backlit <br/>
- Multi‑Touch display with IPS technology<br/>
- 2388-by-1668-pixel resolution at 264 <br/>
pixels per inch (ppi)<br/>
- ProMotion technology<br/>
- Wide color display (P3)<br/>
- True Tone display<br/>
- Fingerprint-resistant oleophobic coating<br/>
- Fully laminated display<br/>
- Antireflective coating<br/>
- 1.8% reflectivity<br/>
- 600 nits brightness</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
Chip
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>- A12X Bionic chip with 64-bit architecture<br/>
- Neural Engine<br/>
- Embedded M12 coprocessor</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
Camera
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>- 12-megapixel camera<br/>
- ƒ/1.8 aperture<br/>
- Digital zoom up to 5x<br/>
- Five‑element lens<br/>
- Quad-LED True Tone flash<br/>
- Panorama (up to 63 megapixels)<br/>
- Sapphire crystal lens cover<br/>
- Backside illumination sensor<br/>
- Hybrid IR filter<br/>
- Autofocus with Focus Pixels<br/>
- Tap to focus with Focus Pixels<br/>
- Live Photos with stabilization<br/>
- Wide color capture for photos and Live Photos<br/>
- Improved local tone mapping<br/>
- Exposure control<br/>
- Noise reduction<br/>
- Smart HDR for photos<br/>
- Auto image stabilization<br/>
- Burst mode<br/>
- Timer mode<br/>
- Photo geotagging<br/>
- Image formats captured: HEIF and JPEG</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="1">
Operating System
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>- iPadOS comes with powerful features and built-in apps designed to take<br/>
advantage of the unique capabilities of iPad.</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
<br/>
<Button href="/home" variant="outline-primary">Back to Shop</Button>
</div>
);
}
}
export default iPad;<file_sep>import React, { Component } from 'react';
import './Header.css';
import Navbar from 'react-bootstrap/Navbar'
import Nav from 'react-bootstrap/Nav'
import FormControl from 'react-bootstrap/FormControl'
import Form from 'react-bootstrap/Form'
import Button from 'react-bootstrap/Button';
import NavDropdown from 'react-bootstrap/NavDropdown'
class Header extends Component {
constructor(props) {
super(props);
this.state = {
data:[],
redirectToReferrer: false,
name:'',
};
this.getUserFeed = this.getUserFeed.bind(this);
this.logout = this.logout.bind(this);
}
componentWillMount() {
if(sessionStorage.getItem("userData")){
this.getUserFeed();
}
else{
this.setState({redirectToReferrer: true});
}
}
getUserFeed() {
let data = JSON.parse(sessionStorage.getItem("userData"));
this.setState({name:data.userData.name});
}
logout(){
sessionStorage.setItem("userData",'');
sessionStorage.clear();
window.location.href = "/login";
}
render() {
return (
/* <Navbar bg="dark" variant="dark" expand="lg" fixed="top" >
<nav class="navbar navbar-expand-sm " style={{width:'100%'}}>
<a class="navbar-brand" href="/" style={{fontSize:'20px'}}>TKD's Gadgets</a>
<ul class="navbar-nav ">
<li class="nav-item active">
<a class="nav-link" href="/home">Shop</a>
</li>
<li class="nav-item">
<a class="nav-link" href="//codeply.com">Codeply</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
<div class="navbar-brand" >
<NavDropdown title={this.state.name} id="basic-nav-dropdown" >
<NavDropdown.Item onClick={this.logout}>Logout</NavDropdown.Item>
</NavDropdown>
</div>
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
<div class="navbar-collapse collapse w-100" id="collapsingNavbar3">
<ul class="nav navbar-nav ml-auto w-100 justify-content-end">
<li class="nav-item">
<a class="nav-link" href="#">Right</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Right</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Right</a>
</li>
</ul>
</div>
</nav>
</Navbar> */
<div>
<Navbar bg="dark" variant="dark" expand="lg" fixed="top" >
<Navbar.Brand href="/">TKD's Gadgets</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="/home">Shop</Nav.Link>
<Nav.Link href="/cart">Cart</Nav.Link>
<Nav.Link href="/order">My Order</Nav.Link>
<NavDropdown title={this.state.name} id="basic-nav-dropdown">
<NavDropdown.Item onClick={this.logout}>Logout</NavDropdown.Item>
</NavDropdown>
</Nav>
</Navbar.Collapse>
</Navbar>
</div>
);
}
}
export default Header; | 898362bb0c0328c3ffa4348a0680778bccac94f8 | [
"JavaScript",
"SQL",
"PHP"
]
| 12 | JavaScript | DarunoK-init/web-app | fc849458ecefe61a51f414ff8d53bb220f8c4ff0 | bf58408a490751c06a25f1c5eb58ca6ea1ae76ff |
refs/heads/master | <file_sep>// Gulp rigger adding plugins
//= ../../../bower_components/jquery/dist/jquery.js
//= items/bootstrap.js
//= ../../../bower_components/swiper/dist/js/swiper.jquery.js
//= ../../../bower_components/ajaxchimp/jquery.ajaxchimp.js
//= ../../../bower_components/filterizr/dist/jquery.filterizr.min.js
//= ../../../bower_components/jquery.countdown/dist/jquery.countdown.js
//= ../../../bower_components/jquery.mb.ytplayer/dist/jquery.mb.YTPlayer.js
//= ../../../bower_components/jquery-validation/dist/jquery.validate.js
//= ../../../bower_components/particles.js/particles.js | ba02de6529147a6f552874fcfe4fa26d460cb99a | [
"JavaScript"
]
| 1 | JavaScript | WojciechRu/MyGulpPack | 6eea52774e5005f82bda7b70998dc2d9ea9a0b3a | 92f7c7487216153ced91d459e616d4a838060295 |
refs/heads/master | <file_sep>/*
* LaunchPad.h
*
*Created on: Apr 3, 2013
* Author: <NAME>
*Revised on: Oct 23, 2014
* Author: jnjuguna
*
* Note: Make sure that C:/ti/TivaWare_C_Series-2.1.0.12573 is located under the "Includes" drop down
* in the Project. If not:
* 1. Go to Properties->Include Options and add this location
*
*/
#ifndef LAUNCHPAD_H_
#define LAUNCHPAD_H_
#include <time.h>
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/asmdefs.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_adc.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_can.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_comp.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_eeprom.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_epi.h"
//#include "inc/hw_ethernet.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_fan.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_flash.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_gpio.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_hibernate.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_i2c.h"
//#include "inc/hw_i2s.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_ints.h"
//#include "inc/hw_lpc.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_memmap.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_nvic.h"
//#include "inc/hw_peci.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_pwm.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_qei.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_ssi.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_sysctl.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_sysexc.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_timer.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_types.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_uart.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_udma.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_usb.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/inc/hw_watchdog.h"
/*
* Include All Peripheral Driver Headers
*/
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/adc.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/can.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/comp.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/cpu.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/debug.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/eeprom.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/epi.h"
//#include "driverlib/ethernet.h"
//#include "driverlib/fan.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/flash.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/fpu.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/gpio.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/hibernate.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/i2c.h"
//#include "driverlib/i2s.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/interrupt.h"
//#include "driverlib/lpc.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/mpu.h"
//#include "driverlib/peci.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/pin_map.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/pwm.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/qei.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/rom_map.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/rom.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/rtos_bindings.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/ssi.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/sysctl.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/sysexc.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/systick.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/timer.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/uart.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/udma.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/usb.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/driverlib/watchdog.h"
/*
* Include All Utility Drivers
*/
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/utils/cmdline.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/utils/cpu_usage.h"
//#include "utils/crc.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/utils/flash_pb.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/utils/isqrt.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/utils/ringbuf.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/utils/scheduler.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/utils/sine.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/utils/softi2c.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/utils/softssi.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/utils/softuart.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/utils/uartstdio.h"
#include "C:/ti/TivaWare_C_Series-2.1.0.12573/utils/ustdlib.h"
/*
* On board button (switch) definitions
*/
#define lpSWPort GPIO_PORTF_BASE
#define lpSW1Port GPIO_PORTF_BASE
#define lpSW2Port GPIO_PORTF_BASE
#define lpSW1 GPIO_PIN_4
#define lpSW2 GPIO_PIN_0
#endif /* LAUNCHPAD_H_ */
<file_sep>extern "C" {
#include <FillPat.h>
#include <EEPROM.h>
#include <LaunchPad.h>
#include <my_oled.h>
#include <delay.h>
#include "OrbitBoosterPackDefs.h"
#include <OrbitOled.h>
#include <OrbitOledChar.h>
#include <OrbitOledGrph.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include <math.h>
}
#define LED RED_LED
extern int xchOledMax; // defined in OrbitOled.c
extern int ychOledMax; // defined in OrbitOled.c
bool fClearOled; // local variable needed
/*
* Used with getIt to check which Cmd_Type is being requested
*/
enum Cmd_Type { // Enums don't work as function return types or parameters for TI :/
twist_it,
shake_it,
orb_it,
flick_it
};
const int nameSize = 3;
const int scoreSize = 50;
const int SHAKE_THRESH = 600; // for shake it!
const int TWIST_THRESH = 550; // for twist it!
const int MAX_TWIST_READING = 4095;
const int START_DELAY = 2000; // delay before welcome and start msg (startscreen)
const int CNTDWN_DELAY = 1000; // delay between numbers for count down (startscreen)
const int BTN_DELAY = 190; // delay between button presses for name select and start screen
const int SGL_PLAYER_DELAY = 500; // single player delay
const int PASS_DELAY = 2000; // delay between passes
const int ROUND_DELAY = 1500; // delay between each round
const int FAIL_DELAY = 3000; // how long the game over screen plays
const int END_DELAY = 1500; // delay in endscreen before high scores
const int DEC_DEADLINE = 200; // amount the time decreases (halved for single player)
const int MIN_DEADLINE = 600; // the minimum time decreased
int deadLine = 3000; // time allotted per player
char *CMDSTRINGS[] = {"Twist It!","Shake It!","Orb It!","Flick It!"}; // in the same order as enum
char welcomeMsg[] = "ORB IT!";
char successMsg[] = "PASS IT ON"; // confirmation for correct input
char failMsg[] = "Game Over :("; // displayed when incorrect input, time too long
char scoreMsg[] = "Your Score:"; // displayed on final score screen
char newHighScoreMsg[] = "NEW HIGH SCORE";
char highScoreMsg[] = "High Scores";
char selectMsg[] = "Choose a Name:";
char confirmMsg[] = "FLICK to End";
char scoreString[scoreSize]; // 50 digits for the score because wtf 9000
char roundString[10]; // stores the current round
int MAX_PLAYERS = 10;
int totalPlayers = 1;
int curPlayer = 1; // current player number
int curRound = 0; // rounds passed
bool DEBUG = false; // for debugging
bool RESET = false; // set true to reset all the scores to dev 0
char debugString[10];
const int ledPin1 = GREEN_LED;
const int ledPin2 = BLUE_LED;
const int ledPin3 = RED_LED;
void setup() {
if (RESET) {
char *s = "dev";
int scoreS = 0;
char *t = "dev";
int scoreT = 0;
char *bha = "dev";
int scoreBha = 0;
writeEEPROM(200, scoreS, s);
writeEEPROM(100, scoreT, t);
writeEEPROM(0, scoreBha, bha);
}
pinMode(LED, OUTPUT);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
GPIOPadConfigSet(BTN1Port, BTN1, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPD);
GPIOPadConfigSet(BTN2Port, BTN2, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPD);
GPIOPadConfigSet(SWTPort, SWT1 | SWT2, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPD);
GPIOPinTypeGPIOInput(BTN1Port, BTN1);
GPIOPinTypeGPIOInput(BTN2Port, BTN2);
GPIOPinTypeGPIOInput(SWTPort, SWT1 | SWT2);
//Potentiometer stuff (The twist thing)
SysCtlPeripheralEnable(SYSCTL_PERIPH_ADC0);
GPIOPinTypeADC(AINPort, AIN);
ADCSequenceConfigure(ADC0_BASE, 0, ADC_TRIGGER_PROCESSOR, 0);
ADCSequenceStepConfigure(ADC0_BASE, 0, 0, ADC_CTL_IE | ADC_CTL_END | ADC_CTL_CH0);
ADCSequenceEnable(ADC0_BASE, 0);
// nice lil Serial debugging port
Serial.begin(9600);
// seed the random number with random noise? this code is copied :|
randomSeed(analogRead(0));
OrbitOledInit(); // set up the oled display
fClearOled = true; // clears the screen
if (!DEBUG) startScreen(); // remove it for debugging
}
void loop() {
if (!DEBUG){ // set debug to true; paste code in else portion
if (runAction()) { // increment the score based on the number of rounds
//Serial.println(deadLine);
if (totalPlayers == 1) {
fClearOled = true;
curRound++;
Serial.println("success");
delay(20);
Serial.println(187,DEC);
sprintf(roundString,"%d",curRound);
updateScreen(roundString,true);
delay(SGL_PLAYER_DELAY); // shortened delay for single player
if (deadLine > MIN_DEADLINE) deadLine -= DEC_DEADLINE/2; // time shortens more slowly for single player
} else {
fClearOled = true;
curPlayer++;
if (curPlayer > totalPlayers){ // if it's the last player of the round
Serial.println("success");
delay(20);
Serial.println(187,DEC);
delay(2);
Serial.println(78,DEC);
delay(2);
char roundMsg[20] = "Round ";
curPlayer = 1;
curRound++;
sprintf(roundString,"%d",curRound);
strcat(roundMsg,roundString);
strcat(roundMsg," Over");
updateScreen(roundMsg,true);
delay(ROUND_DELAY);
if (deadLine > MIN_DEADLINE) deadLine -= DEC_DEADLINE; // time shortens each round
} else {
Serial.println("success");
delay(20);
Serial.println(187,DEC);
delay(2);
Serial.println(78,DEC);
delay(2);
updateScreen(successMsg, true, 2);
delay(PASS_DELAY);
}
}
// sprintf(debugString,"%d",deadLine);
}
else {
return endScreen();
}
} else {
// Serial.println(selectScreen());
// while(1);
}
}
/**
* Returns a score based on a formula dependent on the current player
* and current round
*/
int getPasses(){
int scorePerPlayer = 100;
int score = 0;
int nPasses = (curPlayer - 1) + curRound*totalPlayers; // how many passes so far
return nPasses;
}
/*
* Rainbow Blinking for the beginning of the game
*/
int overTheRainbow(int t){
unsigned long initTime = millis();
unsigned long currentTime = millis();
while(currentTime - initTime < t){
digitalWrite(ledPin1, HIGH);
delay(100);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, HIGH);
delay(100);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, HIGH);
delay(100);
digitalWrite(ledPin3, LOW);
currentTime = millis();
}
}
/*
* Shows the startscreen
* Sets the number of players
*/
int startScreen(){
char startMsg[13] = "# Players:";
char startMsg2[20] = "FLICK to Start";
char playerString[4]; // max players is 2 digits long + space + null
// INITIALIZE FLICK
int original1 = GPIOPinRead(SWT1Port, SWT1); // original switch positions
int original2 = GPIOPinRead(SWT2Port, SWT2);
fClearOled = true;
updateScreen(welcomeMsg, true, 2);
overTheRainbow(START_DELAY);
fClearOled = true;
while (GPIOPinRead(SWT1Port, SWT1) == original1 && GPIOPinRead(SWT2Port, SWT2) == original2){ // while the switches haven't been flicked
if (GPIOPinRead(BTN2Port, BTN2)) { // move up
if (totalPlayers == MAX_PLAYERS)
totalPlayers = 1;
else
totalPlayers++;
}
else if (GPIOPinRead(BTN1Port, BTN1)) { // move down
if (totalPlayers == 1)
totalPlayers = MAX_PLAYERS;
else
totalPlayers--;
}
delay(BTN_DELAY); // button sensitivity
sprintf(playerString, "%d",totalPlayers);
if (totalPlayers==9 || totalPlayers == 1){ // gets rid of that pesky leading 1 digit
updateScreen(" ",xchOledMax-2,1,true);
}
updateScreen(startMsg, 0, 1, true);
updateScreen(playerString, xchOledMax-strlen(playerString),1,true);
updateScreen(startMsg2,true,3);
}
fClearOled = true;
strcpy(startMsg,"Players: ");
strcat(startMsg, playerString);
updateScreen(startMsg, true);
delay(CNTDWN_DELAY/2);
fClearOled = true;
updateScreen("3",true);
delay(CNTDWN_DELAY);
fClearOled = true;
updateScreen("2",true);
delay(CNTDWN_DELAY);
fClearOled = true;
updateScreen("1",true);
delay(CNTDWN_DELAY);
fClearOled = true;
updateScreen("Start!",true);
delay(CNTDWN_DELAY/2); // start's a bit quicker
}
/**
* Shows the endscreen
* Just to make our end configurable
*/
void endScreen(){
int score = getPasses();
if (checkScoreEEPROM(score)){
Serial.println(1000,DEC);
delay(20);
Serial.println(111,DEC);
delay(2);
Serial.println(1000,DEC);
delay(2);}
else {
Serial.println(78,DEC);
delay(2);
Serial.println("stop");
delay(15);
Serial.println(78,DEC);
delay(2);
int score = getPasses();}
fClearOled = true;
updateScreen(failMsg,true);
digitalWrite(LED, HIGH); // red lights on
delay(FAIL_DELAY);
digitalWrite(LED, LOW); // red lights off
fClearOled = true;
score = getPasses();
sprintf(scoreString, "%d", score);
updateScreen(scoreMsg, true, 1);
updateScreen(scoreString, true, 3);
delay(END_DELAY);
fClearOled = true;
// HIGH SCORES
if (checkScoreEEPROM(score)){
updateScreen(newHighScoreMsg,true);
overTheRainbow(END_DELAY);
char *name = selectScreen();
updateEEPROM(score,name);
} else;
printEEPROM();
while (1);
}
char* selectScreen(){
char *nameString = (char*)malloc(4*sizeof(char));
if (!nameString) //Serial.println("Error allocating memory for namestring");
nameString[0] = 'A'; nameString[1] = 'A'; nameString[2] = 'A'; nameString[3] = '\0';
char cursorString[4] = {'^',' ',' ','\0'}; // indicates the current cursor position
int NALPHA = 26;
int letterAt = 0;
char letter = nameString[letterAt]; // initialize
// INITIALIZE FLICK & SHAKE
int original1 = GPIOPinRead(SWT1Port, SWT1); // original switch positions
int original2 = GPIOPinRead(SWT2Port, SWT2);
short dataX, dataY, dataZ; // coordinate values
char chPwrCtlReg = 0x2D, chX0Addr = 0x32, chY0Addr = 0x34, chZ0Addr = 0x36; // addresses?
char rgchReadAccl_x[] = {0, 0, 0}, rgchReadAccl_y[] = {0, 0, 0}, rgchReadAccl_z[] = {0, 0, 0}; // where the data's stored
char rgchWriteAccl[] = {0, 0}; // facilitates writing
SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C0); // enable the I2C peripheral (accel)
SysCtlPeripheralReset(SYSCTL_PERIPH_I2C0);
GPIOPinTypeI2C(I2CSDAPort, I2CSDA_PIN); // set the pins
GPIOPinTypeI2CSCL(I2CSCLPort, I2CSCL_PIN);
GPIOPinConfigure(I2CSCL);
GPIOPinConfigure(I2CSDA);
I2CMasterInitExpClk(I2C0_BASE, SysCtlClockGet(), false); // set up I2C
GPIOPinTypeGPIOInput(ACCL_INT2Port, ACCL_INT2); // initialize accl
rgchWriteAccl[0] = chPwrCtlReg;
rgchWriteAccl[1] = 1 << 3; // sets accl in measurement mode
I2CGenTransmit(rgchWriteAccl, 1, WRITE, ACCLADDR);
fClearOled = true;
updateScreen(selectMsg, true, 0);
updateScreen(nameString,true,1);
updateScreen(cursorString,true,2);
updateScreen(confirmMsg,true, 5);
while (GPIOPinRead(SWT1Port, SWT1) == original1 && GPIOPinRead(SWT2Port, SWT2) == original2){ // while a button hasn't been pressed
if (GPIOPinRead(BTN2Port, BTN2)) { // move up
if (letter == 'Z') // 'Z' go to 'A'
letter = 'A';
else
letter++;
delay(BTN_DELAY); // button sensitivity
}
else if (GPIOPinRead(BTN1Port, BTN1)) { // move down
if (letter == 'A') // 'A' go to 'Z'
letter = 'Z';
else
letter--;
delay(BTN_DELAY); // button sensitivity
}
nameString[letterAt] = letter;
//Serial.println(nameString); // TODO remove
updateScreen(nameString,true,1);
// SHAKE
rgchReadAccl_x[0] = chX0Addr; // sets the channels for reading, i think
rgchReadAccl_y[0] = chY0Addr;
rgchReadAccl_z[0] = chZ0Addr;
I2CGenTransmit(rgchReadAccl_x, 2, READ, ACCLADDR); // gets the accelerometer data
I2CGenTransmit(rgchReadAccl_y, 2, READ, ACCLADDR);
I2CGenTransmit(rgchReadAccl_z, 2, READ, ACCLADDR);
dataX = (rgchReadAccl_x[2] << 8) | rgchReadAccl_x[1]; // get readable data
dataY = (rgchReadAccl_y[2] << 8) | rgchReadAccl_y[1];
dataZ = (rgchReadAccl_z[2] << 8) | rgchReadAccl_z[1];
if (sqrt(dataX*dataX+dataY*dataY+dataZ*dataZ) > SHAKE_THRESH){ // shake to switch letter at
cursorString[letterAt] = ' ';
if (letterAt == 2)
letterAt = 0;
else
letterAt++;
cursorString[letterAt] = '^';
letter = nameString[letterAt];
updateScreen(cursorString,true,2);
delay(BTN_DELAY);
}
}
//delay(1000);
return nameString;
}
/*
* Runs a random command
*/
int runAction() {
int action = random(0, 4); // note: this is exclusive; rub it currently not included
fClearOled = true;
updateScreen(CMDSTRINGS[action],true);
return getIt(action);
}
/*
* Sends the actual command for the user to respond to
* Returns 1 if the command was correct, 0 else
*/
int getIt(int cmd){ // enums aren't working for some reason
/*
* FLICK IT
*/
int original1 = GPIOPinRead(SWT1Port, SWT1); // original switch positions
int original2 = GPIOPinRead(SWT2Port, SWT2);
/*
* TWIST IT
*/
uint32_t ulAIN0; // where we store the current potentio readings
uint32_t init; // the initial reading as reference point
ADCProcessorTrigger(ADC0_BASE, 0); // initiate ADC conversion
while (!ADCIntStatus(ADC0_BASE, 0, false)); // waits until ready (i think)
ADCSequenceDataGet(ADC0_BASE, 0, &ulAIN0); // TODO: switch to init
ADCProcessorTrigger(ADC0_BASE, 0); // repeat for accuracy (required!)
while (!ADCIntStatus(ADC0_BASE, 0, false));
ADCSequenceDataGet(ADC0_BASE, 0, &ulAIN0);
init = ulAIN0;
int diff = 0; // initialize the difference we're gonna measure
/*
* SHAKE IT
*/
short dataX, dataY, dataZ; // coordinate values
char chPwrCtlReg = 0x2D, chX0Addr = 0x32, chY0Addr = 0x34, chZ0Addr = 0x36; // addresses?
char rgchReadAccl_x[] = {0, 0, 0}, rgchReadAccl_y[] = {0, 0, 0}, rgchReadAccl_z[] = {0, 0, 0}; // where the data's stored
char rgchWriteAccl[] = {0, 0}; // facilitates writing
SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C0); // enable the I2C peripheral (accel)
SysCtlPeripheralReset(SYSCTL_PERIPH_I2C0);
GPIOPinTypeI2C(I2CSDAPort, I2CSDA_PIN); // set the pins
GPIOPinTypeI2CSCL(I2CSCLPort, I2CSCL_PIN);
GPIOPinConfigure(I2CSCL);
GPIOPinConfigure(I2CSDA);
I2CMasterInitExpClk(I2C0_BASE, SysCtlClockGet(), false); // set up I2C
GPIOPinTypeGPIOInput(ACCL_INT2Port, ACCL_INT2); // initialize accl
rgchWriteAccl[0] = chPwrCtlReg;
rgchWriteAccl[1] = 1 << 3; // sets accl in measurement mode
I2CGenTransmit(rgchWriteAccl, 1, WRITE, ACCLADDR);
int deadTime = millis()+deadLine; // set timer
while(millis()<deadTime){ // check conditions
/*
* FLICK IT
*/
if (GPIOPinRead(SWT1Port, SWT1) != original1 ||
GPIOPinRead(SWT2Port, SWT2) != original2){ // check if switches have moved
if (cmd == flick_it) return 1;
else return 0;
}
/*
* ORB IT
*/
if (GPIOPinRead(BTN1Port, BTN1) ||
GPIOPinRead(BTN2Port, BTN2)){ // check if button pressed
if (cmd == orb_it) return 1;
else return 0;
}
/*
* TWIST IT
*/
ADCProcessorTrigger(ADC0_BASE, 0); // initiate ADC Conversion
while (!ADCIntStatus(ADC0_BASE, 0, false)); // waits until ready
ADCSequenceDataGet(ADC0_BASE, 0, &ulAIN0); // stores potentiometer data
diff = abs(ulAIN0 - init); // difference between current state and initial state
if (diff > TWIST_THRESH){ // if twisted beyond the threshold
if (cmd == twist_it) return 1;
else return 0;
}
/*
* SHAKE IT
*/
rgchReadAccl_x[0] = chX0Addr; // sets the channels for reading, i think
rgchReadAccl_y[0] = chY0Addr;
rgchReadAccl_z[0] = chZ0Addr;
I2CGenTransmit(rgchReadAccl_x, 2, READ, ACCLADDR); // gets the accelerometer data
I2CGenTransmit(rgchReadAccl_y, 2, READ, ACCLADDR);
I2CGenTransmit(rgchReadAccl_z, 2, READ, ACCLADDR);
dataX = (rgchReadAccl_x[2] << 8) | rgchReadAccl_x[1]; // get readable data
dataY = (rgchReadAccl_y[2] << 8) | rgchReadAccl_y[1];
dataZ = (rgchReadAccl_z[2] << 8) | rgchReadAccl_z[1];
if (sqrt(dataX*dataX+dataY*dataY+dataZ*dataZ) > SHAKE_THRESH){ // if the magnitude is beyond
if (cmd == shake_it) return 1;
else return 0;
}
}
return 0;
}
/**********************************************
* CODE NEEDED FOR SHAKE
*********************************************/
char I2CGenTransmit(char * pbData, int cSize, bool fRW, char bAddr) {
int i;
char * pbTemp;
pbTemp = pbData;
/*Start*/
/*Send Address High Byte*/
/* Send Write Block Cmd*/
I2CMasterSlaveAddrSet(I2C0_BASE, bAddr, WRITE);
I2CMasterDataPut(I2C0_BASE, *pbTemp);
I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_START);
DelayMs(1);
/* Idle wait*/
while (I2CGenIsNotIdle())
;
/* Increment data pointer*/
pbTemp++;
/*Execute Read or Write*/
if (fRW == READ) {
/* Resend Start condition
** Then send new control byte
** then begin reading
*/
I2CMasterSlaveAddrSet(I2C0_BASE, bAddr, READ);
while (I2CMasterBusy(I2C0_BASE))
;
/* Begin Reading*/
for (i = 0; i < cSize; i++) {
if (cSize == i + 1 && cSize == 1) {
I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_SINGLE_RECEIVE);
DelayMs(1);
while (I2CMasterBusy(I2C0_BASE))
;
} else if (cSize == i + 1 && cSize > 1) {
I2CMasterControl(I2C0_BASE,
I2C_MASTER_CMD_BURST_RECEIVE_FINISH);
DelayMs(1);
while (I2CMasterBusy(I2C0_BASE))
;
} else if (i == 0) {
I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_RECEIVE_START);
DelayMs(1);
while (I2CMasterBusy(I2C0_BASE))
;
/* Idle wait*/
while (I2CGenIsNotIdle())
;
} else {
I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_RECEIVE_CONT);
DelayMs(1);
while (I2CMasterBusy(I2C0_BASE))
;
/* Idle wait */
while (I2CGenIsNotIdle())
;
}
while (I2CMasterBusy(I2C0_BASE))
;
/* Read Data */
*pbTemp = (char) I2CMasterDataGet(I2C0_BASE);
pbTemp++;
}
} else if (fRW == WRITE) {
/*Loop data bytes */
for (i = 0; i < cSize; i++) {
/* Send Data */
I2CMasterDataPut(I2C0_BASE, *pbTemp);
while (I2CMasterBusy(I2C0_BASE))
;
if (i == cSize - 1) {
I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_FINISH);
DelayMs(1);
while (I2CMasterBusy(I2C0_BASE))
;
} else {
I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_CONT);
DelayMs(1);
while (I2CMasterBusy(I2C0_BASE))
;
/* Idle wait */
while (I2CGenIsNotIdle())
;
}
pbTemp++;
}
}
return 0x00;
}
bool I2CGenIsNotIdle() {
return !I2CMasterBusBusy(I2C0_BASE);
}
/**********************************************
* SCREEN METHODS
*********************************************/
void updateScreen(char sentence[], int x, int y, bool clear) {
OrbitOledMoveTo(0, 0);
if (clear) {
if (fClearOled) {
OrbitOledClear();
OrbitOledMoveTo(0, 0);
OrbitOledSetCursor(0, 0);
fClearOled = false;
}
}
OrbitOledSetCursor(x, y);
OrbitOledPutString(sentence);
}
void updateScreen(char sentence[], bool clear) {
if (clear) {
if (fClearOled) {
OrbitOledClear();
OrbitOledMoveTo(0, 0);
OrbitOledSetCursor(0, 0);
fClearOled = false;
}
}
int size = strlen(sentence);
OrbitOledSetCursor((xchOledMax - size) / 2.0 + 1, ychOledMax / 2);
OrbitOledPutString(sentence);
}
void updateScreen(char sentence[], bool clear, double y) {
OrbitOledMoveTo(0, 0);
if (clear) {
if (fClearOled) {
OrbitOledClear();
OrbitOledMoveTo(0, 0);
OrbitOledSetCursor(0, 0);
fClearOled = false;
}
}
int size = strlen(sentence);
OrbitOledSetCursor((xchOledMax - size) / 2.0 + 1, y);
OrbitOledPutString(sentence);
}
void updateScreen(char sentence[]) {
int size = strlen(sentence);
OrbitOledSetCursor((xchOledMax - size) / 2.0 + 1, ychOledMax / 2);
OrbitOledPutString(sentence);
}
/************************************************
* HIGH SCORES
***********************************************/
/*
* Writes the name and score to a specific address
*/
void writeEEPROM(int addr, int score, char* name){
int nDigits;
if (!score) nDigits = 1;
else nDigits = (int) (floor(log10(abs(score))) + 1);
for (int i = addr; i < addr + scoreSize-nDigits; i++){
EEPROM.write(i, 0);
}
int a = score;
if (!a)
EEPROM.write(addr + scoreSize - 1, 0);
else if(nDigits > 0)
{
for(int k = addr + scoreSize - 1; k >= addr + scoreSize - nDigits && a != 0; k--)
{
int nextDigit = a % 10;
a /= 10;
EEPROM.write(k, nextDigit);
}
}
// put the name in some characters later
int charIndex = 0;
for(int i = addr + scoreSize + 1; i < addr + scoreSize + nameSize + 1; i++)
{
EEPROM.write(i, (int)name[charIndex]);
charIndex++;
}
}
/*
* Reads the score from an address
*/
int readEEPROMScore(int addr){
int a = 0;
int power = 0;
for(int i = addr; i < addr + scoreSize; i++){
a += (int) EEPROM.read(i) * (int) floor(pow(10, scoreSize-power-1));
power++;
}
return a;
}
/*
* Reads the name from an address
*/
char * readEEPROMName(int addr){
char * s = (char *)malloc((nameSize + 1) * sizeof(char));
s[nameSize] = '\0';
int a = 0;
for(int i = addr + scoreSize + 1; i < addr + scoreSize + nameSize + 1; i++){
s[a] = (char) EEPROM.read(i);
a++;
}
return s;
}
/*
* Adds a new entry to memory if score is high enough
*/
void updateEEPROM(int score, char *name){
// addresses (constant)
int addr1 = 0;
int addr2 = 100;
int addr3 = 200;
if (score>readEEPROMScore(addr1)){ // if the score is the highest
int score1 = readEEPROMScore(addr1);
char* name1 = readEEPROMName(addr1);
int score2 = readEEPROMScore(addr2);
char *name2 = readEEPROMName(addr2);
writeEEPROM(addr1,score,name);
writeEEPROM(addr2,score1,name1);
writeEEPROM(addr3,score2,name2);
} else if (score>readEEPROMScore(addr2)){ // if the score is the second highest
int score2 = readEEPROMScore(addr2);
char *name2 = readEEPROMName(addr2);
writeEEPROM(addr2,score,name);
writeEEPROM(addr3,score2,name2);
} else if (score>readEEPROMScore(addr3)){ // if the score is the third highest
writeEEPROM(addr3,score,name);
}
}
/*
* Check if a score is higher than the current
* listings
*/
int checkScoreEEPROM(int score){
if(score > readEEPROMScore(200))
return 1;
return 0;
}
// print everybody on the top players list
int printEEPROM()
{
int x = 5;
double y = 1;
fClearOled = true;
updateScreen(highScoreMsg,true,0);
// go through each addreess on the list buddy
for(int i = 0; i < 3; i++)
{
int nextAddress = 100 * i;
int nextScore = readEEPROMScore(nextAddress);
char *player = append(nextAddress);
updateScreen(player,x,y,true);
y += 1;
delay(1000);
}
delay(3000);
}
/*
* Returns the appended name and score from an address
*/
char* append(int addr){
int power = 0;
int score = 0;
int nDigits = 0;
char *s;
char *t;
int a = 0;
for(int i = addr; i < addr + scoreSize; i++){
score += (int) EEPROM.read(i) * (int) floor(pow(10, scoreSize-power-1));
power++;
}
if(score>0) {
nDigits = floor(log10(abs(score))) + 1;
} else { // log10(0) is undefined
nDigits = 1;
}
s = (char *)malloc((nDigits + nameSize + 3) * sizeof(char));
t = readEEPROMName(addr);
s[nDigits + nameSize + 2] = '\0';
for (int i = 0; i < nameSize; i++){
s[i] = t[a];
a++;
}
s[nameSize] = ':';
s[nameSize + 1] = ' ';
for(int i = nameSize + 1 + nDigits; i >= nameSize + 2; i--){
s[i] = (char) (48 + score % 10);
score/=10;
}
return s;
}
<file_sep>#if !defined(MYOLED_INC)
#define MYOLED_INC
void init_OLED();
void setup_OLED();
void init_LEDS();
#endif
| c78f353ddb109262505757e8124e17e50189e375 | [
"C",
"C++"
]
| 3 | C | bhavyata9/orbit101 | 11b339a1f279e86b74c30774f1da0fba0ddf57ec | c50ebf858233e5cede95de9cd65f75ee1cc15a0a |
refs/heads/master | <repo_name>nowrie141/highlighter<file_sep>/README.md
<!-- PROJECT SHIELDS -->
<!--
*** I'm using markdown "reference style" links for readability.
*** Reference links are enclosed in brackets [ ] instead of parentheses ( ).
*** See the bottom of this document for the declaration of the reference variables
*** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use.
*** https://www.markdownguide.org/basic-syntax/#reference-style-links
-->
[![Contributors][contributors-shield]][contributors-url]
[![Forks][forks-shield]][forks-url]
[![Stargazers][stars-shield]][stars-url]
[![Issues][issues-shield]][issues-url]
[![MIT License][license-shield]][license-url]
[![LinkedIn][linkedin-shield]][linkedin-url]
<!-- PROJECT LOGO -->
<br />
<p align="center">
<a href="https://github.com/nowrie141/content-justifier">
<img src="images/justify128.png" alt="Logo" width="128" height="128">
</a>
<h3 align="center">Content Justifier</h3>
<p align="center">
An awesome Chrome extension to justify the text of every web page!
<br />
<a href="https://github.com/nowrie141/content-justifier"><strong>Explore the docs »</strong></a>
<br />
<br />
·
<a href="https://github.com/nowrie141/content-justifier/issues">Report Bug</a>
·
<a href="https://github.com/nowrie141/content-justifier/issues">Request Feature</a>
</p>
</p>
<!-- TABLE OF CONTENTS -->
## Table of Contents
- [About the Project](#about-the-project)
- [Built and Deployed With](#built-and-deployed-with)
- [What did I learn?](#what-did-i-learn-?)
- [Contributing](#contributing)
- [License](#license)
- [Contact](#contact)
<!-- ABOUT THE PROJECT -->
## About The Project
The project is created to provide an easy tool which allows the user to justify the content of every web page he visits. I made this project as I feel more comfortable reading text that is justified, it can be disabled anytime.
### Built and Deployed With
- [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript)
- [Google Chrome Extensions](https://developer.chrome.com/extensions/devguide)
- [HTML]()
- [CSS]()
<!-- WHAT DID I LEARN -->
## What did I learn?
In this project, I improved my skills as a web developer working on how to develop chrome extensions. I improved my skills with JavaScript and the development of Chrome extensions.
<!-- CONTRIBUTING -->
## Contributing
Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
<!-- LICENSE -->
## License
Distributed under the MIT License. See `LICENSE` for more information.
<!-- CONTACT -->
## Contact
<NAME> - [@abujadur](https://twitter.com/abujadur) - <EMAIL>
Project Link: [https://github.com/nowrie141/content-justifier](https://github.com/nowrie141/content-justifier)
<!-- MARKDOWN LINKS & IMAGES -->
[contributors-shield]: https://img.shields.io/github/contributors/nowrie141/content-justifier?style=flat-square
[contributors-url]: https://github.com/nowrie141/content-justifier/graphs/contributors
[forks-shield]: https://img.shields.io/github/forks/nowrie141/content-justifier.svg?style=flat-square
[forks-url]: https://github.com/nowrie141/content-justifier/network/members
[stars-shield]: https://img.shields.io/github/stars/nowrie141/content-justifier.svg?style=flat-square
[stars-url]: https://github.com/nowrie141/content-justifier/stargazers
[issues-shield]: https://img.shields.io/github/issues/nowrie141/content-justifier.svg?style=flat-square
[issues-url]: https://github.com/nowrie141/content-justifier/issues
[license-shield]: https://img.shields.io/github/license/nowrie141/content-justifier.svg?style=flat-square
[license-url]: https://github.com/nowrie141/content-justifier/blob/master/LICENSE.txt
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=flat-square&logo=linkedin&colorB=555
[linkedin-url]: https://linkedin.com/in/ismael-abu-jadur-garcía-809154a6
<file_sep>/scripts.js
'use strict'
// Listen for the messages send by clicking on the extension button
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.message === 'active') {
document.body.style.textAlign = 'justify'
} else {
document.body.style.textAlign = 'initial'
}
})
| 96e7db3108f6ade4343761968b3cb815b15b2ed5 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | nowrie141/highlighter | 04a50c8bbb90547e4dc7c8e6c8658e9b8a7ab358 | ae86c79f7c11be3aa18aa831af70db0cdb6ca8b9 |
refs/heads/master | <repo_name>btmatthew/VideoClassificationExperiment<file_sep>/src/main/java/convolution/Convolution.java
package convolution;
import org.canova.api.io.filters.BalancedPathFilter;
import org.canova.api.io.labels.ParentPathLabelGenerator;
import org.canova.api.split.FileSplit;
import org.canova.api.split.InputSplit;
import org.canova.image.loader.BaseImageLoader;
import org.canova.image.recordreader.ImageRecordReader;
import org.deeplearning4j.datasets.canova.RecordReaderDataSetIterator;
import org.deeplearning4j.eval.Evaluation;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.*;
import org.deeplearning4j.nn.conf.distribution.GaussianDistribution;
import org.deeplearning4j.nn.conf.distribution.NormalDistribution;
import org.deeplearning4j.nn.conf.layers.*;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.deeplearning4j.util.ModelSerializer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
/**
* Created by agibsonccc on 9/16/15.
*/
public class Convolution {
private static final Logger log = LoggerFactory.getLogger(Convolution.class);
protected static final long seed = 15468;//12345;
public static final Random randNumGen = new Random(seed);
protected static final String [] allowedExtensions = BaseImageLoader.ALLOWED_FORMATS;
static int nEpochs = 10;
static int batch =10;
static int channels=3;
static int height = 120;
static int width = 160;
static int output =2;
static int iterations = 1;
public static void main(String[] args) throws Exception {
File parentDir = new File("C:\\Users\\admin\\Desktop\\datasets\\dataset\\");
FileSplit filesInDir = new FileSplit(parentDir, allowedExtensions, randNumGen);
ParentPathLabelGenerator labelMaker = new ParentPathLabelGenerator();
BalancedPathFilter pathFilter = new BalancedPathFilter(randNumGen, allowedExtensions, labelMaker);
InputSplit[] filesInDirSplit = filesInDir.sample(pathFilter, 80, 20);
InputSplit trainData = filesInDirSplit[0];
InputSplit testData = filesInDirSplit[1];
ImageRecordReader recordReader = new ImageRecordReader(height,width,channels,labelMaker);
recordReader.initialize(trainData);
ImageRecordReader recordReader1 = new ImageRecordReader(height,width,channels,labelMaker);
recordReader1.initialize(testData);
log.info("Load data....");
DataSetIterator cnnTrain = new RecordReaderDataSetIterator(recordReader, batch, 1, output);
DataSetIterator cnnTest = new RecordReaderDataSetIterator(recordReader1, batch, 1, output);
log.info("Build model....");
log.info("Build model....");
// Tiny model configuration
MultiLayerNetwork network;
File modelFile = new File("CNNImageRecognision");
boolean loadModel = true;
if(loadModel) {
// MultiLayerConfiguration confTiny = new NeuralNetConfiguration.Builder()
// .seed(seed)
// .iterations(iterations)
// .activation("relu")
// .weightInit(WeightInit.XAVIER)
// .gradientNormalization(GradientNormalization.RenormalizeL2PerLayer)
// .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
// .updater(Updater.NESTEROVS)
// .learningRate(0.001)
// .momentum(0.2)
// .regularization(true)
// .l2(0.03)
// .useDropConnect(true)
// .list()
// .layer(0, new ConvolutionLayer.Builder(5, 5)
// .name("cnn1")
// .nIn(channels)
// .stride(1, 1)
// .padding(2, 2)
// .nOut(8)
// .activation("relu")
// .build())
// .layer(1, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
// .kernelSize(3, 3)
// .name("pool1")
// .build())
// .layer(2, new LocalResponseNormalization.Builder(3, 5e-05, 0.75).build())
// .layer(3, new ConvolutionLayer.Builder(5, 5)
// .name("cnn2")
// .stride(1, 1)
// .padding(2, 2)
// .nOut(8)
// .activation("relu")
// .build())
// .layer(4, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
// .kernelSize(3, 3)
// .name("pool2")
// .build())
// .layer(5, new LocalResponseNormalization.Builder(3, 5e-05, 0.75).build())
// .layer(6, new ConvolutionLayer.Builder(5, 5)
// .name("cnn2")
// .stride(1, 1)
// .padding(2, 2)
// .nOut(8)
// .activation("relu")
// .build())
// .layer(7, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
// .kernelSize(3, 3)
// .name("pool2")
// .build())
// .layer(8, new DenseLayer.Builder()
// .name("ffn1")
// .nOut(30)
// .build())
// .layer(9, new DenseLayer.Builder()
// .name("ffn2")
// .nOut(10)
// .build())
// .layer(10, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
// .nOut(output)
// .name("fully connected")
// .activation("softmax")
// .build())
// .backprop(true).pretrain(true)
// .cnnInputSize(height,width,channels).build();
network = new MultiLayerNetwork(mattNetwork());
network.init();
}else{
network = ModelSerializer.restoreMultiLayerNetwork(modelFile);
}
log.info("Train model....");
network.setListeners(new ScoreIterationListener(1));
//network.setListeners(new HistogramIterationListener(1));
for( int i=0; i<nEpochs; i++ ) {
while(cnnTrain.hasNext()){
DataSet trainData1 = cnnTrain.next();
network.fit(trainData1);
}
cnnTrain.reset();
ModelSerializer.writeModel(network, modelFile, true);
log.info("Evaluate model....");
evaluatePerformance(network,cnnTest);
cnnTest.reset();
}
log.info("****************Example finished********************");
}
private static void evaluatePerformance(MultiLayerNetwork model,DataSetIterator dataSetIterator) throws Exception {
//Assuming here that the full test data set doesn't fit in memory -> load 10 examples at a time
Map<Integer, String> labelMap = new HashMap<>();
labelMap.put(0, "person");
labelMap.put(1, "empty");
Evaluation evaluation = new Evaluation(labelMap);
DataSetIterator testData = dataSetIterator;
while(testData.hasNext()) {
DataSet dsTest = testData.next();
INDArray predicted = model.output(dsTest.getFeatureMatrix(), false);
INDArray actual = dsTest.getLabels();
evaluation.eval(actual,predicted);
}
System.out.println(evaluation.stats());
}
public static MultiLayerConfiguration mattNetwork(){
MultiLayerConfiguration confTiny = new NeuralNetConfiguration.Builder()
.seed(seed)
.iterations(iterations)
.activation("relu")
.weightInit(WeightInit.XAVIER)
.gradientNormalization(GradientNormalization.RenormalizeL2PerLayer)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.updater(Updater.NESTEROVS)
.learningRate(0.001)
.momentum(0.2)
.regularization(true)
.l2(0.03)
.useDropConnect(true)
.list()
.layer(0, new ConvolutionLayer.Builder(5, 5)
.name("cnn1")
.nIn(channels)
.stride(1, 1)
.padding(2, 2)
.nOut(8)
.activation("relu")
.build())
.layer(1, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
.kernelSize(3, 3)
.name("pool1")
.build())
.layer(2, new LocalResponseNormalization.Builder(3, 5e-05, 0.75).build())
// .layer(3, new ConvolutionLayer.Builder(5, 5)
// .name("cnn2")
// .stride(1, 1)
// .padding(2, 2)
// .nOut(8)
// .activation("relu")
// .build())
// .layer(4, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
// .kernelSize(3, 3)
// .name("pool2")
// .build())
// .layer(5, new LocalResponseNormalization.Builder(3, 5e-05, 0.75).build())
// .layer(6, new ConvolutionLayer.Builder(5, 5)
// .name("cnn2")
// .stride(1, 1)
// .padding(2, 2)
// .nOut(8)
// .activation("relu")
// .build())
// .layer(7, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
// .kernelSize(3, 3)
// .name("pool2")
// .build())
.layer(3, new DenseLayer.Builder()
.name("ffn1")
.nOut(30)
.build())
// .layer(9, new DenseLayer.Builder()
// .name("ffn2")
// .nOut(10)
// .build())
.layer(4, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.nOut(output)
.name("fully connected")
.activation("softmax")
.build())
.backprop(true).pretrain(false)
.cnnInputSize(height,width,channels).build();
return confTiny;
}
public static MultiLayerConfiguration alexNetetwork(){
double nonZeroBias = 1;
double dropOut = 0.5;
SubsamplingLayer.PoolingType poolingType = SubsamplingLayer.PoolingType.MAX;
// TODO split and link kernel maps on GPUs - 2nd, 4th, 5th convolution should only connect maps on the same gpu, 3rd connects to all in 2nd
MultiLayerConfiguration.Builder conf = new NeuralNetConfiguration.Builder()
.seed(seed)
.weightInit(WeightInit.DISTRIBUTION)
.dist(new NormalDistribution(0.0, 0.01))
.activation("relu")
.updater(Updater.NESTEROVS)
.iterations(iterations)
.gradientNormalization(GradientNormalization.RenormalizeL2PerLayer) // normalize to prevent vanishing or exploding gradients
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.learningRate(0.02)
.biasLearningRate(1e-2*2)
.learningRateDecayPolicy(LearningRatePolicy.Step)
.lrPolicyDecayRate(0.1)
.lrPolicySteps(100000)
.regularization(true)
.l2(0.04)
.momentum(0.2)
.miniBatch(true)
.list()
.layer(0, new ConvolutionLayer.Builder(new int[]{11, 11}, new int[]{4, 4}, new int[]{3, 3})
.name("cnn1")
.nIn(channels)
.nOut(96)
.build())
.layer(1, new LocalResponseNormalization.Builder()
.name("lrn1")
.build())
.layer(2, new SubsamplingLayer.Builder(poolingType, new int[]{3, 3}, new int[]{2, 2})
.name("maxpool1")
.build())
.layer(3, new ConvolutionLayer.Builder(new int[]{5, 5}, new int[]{1, 1}, new int[]{2, 2})
.name("cnn2")
.nOut(256)
.biasInit(nonZeroBias)
.build())
.layer(4, new LocalResponseNormalization.Builder()
.name("lrn2")
.k(2).n(5).alpha(1e-4).beta(0.75)
.build())
.layer(5, new SubsamplingLayer.Builder(poolingType, new int[]{3, 3}, new int[]{2, 2})
.name("maxpool2")
.build())
.layer(6, new ConvolutionLayer.Builder(new int[]{3, 3}, new int[]{1, 1}, new int[]{1, 1})
.name("cnn3")
.nOut(384)
.build())
.layer(7, new ConvolutionLayer.Builder(new int[]{3, 3}, new int[]{1, 1}, new int[]{1, 1})
.name("cnn4")
.nOut(384)
.biasInit(nonZeroBias)
.build())
.layer(8, new ConvolutionLayer.Builder(new int[]{3, 3}, new int[]{1, 1}, new int[]{1, 1})
.name("cnn5")
.nOut(256)
.biasInit(nonZeroBias)
.build())
.layer(9, new SubsamplingLayer.Builder(poolingType, new int[]{3, 3}, new int[]{2, 2})
.name("maxpool3")
.build())
.layer(10, new DenseLayer.Builder()
.name("ffn1")
.nOut(4096)
.dist(new GaussianDistribution(0, 0.005))
.biasInit(nonZeroBias)
.dropOut(dropOut)
.build())
.layer(11, new DenseLayer.Builder()
.name("ffn2")
.nOut(4096)
.dist(new GaussianDistribution(0, 0.005))
.biasInit(nonZeroBias)
.dropOut(dropOut)
.build())
.layer(12, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.name("output")
.nOut(output)
.activation("softmax")
.build())
.backprop(true)
.pretrain(false)
.cnnInputSize(height,width,channels);
return conf.build();
}
public static MultiLayerNetwork leNetNetwork() {
MultiLayerConfiguration.Builder conf = new NeuralNetConfiguration.Builder()
.seed(seed)
.iterations(1)
.activation("sigmoid")
.weightInit(WeightInit.DISTRIBUTION)
.dist(new NormalDistribution(0.0, 0.01))
.learningRate(7*10e-5)
//.learningRate(1e-3)
.learningRateScoreBasedDecayRate(1e-1)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.list()
.layer(0, new ConvolutionLayer.Builder(new int[]{5, 5}, new int[]{1, 1})
.name("cnn1")
.nIn(3)
.nOut(6)
.build())
.layer(1, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX, new int[]{2, 2}, new int[]{2, 2})
.name("maxpool1")
.build())
.layer(2, new ConvolutionLayer.Builder(new int[]{5, 5}, new int[]{1, 1})
.name("cnn2")
.nOut(16)
.biasInit(1)
.build())
.layer(3, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX, new int[]{2, 2}, new int[]{2, 2})
.name("maxpool2")
.build())
.layer(4, new DenseLayer.Builder()
.name("ffn1")
.nOut(120)
.build())
.layer(5, new DenseLayer.Builder()
.name("ffn2")
.nOut(84)
.build())
.layer(6, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.name("output")
.nOut(2)
.activation("softmax") // radial basis function required
.build())
.backprop(true)
.pretrain(false)
.cnnInputSize(height,width,channels);
MultiLayerNetwork model = new MultiLayerNetwork(conf.build());
model.init();
return model;
}
}
| 51119e9d7cc22404f029b0817aed4536700ceac0 | [
"Java"
]
| 1 | Java | btmatthew/VideoClassificationExperiment | 5e443b2a857c9ea16f134032792ac352ce331a46 | c0a236206e828ca32b65d14805e863335349f123 |
refs/heads/master | <repo_name>neosat55/phpBookExample<file_sep>/generator/test.php
<?php
require_once('generator.php');
$arr = [1, 2, 3, 4, 5];
// $select = select($arr, function($e) { return $e % 2 === 0; });
// $collect = collect($select, function($e) { return $e * $e; });
$range = crangeWithArr(1024000);
// foreach ($range as $i) echo "$i ";
echo memory_get_usage();
// foreach ($collect as $val) echo "$val ";
// foreach (even_square($arr) as $value) echo " $value ";<file_sep>/builtInFunction/test.php
<?php
require_once("builtInFunction.php");
$from = ["{Title}", "{Body}"];
$to = ['Filosdfk', 'sadfsadfsadfasdfasdf'];
$template = <<<MARKER
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{Title}</title>
</head>
<body>
{Body}
</body>
</html>
MARKER;
// echo str_replace($from, $to, $template);
// $built = file_get_contents('builtInFunction/text.php') or die('Error');
// file_put_contents("newtext.php", $built);
// print_r($built);
// echo "<pre>";
// echo "/\n";
// смена текущей директории
// chdir($_SERVER['DOCUMENT_ROOT']);
// printTree();
// echo "</pre>";
echo "<pre>";
print_r(glob("*.php"));
echo "</pre>";
$text = <<<CLA
<?php
class {NAME} extends Controllers
{
private index()
{
}
}
CLA;
// echo "$" . number_format(100000.1224, 2, ",", " ");
$text = "Новую версию PHP 7 сообщество разработчиков ожидало более 10 лет. Предыдущие издание книги вышло более 8 лет назад. За это время язык и среда разработки изменились кардинально. PHP обогатился трейтами, пространством имен, анонимными функциями, замыканиями, элементами строгой типизации, генераторами, встроенным Web-сервером и многими другими возможностями. Версия PHP 7 дополняет язык новыми операторами, переработанным механизмом обработки ошибок, анонимными классами, рассширенной поддержкой генераторов, кодировки UTF-8 и множеством более мелких изменений. Все возможности языка детально освещаются в книге. В третьем издании добавлены 24 новые главы, остальные главы обновлены или переработаны.";
// echo "<pre>";
// echo cite($text, 120);
setlocale(LC_ALL, 'ru_RU.UTF-8');
echo '<pre>';
print_r(getUniques($text));
echo '</pre>';
$linkText = 'Сыыыылка: (http://themaxtix.com), www.ru?"a"=b, http://dojki.ru';
echo hrefActivate($linkText);
// $d = opendir('.');
// while (false !== ($e = readdir($d))) {
// if (is_dir($e)) $files[$e] = 0;
// else $files[$e] = filesize($e);
// }
// uksort($files, function($f1, $f2) {
// if (is_dir($f1) && !is_dir($f2)) return -1;
// if (!is_dir($f1) && is_dir($f2)) return 1;
// return $f1 <=> $f2;
// });
// extract($_SERVER, EXTR_PREFIX_ALL, "E");
// echo "<pre>";
// print_r($_SERVER);
// echo "</pre>";
// $arr = [1, 32, 5, 31, 43];
// echo min($arr);
?><file_sep>/OOP/FileLogger.php
<?php
namespace FileLogger;
class Logger
{
public $f;
public $name;
public $lines = [];
function __construct($name, $f)
{
$this->name = $name;
$this->f = fopen($f, "a+");
}
public function log($str)
{
$prefix = "[" . date('Y-m-d_h:i:s ') . "{$this->name}] ";
$str = preg_replace('/^/m', $prefix, rtrim($str));
$this->lines[] = $str . "\n";
}
public function __destruct()
{
$this->log("### __desctruct called");
fputs($this->f, join('', $this->lines));
fclose($this->f);
}
public function __get($a) {
echo $a;
}
public function __call($fn, $a) {
echo $fn;
echo $a;
}
}<file_sep>/OOP/autoload.php
<?php
function __autoload($classname)
{
require_once(__DIR__ . "/$classname.php");
}<file_sep>/OOP/test.php
<?php
// require_once __DIR__ . '/MathComplex.php';
// require_once __DIR__ . '/FileLogger.php';
// require_once __DIR__ . '/FileLoggerDebug.php';
require_once(__DIR__ . '/Error.php');
// spl_autoload_register(function($classname){
// echo $classname;
// require_once(__DIR__ . "/$classname.php");
// });
set_error_handler("myErrorHandler", E_ALL);
filemtime('sppotm.txt');
// // use File;
// $obj = new Math\MathComplex(10, 11);
// echo $obj;
// // $obj->add(10, 34);
// // print_r($obj->__toString());
// $logger = new File\Logger("test$n.log");
// $logger->debug('Text');<file_sep>/network/Network.php
<?php
class Network
{
// Функция отключает кэширование страниц
public function nocache()
{
header('Expires: Thu, 19 Feb 1998 13:24:18 GMT');
header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0');
header('Cache-Control: max-age=0');
header('Pragma: no-cache');
}
public function printHeaderList()
{
echo "<pre>";
print_r(headers_list());
echo "</pre>";
}
public function counter()
{
$counter = isset($_COOKIE['counter']) ? $_COOKIE['counter'] : 0;
$counter++;
setcookie('counter', $counter, 0x7FFFFFFF);
echo "$counter";
}
public function parseQueryString($str)
{
parse_str($str, $out);
$this->__print_array($out);
}
public function wrap()
{
echo "<h1>First page</h1>";
echo file_get_contents('http://php.net');
echo "<h1>Second page</h1";
echo file_get_contents('ftp://ftp.aha.ru/');
}
public function sessionCountExample($grn, $n)
{
session_name($grn);
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
}
$_SESSION['count'] += $n;
// echo session_id($grn);
echo "<h2>Счётчик сессий {$_SESSION['count']}</h2>";
}
public function destroySession()
{
$_SESSION = [];
unset($_COOKIE[session_name()]);
session_destroy();
}
private function __print_array($arr)
{
echo "<pre>";
print_r($arr);
echo "</pre>";
}
}<file_sep>/extension/Extension.php
<?php
// require_once('connect_db.php');
class Extension
{
public function filterExample()
{
$email_correct = '<EMAIL>';
$email_wrong = '<EMAIL>';
echo 'correct=' . filter_var($email_correct, FILTER_VALIDATE_EMAIL) . '<br/>';
echo 'wrond=' . filter_var($email_wrong, FILTER_SANITIZE_EMAIL) . '<br/>';
}
public function filterVarArray()
{
$data = [
'number' => 5,
'first' => 'chapter01',
'second' => 'ch02',
'id' => 2,
'float' => 11.00
];
$definition = [
'number' => [
'filter' => FILTER_VALIDATE_INT,
'options' => ['min_range' => -10, 'max_range' => 10]
],
'first' => [
'filter' => FILTER_VALIDATE_REGEXP,
'options' => ['regexp' => '/^ch\d+$/']
],
'second' => [
'filter' => FILTER_VALIDATE_REGEXP,
'options' => ['regexp' => '/^ch\d+$/']
],
'id' => FILTER_VALIDATE_INT,
'float' => [
'filter' => FILTER_VALIDATE_FLOAT,
'options' => ['min_range' => 0, 'max_range' => 100]
]
];
$res = filter_var_array($data, $definition);
$this->__print_array($res);
}
public function mysqlVersion()
{
$pdo = $GLOBALS['pdo'];
$pdo = "";
$query = "SELECT version() as version";
$ver = $pdo->query($query);
$version = $ver->fetch();
echo $version['version'];
}
public function createButtonImage()
{
$string = 'Hello, world';
$im = imagecreate(10, 10);
$color = imageColorAllocate($im, 0, 0, 0);
$px = (imageSX($im) - 6.5 * strlen($string)) / 2;
imageString($im, 3, $px, 1, $string, $color);
// header('Content-Type: image/png');
$img = imagePng($im);
echo '<img src="' . $img . '">';
imageDestroy($im);
}
public function curlExample()
{
$curl = curl_init('http://php.net');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($curl);
curl_close($curl);
echo $content;
}
public function curlGetContent($hostname)
{
$curl = curl_init($hostname);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_NOBODY, 1);
$content = curl_exec($curl);
curl_close($curl);
$this->__print_array(explode("\r\n", $content));
}
public function memcachedExample()
{
$m = new Memcached();
// Можно добавлять по отдельности
// $m->addServer('mem1.domain.com', 11211, 10);
// $m->addServer('mem1.domain.com', 11211, 100);
// Можно добавить в массиве
// $m->addServers([
// ['mem1.domain.com', 11211, 10],
// ['mem1.domain.com', 11211, 100]
// ]);
$m->addServer('127.0.0.1', 11211);
if ($m->add("keys", "values")) {
echo 'Value ' . $m->get('keys');
} else {
echo $m->getResultMessage();
}
$m->set('keys', 'aaaaa');
print_r($m->get('keys'));
}
private function __print_array($arr)
{
echo "<pre>";
print_r($arr);
echo "</pre>";
}
}<file_sep>/builtInFunction/builtInFunction.php
<?php
function cite($outText, $maxLen = 60, $prefix = "> ")
{
$st = wordwrap($outText, $maxLen - strlen($prefix), "\n");
$st = $prefix.str_replace("\n", "\n$prefix", $st);
return $st;
}
// выводит дерево каталагов
function printTree($level = 1)
{
$d = @opendir('.');
if (!$d) return;
while (($e = readdir($d)) !== false) {
if ($e === '.' || $e === '..') continue;
if (!is_dir($e)) continue;
for ($i = 0; $i < $level; $i++) {
echo " ";
}
echo "$e\n";
if (!chdir($e)) continue;
printTree($level + 1);
chdir('..');
flush();
}
closedir($d);
}
// вычисляет timestamp в Гринвиче,
// который соответствует timestamp-формату
function local2gm($localStamp = false)
{
if ($localStamp === false) {
$localStamp = time();
}
$tzOffset = date('Z', $localStamp);
return $localStamp - $tzOffset;
}
// Вычисляет локальный timestamp в Гривниче, который
// соответствует timestamp-формату GMT. Можно указать
// смещение локальной зоны относительно GMT (в часах)
// тогда будет осущетсвлён перевод в эту зону
// (а не текущую локальную)
function gm2Local($gmStamp = false, $tzOffset = false)
{
if ($gmStamp === false) {
return time();
}
if ($tzOffset === false) {
$tzOffset = date('Z', $gmStamp);
} else {
$tzOffset *= 60 * 60;
}
return $gmStamp + $tzOffset;
}
// эта функция выделяет из текста в $text все уникальные слова
// и возвращает их список. В необязательный параметр $nOrigWord
// помещается исходное число слов в тексте, которое было до
// фильтрации
function getUniques($text, $nOrigWord = false)
{
$words = preg_split("/([^[:alnum:]]|['-])+/s", $text);
$nOrigWord = count($words);
$words = array_map("strtolower", $words);
$words = array_unique($words);
return $words;
}
// функция преобразует ссылки в тексте в эквивалентый html тег
function hrefActivate($text)
{
echo $text;
return preg_replace_callback(
'{
(?:
(\w+://)
|
www\.
)
[\w-]+(\.[\w-]+)*
(?: : \d+)?
[^<>"\'()\[\]\s]*
(?:
(?<! [[:punct:]])
|
(?<= [-/&+*])
)
}xis',
function ($p) {
$name = htmlspecialchars($p[0]);
$href = !empty($p[1]) ? $name : "http://$name";
return "<a href=\"$href\">$name</a>";
},
$text
);
}<file_sep>/extension/test.php
<?php
require_once(__DIR__ . '/Extension.php');
$ext = new Extension();
// $ext->filterExample();
// $ext->filterVarArray();
// $ext->mysqlVersion();
// $ext->createButtonImage();
// $ext->curlExample();
// $ext->curlGetContent('http://php.net');
$ext->memcachedExample();
// print_r($mem);<file_sep>/definedClasses/View.php
<?php
class View
{
protected $pages = [];
protected $title = 'Контакты';
protected $body = 'About contact';
public function addPage($page, $pageCallback)
{
# code...
$this->pages[$page] = $pageCallback->bindTo($this, __CLASS__);
}
public function render($page)
{
$this->pages[$page]();
$content = <<<HTML
<div class="wrapper">
<h3>{$this->title()}</h3>
<div>{$this->body()}</div>
</div>
HTML;
echo $content;
}
public function title()
{
return htmlspecialchars($this->title);
}
public function body()
{
return nl2br(htmlspecialchars($this->body));
}
}<file_sep>/generator/generator.php
<?php
function collect($arr, $callback)
{
foreach ($arr as $val) {
yield $callback($val);
}
}
function select($arr, $callback)
{
foreach ($arr as $val) {
if ($callback($val)) yield $val;
}
}
function square($val)
{
yield $val * $val;
}
function even_square($arr)
{
foreach ($arr as $value) {
if ($value % 2 === 0) yield from square($value);
}
}
function crangeWithArr($size) {
$arr = [];
for ($i = 0; $i < $size; $i++) {
$arr[] = $i;
}
return $arr;
}
function crangeWithGen($size) {
for($i = 0; $i < $size; $i++) {
yield $i;
}
}<file_sep>/index.php
<?php
// require_once('generator/test.php');
// require_once('builtInFunction/test.php');
// require_once('OOP/test.php');
// require_once('definedClasses/test.php');
// require_once('network/test.php');
require_once('extension/test.php');
// echo $_SERVER['REMOTE_ADDR'];
// $count = 0;
// if (isset($_COOKIE['count'])) $count = $_COOKIE['count'];
// $count++;
// setcookie('count', $count, 0x7FFFFFFF, '/');
// echo $count;
// $a = ['a' => 10, 'b' => 20];
// $b = ['b' => 'new'];
// $a += $b;
// print_r($a);
// function incremetn(&$a)
// {
// echo "A $a </br>";
// $a++;
// echo "A $a </br>";
// }
// function selfCount()
// {
// static $count = 0;
// $count++;
// echo $count;
// }
// function father($a)
// {
// echo "$a </br>";
// function child($b) {
// echo $b + 1, '</br>';
// return $b * $b;
// }
// return $a * $a * child($a);
// }
// function myEcho(...$str)
// {
// foreach ($str as $v) {
// echo "$v</br>\n";
// }
// }
// function tabber($spaces, ...$planets) {
// $new = [];
// foreach ($planets as $planet) {
// $new[] = str_repeat(" ", $spaces).$planet;
// }
// call_user_func_array("myEcho", $new);
// }
// tabber(10, "Mercure", "Venus", "Earth", "Mars");
// $message = "Work don't be continue </br>";
// $check = function (array $errors) use ($message)
// {
// if (isset($errors) && count($errors) > 0) {
// echo $message;
// foreach ($errors as $error) {
// echo "$error </br>";
// }
// }
// };
// // $check([]);
// // $errors[] = "Fill username";
// // $check($errors);
// // $message = "Required list";
// // $errors = ["PHP", "MySQL", "memcache"];
// // $check($errors);
// function takeVal($a) { $x = $a[1234]; }
// function takeRef(&$a) { $x = $a[1234]; }
// function takeValAndMod($a) {$a[1234]++;}
// function takeRefAndMod(&$a) {$a[1234]++;}
// // test("takeVal");
// // test("takeRef");
// // test("takeValAndMod");
// // test("takeRefAndMod");
// function test($func) {
// $a = [];
// for ($i = 1; $i < 10000; $i++) {
// $a[$i] = $i;
// }
// for ($t = time(); $t == time(); );
// for ($n = 0, $t = time(); time() == $t; $n++) {
// $func($a);
// }
// printf("<tt>$func</tt> took %d itr/sec</br>", $n);
// }
<file_sep>/definedClasses/definedClasses.php
<?php
require_once('./OOP/MathComplex.php');
// Пример встроенного класса Directory
// функция dir
function getCatalog() {
$cat = dir('.');
while (($file = $cat->read()) !== false) {
echo $file . '<br />';
}
$cat->close();
}
function diffDate($date) {
$dDate = new DateTime($date);
$nowDate = new DateTime();
$interval = $nowDate->diff($dDate);
echo $dDate->format('d-m-Y H:i:s') . "<br/>";
echo $nowDate->format('d-m-Y H:i:s') . "<br/>";
echo $interval->format("%Y-%m-%d %H:%S") . "<br/>";
echo "<pre>";
print_r($interval);
echo "</pre>";
}
// рекурсивный обход дерева
function recursion_dir($path) {
static $depth = 0;
$dir = opendir($path);
while(($file = readdir($dir)) !== false) {
if ($file === '.' || $file === '..') continue;
echo str_repeat('-', $depth) . "$file<br/>";
if (is_dir("$path/$file")) {
$depth++;
recursion_dir("$path/$file");
$depth--;
}
}
closedir($dir);
}
function recursive_iterator($path)
{
$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), true);
foreach ($dir as $file) {
echo str_repeat('-', $dir->getDepth()) . "$file<br/>";
}
}
function reflectionClass($className, $args)
{
$class = new ReflectionClass($className);
$obj = $class->newInstance(102, 303);
echo "First obj: $obj<br/>";
$obj = call_user_func_array([$class, 'newInstance'], $args);
echo "Second obj: $obj<br/>";
}<file_sep>/definedClasses/FSDirectory.php
<?php
class FSDirectory implements IteratorAggregate
{
public $path;
public function __construct($path)
{
$this->path = $path;
}
public function getIterator()
{
return new FSDirectoryIterator($this);
}
}
class FSDirectoryIterator implements Iterator
{
private $owner;
private $d = null;
private $curr = false;
public function __construct($owner)
{
$this->owner = $owner;
$this->d = opendir($owner->path);
$this->rewind();
}
public function rewind()
{
rewinddir($this->d);
$this->curr = readdir($this->d);
}
public function valid()
{
return $this->cur !== false;
}
public function key()
{
return $this->cur;
}
public function current()
{
$path = $this->owner->path . '/' . $this->cur;
return is_dir($path) ? new FSDirectory($path) : new FSFile($path);
}
public function next()
{
$this->cur = readdir($this->d);
}
}
class FSFile
{
public $path;
public function __construct($path)
{
$this->path = $path;
}
public function getSize() {
return filesize($this->path);
}
}
<file_sep>/README.md
# PHP example of the book<file_sep>/definedClasses/test.php
<?php
require_once(__DIR__ .'/definedClasses.php');
require_once(__DIR__ .'/View.php');
require_once(__DIR__ .'/FSDirectory.php');
// chdir('definedClasses');
getCatalog();
$view = new View();
$d = new FSDirectory('.');
foreach ($d as $path => $entry) {
if ($entry instanceof FSFile) {
echo "<tt>$path</tt> " . $entry->getSize() . "<br>";
} else {
echo "<br><tt>$path</tt> ";
}
}
$view->addPage('about', function() {
$this->title = 'Us';
$this->body = 'About us';
});
$view->render('about');
diffDate('2015-01-01 0:0:0');
// recursive_iterator('.');
reflectionClass('MathComplex', [12, 35]);
/**
* document
* aaaa
*/
function foo($which)
{
echo "(fooooooo $which)";
}
$func = new ReflectionFunction('foo');
print_r(get_loaded_extensions());
// echo $func->isUserDefined();
// echo $func->getName()
// echo $func->getDocComment();<file_sep>/network/test.php
<?php
require_once(__DIR__ . '/Network.php');
setcookie('cookie', 'Some text');
setcookie('cookie', 'Some text', time() + 3600);
$netw = new Network();
$netw->nocache();
$netw->printHeaderList();
$netw->counter();
$netw->parseQueryString('sullivan=paul&names[roy]=noni&names[read]=tom');
$netw->sessionCountExample('sesA', 1);
$netw->sessionCountExample('sesB', 3);
// $netw->destroySession();<file_sep>/OOP/Error.php
<?php
function myErrorHandler($errno, $msg, $file, $line)
{
echo '<div style="border-style: inset; border-width:2">';
echo "Error with code <b>$errno</b></br>";
echo "File <tt>$file</tt>, line $line. </br>";
echo "Error text: <i>$msg</i>";
echo "</div>";
} | 41bfe170d26b9b17eef57fe30a5b1cac75dae79d | [
"Markdown",
"PHP"
]
| 18 | PHP | neosat55/phpBookExample | d114909ab5422bb873525496fa4be992a3796dc6 | 3f3a0c552553b8c282f29550c9cc38d750726987 |
refs/heads/master | <repo_name>2794957194/akdata<file_sep>/_docs/levels.md
---
title: 关卡信息(可用)
withjs: true
withcss: true
parent: /stages/
---
<file_sep>/_docs/mastery.js
const ProfessionNames = {
"PIONEER": "先锋",
"WARRIOR": "近卫",
"SNIPER": "狙击",
"TANK": "重装",
"MEDIC": "医疗",
"SUPPORT": "辅助",
"CASTER": "术师",
"SPECIAL": "特种",
// "TOKEN": "召唤物",
// "TRAP": "装置",
};
const DamageColors = ['black','blue','limegreen','gold','aqua'];
const DefaultAttribute = {
phase: 2,
level: "max",
favor: 200,
potential: 5, // 0-5
skillLevel: 9, // 0-9
options: { cond: true, crit: true, stack: true }
};
const DefaultEnemy = { def: 0, magicResistance: 0, count: 1, hp: 0 };
const Stages = {
"基准": { level: 1, potential: 0, skillLevel: 6, desc: "精2 1级 潜能1 技能7级" },
"满级": { level: "max", desc: "精2 满级 潜能1 技能7级" },
"专1": { skillLevel: 7, desc: "满级 潜能1 专精1" },
"专2": { skillLevel: 8, desc: "满级 潜能1 专精2" },
"专3": { skillLevel: 9, desc: "满级 潜能1 专精3" },
"满潜": { potential: 5, desc: "满级 满潜 专精3"},
};
function init() {
$('#update_prompt').text("正在载入角色数据,请耐心等待......");
AKDATA.load([
'excel/character_table.json',
'excel/skill_table.json',
'../version.json',
'../customdata/dps_specialtags.json',
'../customdata/dps_options.json',
'../resources/attributes.js'
], load);
}
const charColumnCount = $(document).width() <= 1400 ? 2 : 4;
const Characters = new Array(charColumnCount);
function getElement(classPart, index) {
return $(`.dps__${classPart}[data-index="${index}"]`);
}
function buildVueModel() {
let version = AKDATA.Data.version;
// select char list
let charList = {};
Object.keys(ProfessionNames).forEach(key => {
var opts = [];
for (let id in AKDATA.Data.character_table) {
let data = AKDATA.Data.character_table[id];
if (data.profession == key && data.phases.length > 2)
opts.push({"name": data.name, "id": id});
}
charList[ProfessionNames[key]] = opts;
});
return {
version,
charList,
charId: "-",
chartKey: "dps",
resultView: {},
test: "test"
};
}
function load() {
$("#vue_version").html("程序版本: {{ version.akdata }}, 数据版本: {{ version.gamedata }}");
// build html
let html = `
<div id="vue_app">
<div class="card mb-2">
<div class="card-header">
<div class="card-title mb-0">干员</div>
</div>
<table class="table dps" style="table-layout:fixed;">
<tbody>
<tr class="dps__row-select" style="width:20%;"> <th style="width:200px;">干员</th> </tr>
</tbody>
</table>
</div>
<div class="card mb-2">
<div class="card-header">
<div class="card-title">
专精收益
<span class="float-right">
<input type="radio" id="btn_avg" value="dps" v-model="chartKey">
<label for="btn_avg">平均dps/hps</label>
<input type="radio" id="btn_skill" value="s_dps" v-model="chartKey">
<label for="btn_skill">技能dps/hps</label>
<input type="radio" id="btn_total" value="s_dmg" v-model="chartKey">
<label for="btn_total">技能总伤害/治疗</label>
</span>
</div>
</div>
<div id="chart"></div>
</div>
<!--
<div class="card mb-2">
<div class="card-header">
<div class="card-title mb-0">调试信息</div>
</div>
<pre>{{ debugPrint(test) }}</pre>
</div>
-->
</div>`;
let $dps = $(html);
$dps.find('.dps__row-select').append(`<td>
<div class="input-group">
<select class="form-control" v-model="charId" v-on:change="changeChar">
<optgroup v-for="(v, k) in charList" :label="k">
<option v-for="char in v" :value="char.id">
{{ char.name }}
</option>
</optgroup>
</select>
<div class="input-group-append">
<button class="btn btn-outline-secondary dps__goto" type="button"><i class="fas fa-search"></i></button>
</div>
</div>
</td>`);
pmBase.content.build({
pages: [{
content: $dps,
}]
});
// setup vue
window.model = buildVueModel();
let vue_version = new Vue({
el: '#vue_version',
data: {
version: window.model.version,
}
});
window.vue_app = new Vue({
el: '#vue_app',
data: window.model,
methods: {
changeChar: function(event) {
this.resultView = calculate(this.charId);
},
debugPrint: function(obj) {
//console.log(JSON.stringify(obj, null, 2));
return JSON.stringify(obj, null, 2);
}
},
watch: {
resultView: function(_new, _old) {
plot(_new, this.chartKey);
},
chartKey: function(_new, _old) {
updatePlot(this.resultView, _new);
}
}
});
// test c3.js
// var chart = c3.generate({
// bindto: '#chart',
// data: {
// columns: [
// ['data1', 30, 200, 100, 400, 150, 250],
// ['data2', 50, 20, 10, 40, 15, 25]
// ]
// }
// });
}
function goto() {
let $this = $(this);
let index = ~~$this.data('index');
if ( Characters[index].charId ) {
window.open(`../character/#!/${Characters[index].charId}`, '_blank');
}
}
function buildChar(charId, skillId, recipe) {
let char = {
charId,
skillId,
phase: recipe.phase,
favor: recipe.favor,
potentialRank: recipe.potential,
skillLevel: recipe.skillLevel,
options: recipe.options
};
let db = AKDATA.Data.character_table[charId];
let skilldb = AKDATA.Data.skill_table[skillId];
let maxLevel = db.phases[recipe.phase].maxLevel;
if (recipe.level == "max")
char.level = maxLevel;
else
char.level = recipe.level;
char.name = db.name;
char.skillName = skilldb.levels[char.skillLevel].name;
//console.log(char);
return char;
}
function calculate(charId) {
let db = AKDATA.Data.character_table[charId];
let recipe = DefaultAttribute;
let enemy = DefaultEnemy;
let stages = Stages;
let raidBuff = { atk: 0, atkpct: 0, ats: 0, cdr: 0 };
let result = {};
// calculate dps for each recipe case.
db.skills.forEach(skill => {
var entry = {};
for (let st in stages) {
$.extend(recipe, stages[st]);
var ch = buildChar(charId, skill.skillId, recipe);
ch.dps = AKDATA.attributes.calculateDps(ch, enemy, raidBuff);
entry[st] = ch;
};
result[skill.skillId] = entry;
});
// window.model.test = result;
// extract result, making it more readable
// name, skill, stage, damageType, avg, skill, skilldamage, cdr
let resultView = {
name: db.name,
skill: {},
stages: stages,
dps: {}
};
for (let k in result) {
resultView.skill[k] = result[k]["基准"].skillName;
resultView.dps[k] = {};
for (let st in stages) {
var entry = result[k][st].dps;
resultView.dps[k][st] = {
damageType: entry.skill.damageType,
dps: entry.globalDps,
hps: entry.globalHps,
s_dps: entry.skill.dps,
s_hps: entry.skill.hps,
s_dmg: entry.skill.totalDamage,
s_heal: entry.skill.totalHeal,
};
};
};
return resultView;
}
const HealKeys = {
dps: "hps",
s_dps: "s_hps",
s_dmg: "s_heal"
};
function plot(view, key) {
// rotate data for plot columns
let columns = [], groups = [], skill_names = [];
var last = {};
for (let stg in view.stages) {
var entry = [stg];
for (let skill in view.skill) {
var value = view.dps[skill][stg][key];
if (view.dps[skill][stg].damageType == 2) {
value = view.dps[skill][stg][HealKeys[key]];
}
if (skill in last)
entry.push(value - last[skill]);
else
entry.push(value);
last[skill] = value;
}
columns.push(entry);
groups.push(stg);
}
for (let skill in view.skill)
skill_names.push(view.skill[skill]);
window.chart = c3.generate({
bindto: "#chart",
data: {
type: "bar",
columns: [],
groups: [groups],
order: null,
colors: { "基准": "#eeeeee" }
},
axis: {
rotated: true,
x: {
type: "category",
categories: skill_names
}
},
bar: {
width: { ratio: 0.4 }
},
zoom: { enabled: true },
});
setTimeout(function() {
window.chart.load({ columns: columns }, 1000);
});
}
function updatePlot(view, key) {
// rotate data for plot columns
let columns = [], groups = [], skill_names = [];
var last = {};
for (let stg in view.stages) {
var entry = [stg];
for (let skill in view.skill) {
var value = view.dps[skill][stg][key];
if (view.dps[skill][stg].damageType == 2) {
value = view.dps[skill][stg][HealKeys[key]];
}
if (skill in last)
entry.push(value - last[skill]);
else
entry.push(value);
last[skill] = value;
}
columns.push(entry);
groups.push(stg);
}
for (let skill in view.skill)
skill_names.push(view.skill[skill]);
setTimeout(function() {
window.chart.load({ columns: columns, groups: groups }, 1000);
});
}
pmBase.hook.on('init', init);
| c52325fe746de1cd0df58cc1e234063d51be4bfe | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | 2794957194/akdata | 78a0967911dd0a298f5efc3be49da244240e63d6 | 303ba13d0c2c9a7c1bca90541daf7a8ff0b5e624 |
refs/heads/master | <file_sep> //
// WeightedGraph.cpp
// WeightedGraph
//
// Created by <NAME> on 4/2/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
#include "WeightedGraph.h"
WeightedGraph::WeightedGraph(){
nodes.clear();
}
void WeightedGraph::addNode(int val){
Node *n = new Node(val);
if (nodes.empty())
nodes.push_back(n);
else{
for (int i = 0; i < nodes.size(); i++)
if (nodes[i]->info == val)
return;
nodes.push_back(n);
}
}
void WeightedGraph::addDirectedEdge(Node *first, Node *second, int weight){
if (first->list.empty() && (first->info != second->info)){
first->list.insert({second, weight});
}
else if(first->info == second->info){
return;
}
else{
unordered_map<Node*, int>::iterator it;
for (it = first->list.begin(); it != first->list.end(); it++){
if (it->first->info == second->info)
return;
}
first->list.insert({second, weight});
}
}
void WeightedGraph::removeDirectedEdge(Node *first, Node *second){
if (first->list.empty())
return;
unordered_map<Node*, int>::iterator it;
for (it = first->list.begin(); it != first->list.end(); it++)
if (it->first->info == second->info)
it->first->list.erase(second);
}
void WeightedGraph::printNodes(){
cout << " { ";
for (int i = 0; i < nodes.size(); i++)
cout << nodes[i]->info << " ";
cout << " }" << endl;
}
void WeightedGraph::printU(){
unordered_map<Node*, int>::iterator it;
for (int i = 0; i < nodes.size(); i++){
cout << nodes[i]->info << ": ";
for (it = nodes[i]->list.begin(); it != nodes[i]->list.end(); it++){
cout << "{" << it->first->info << ":" << it->second << "} ";
}
cout << endl;
}
cout << endl;
}
void WeightedGraph::clear(){
nodes.clear();
}
void WeightedGraph::updateDistance(Node *f, Node *s, unordered_map<Node*, int> &umap){
int min = 0, dist = 0;
unordered_map<Node*, int>::iterator it;
for (it = f->list.begin(); it != f->list.end(); it++){
if (it->first->info == s->info)
dist = it->second;
}
min = f->distance + dist;
if (min < s->distance){
s->distance = min;
it = umap.find(s);
it->second = min;
}
}
Node* WeightedGraph::findMinDistance(unordered_map<Node*, int> umap){
Node *n = nullptr;
unordered_map<Node*, int>::iterator it;
if (umap.empty())
return nullptr;
int minimum = INT_MAX;
for (it = umap.begin(); it != umap.end(); it++){
if (!it->first->visit)
if (minimum > it->second)
n = it->first;
}
return n;
}
void WeightedGraph::createRandomCompleteWeightedGraph(int n){
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int> dist(0, (n*n*n));
int r, i;
for (i = 0; i < n; i++)
addNode(dist(mt));
for (i = 0; i < nodes.size(); i++){
for (int j = 0; j < nodes.size(); j++){
if (nodes[i]->info == nodes[j]->info)
continue;
else{
r = rand() % 15 + 1;
addDirectedEdge(nodes[i], nodes[j], r);
}
}
}
}
void WeightedGraph::createLinkedList(int n){
int random, m = n*5;
for (int i = 0; i < n; i++){
random = rand() % m + 1;
addNode(random);
if (nodes.size() > 1)
addDirectedEdge(nodes[nodes.size()-2], nodes[nodes.size()-1], 1);
}
}
unordered_map<Node*, int> WeightedGraph::d(){
return dijkstras(nodes[0]);
}
unordered_map<Node*, int> WeightedGraph::dijkstras(Node *start){
unordered_map<Node*, int> m;
unordered_map<Node*, int>::iterator it;
vector<Node*> vec;
Node *n;
for (it = start->list.begin(); it != start->list.end(); it++)
m.insert({it->first, it->first->distance});
start->distance = 0;
m.insert({start, start->distance});
n = start;
while (n != nullptr && n->distance != INT_MAX){
n->visit = true;
for (it = n->list.begin(); it != n->list.end(); it++){
if (!it->first->visit){
m.insert({it->first, it->first->distance});
updateDistance(n, it->first, m);
}
}
n = findMinDistance(m);
}
return m;
}
<file_sep>//
// WeightedGraph.h
// WeightedGraph
//
// Created by <NAME> on 4/2/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
//https://users.cs.fiu.edu/~weiss/dsaa_c++4/code/TestRandom.cpp
#ifndef WeightedGraph_h
#define WeightedGraph_h
#include <iostream>
#include <vector>
#include <climits>
#include <random>
#include <unordered_map>
#include <unordered_set>
using namespace std;
struct Node{
int info;
int distance;
bool visit;
Node *parent;
unordered_map<Node*, int> list;
Node(int i, int d = INT_MAX, bool v = false) : info(i), distance(d), visit(v){}
};
class WeightedGraph{
vector<Node*> nodes;
public:
WeightedGraph();
void addNode(int val);
void addDirectedEdge(Node *first, Node *second, int weight);
void removeDirectedEdge(Node *first, Node *second);
unordered_set<Node*> getAllNodes();
void createRandomCompleteWeightedGraph(int n);
void createLinkedList(int n);
unordered_map<Node*, int> dijkstras(Node *start);
unordered_map<Node*, int> d();
void updateDistance(Node *first, Node *second, unordered_map<Node*, int> &umap);
Node* findMinDistance(unordered_map<Node*, int> v);
void printNodes();
void printU();
void clear();
};
#endif /* WeightedGraph_h */
<file_sep>//
// main.cpp
// WeightedGraph
//
// Created by <NAME> on 4/2/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
#include "WeightedGraph.h"
int main(int argc, const char * argv[]) {
WeightedGraph g;
unordered_map<Node*, int> umap;
unordered_map<Node*, int>::iterator it;
g.createLinkedList(10);
cout << "LinkedList";
g.printNodes();
g.printU();
g.clear();
g.createRandomCompleteWeightedGraph(10);
cout << "Graph";
g.printNodes();
g.printU();
umap = g.d();
cout << "Disjktra's: ";
for (it = umap.begin(); it != umap.end(); it++)
cout << "{" << it->first->info << ":" << it->second << "}" << " ";
cout << endl;
return 0;
}
| dca77a19fda90c81a17baa29c89c0ccfd153747a | [
"C++"
]
| 3 | C++ | MatthewRodriguez/WeightedGraph | 1a18c69de5af7c7b01f91de28d1e778d7485d89d | aceefca223390de4b3a7323a743ea856841024d4 |
refs/heads/main | <file_sep>a,b,c = input().split(" ")
a = int(a)
b = int(b)
c = int(c)
MaiorAB = (a+b+abs(a-b))/2
MaiorABC = (MaiorAB+c+abs(MaiorAB-c))/2
convercao = int(MaiorABC)
print(convercao," eh o maior")<file_sep>A,B,C,D = input().split(" ")
A = int(A)
B = int(B)
C = int(C)
D = int(D)
if(B > C) and (D > A) and ((C+D)>(A+B)and(C>=0) and (D>=0)and((A%2)== 0)):
print("Valores aceitos")
else:
print("Valores nao aceitos")<file_sep>codigo,quantidade = input().split(" ")
codigo = int(codigo)
quantidade = int(quantidade)
precoProdutos = [4.00, 4.50, 5.00, 2.00, 1.50]
calculoPreco = (quantidade) * (precoProdutos[codigo-1])
print("Total: R$ {:.2f}".format(calculoPreco))<file_sep>x1,y1 = input().split(" ")
x2,y2 = input().split(" ")
x1 = float(x1)
y1 = float(y1)
x2 = float(x2)
y2 = float(y2)
calculoX = (x2-x1)**2
calculoY = (y2-y1)**2
distancia = (calculoX+calculoY)**0.5
print("%.4f"%distancia)<file_sep># Uri Online Judge
Resoluções dos problemas do Uri
<file_sep>A,B,C = input().split(" ")
A = float(A)
B = float(B)
C = float(C)
lista = [A,B,C]
listaOrdenada = sorted(lista)
soma = listaOrdenada[0]+listaOrdenada[1]
perimetro = A+B+C
area = ((A+B)/2)*C
if(soma > listaOrdenada[2]):
print("Perimetro = {:.1f}".format(perimetro))
else:
print("Area = {:.1f}".format(area))<file_sep>N1,N2,N3,N4 = input().split(" ")
N1 = float(N1)
N2 = float(N2)
N3 = float(N3)
N4 = float(N4)
mediaPeso = ((N1*2)+(N2*3)+(N3*4)+(N4*1))/10
print("Media: {:.1f}".format(mediaPeso))
if(mediaPeso >= 7.0):
print("Aluno aprovado.")
elif(mediaPeso < 5.0):
print("Aluno reprovado.")
elif(mediaPeso >= 5.0 and mediaPeso <= 6.9):
print("Aluno em exame.")
N4 = float(input())
print("Nota do exame:",N4)
mediaFinal = (N4 + mediaPeso)/2
if(mediaFinal >= 5.0):
print("Aluno aprovado.")
print("Media final: {:.1f}".format(mediaFinal))
elif(mediaFinal <= 4.9):
print("Aluno reprovado.")
print("Media final: {:.1f}".format(mediaFinal))<file_sep>tempoGasto = int(input())
velocidadeMedia = int(input())
consumoMedio = 12
calculoDistancia = velocidadeMedia*tempoGasto
consumoTotal = calculoDistancia/consumoMedio
print("%.3f"%consumoTotal)<file_sep>A,B,C = input().split(" ")
A = float(A)
B = float(B)
C = float(C)
lista = sorted([A,B,C],reverse = True)
if((lista[0]) >= (lista[1]+lista[2])):
print("NAO FORMA TRIANGULO")
else:
if((lista[0]**2) == ((lista[1]**2)+(lista[2]**2))):
print("TRIANGULO RETANGULO")
if((lista[0]**2)>((lista[1]**2)+(lista[2]**2))):
print("TRIANGULO OBTUSANGULO")
if((lista[0]**2)<((lista[1]**2) + (lista[2]**2))):
print("TRIANGULO ACUTANGULO")
if(A == B == C):
print("TRIANGULO EQUILATERO")
if(((A==B)and (A != C)))or((A==C)and(A!=B))or(((C == B) and (A != C))):
print("TRIANGULO ISOSCELES")<file_sep>raio = float(input())
n = 3.14159
area = n*(raio**2)
print("A=%.4f" % area)<file_sep>totalSegundos = int(input())
quantidadeHoras = totalSegundos//60//60
segundosHoras = quantidadeHoras*60*60
restante = totalSegundos - segundosHoras
quantidadeMinutos = restante//60
segundosMinutos = quantidadeMinutos*60
quantidadeSegundos = restante - segundosMinutos
print('{}:{}:{}'.format(quantidadeHoras, quantidadeMinutos, quantidadeSegundos))<file_sep>valor = float(input())
notas = [100, 50, 20, 10, 5, 2]
moedas = [1.0 , 0.50, 0.25, 0.10, 0.05 , 0.01]
print("NOTAS:")
for nota in notas:
quantNotas = int((valor/nota))
print("{} nota(s) de R$ {:.2f}".format(quantNotas,nota))
valor -= quantNotas * nota
print("MOEDAS:")
for moeda in moedas:
quantMoedas = int(round(valor,2) / moeda)
print("{} moeda(s) de R$ {:.2f}".format(quantMoedas,moeda))
valor -= quantMoedas * moeda<file_sep>distanciaCarroY = int(input())
velocidadeCarro01 = 60
velocidadeCarro02 = 90
calculoTempoDistancia = distanciaCarroY*2
print(calculoTempoDistancia, "minutos")<file_sep>A,B,C = input().split(" ")
A = float(A)
B = float(B)
C = float(C)
raiz = (B**2)-4*A*C
divisao = 2*A
if(raiz < 0):
print("Impossivel calcular")
elif(divisao == 0):
print("Impossivel calcular")
else:
raiz = raiz**0.5
x1 = (-B + raiz)/divisao
x2 = (-B - raiz)/divisao
print("R1 = {:.5f}".format(x1))
print("R2 = {:.5f}".format(x2))<file_sep>a,b,c = input().split(" ")
a = int(a)
b = int(b)
c = int(c)
if(a < b and a < c):
if(b < c):
print(a)
print(b)
print(c)
else:
print(a)
print(c)
print(b)
elif((b < a) and (b < c)):
if(a < c):
print(b)
print(a)
print(c)
else:
print(b)
print(c)
print(a)
elif((c < a) and (c < b)):
if(a < b):
print(c)
print(a)
print(b)
else:
print(c)
print(b)
print(a)
print()
print(a)
print(b)
print(c)<file_sep>numeroFuncionario = int(input())
numeroHorasTrabalhada = int(input())
valorHoraTrabalhada = float(input())
salario = numeroHorasTrabalhada*valorHoraTrabalhada
print("NUMBER =",numeroFuncionario)
print("SALARY = U$ %.2f"%salario)<file_sep>a,b,c = input().split(" ")
a = float(a)
b = float(b)
c = float(c)
areaTringulo = (a*c)/2
areaCirculo = (c**2)*(3.14159)
areaTrapezio = ((a+b)/2)*c
areaQuadrado = b**2
areaRetangulo = a*b
print("TRIANGULO: %.3f"%areaTringulo)
print("CIRCULO: %.3f"%areaCirculo)
print("TRAPEZIO: %.3f"%areaTrapezio)
print("QUADRADO: %.3f"%areaQuadrado)
print("RETANGULO: %.3F"%areaRetangulo)<file_sep>a,b = input().split(" ")
a = int(a)
b = int(b)
if (a > b):
duracao = ((23 - a)+(b+1))
print("O JOGO DUROU",duracao, "HORA(S)")
elif(a == b):
duracao = 24
print("O JOGO DUROU", duracao,"HORA(S)")
else:
duracao = b - a
print("O JOGO DUROU", duracao,"HORA(S)")<file_sep>c1,n1,v1 = input().split(" ")
c2,n2,v2 = input().split(" ")
c1 = int(c1)
n1 = int(n1)
v1 = float(v1)
c2 = int(c2)
n2 = int(n2)
v2 = float(v2)
valorPagar = (n1*v1)+(n2*v2)
print("VALOR A PAGAR: R$ %.2f"%valorPagar)<file_sep>raio = float(input())
pi = 3.14159
volumeEsfera = ((4.0/3)*pi*raio**3)
print("VOLUME = %.3f"%volumeEsfera)<file_sep>nomeVendedor = input()
salarioFixo = float(input())
totalVendasNoMes = float(input())
comicao = 0.15
salarioFinal = (salarioFixo)+(totalVendasNoMes*comicao)
print("TOTAL = R$ %.2f"%salarioFinal)<file_sep>distancia = int(input())
combustivelGasto = float(input())
consumoMedio = (distancia/combustivelGasto)
print("%.3f"%consumoMedio,"km/l")<file_sep>valor = int(input())
notas = [100, 50, 20, 10, 5, 2 , 1]
print(valor)
for nota in notas:
quantNotas = int((valor/nota))
print("{} nota(s) de R$ {},00".format(quantNotas,nota))
valor -= quantNotas * nota<file_sep>dias = int(input())
ano = dias//365
print(ano,"ano(s)")
dias = dias - (ano*365)
mes = dias//30
print(mes,"mes(es)")
dias = dias - (mes*30)
print(dias,"dia(s)") | eafc0393f2f87a20a6158438fddfc34c31fda241 | [
"Markdown",
"Python"
]
| 24 | Python | klayton-a-souza/Uri-Online-Judge | bcd0ea39637ae023ef3e0d20d83d6ac39ee4e828 | ccb5ff59b7c48d941a7b1476c947b57a273bd92e |
refs/heads/master | <repo_name>ohheythereandy/CS311Project2<file_sep>/README.txt
This is a repositoy for my Formal Languages and Automata class project!
<file_sep>/src/NFSA.java
/**
* Created by Andy on 2/15/18.
* This class represents the NFSA object. In this program, it is instantiated by FileInput for every set of input fitting
* a complete machine from the MachineInput.txt file
*/
import java.util.*;
import java.io.*;
public class NFSA {
private static final String ALPHABET = "a b c d e f g h i j k l m n o p q r s t u v w x y z";
private HashMap<Character, Integer> internalAlphabet = new HashMap<>();
private int totalStates;
private boolean[] finalState;
private ArrayList<String> testers, transitionArray;
private ArrayList<Character> actualAlphabet;
private String firstLine;
private String[] initInput;
Set<Integer>[][] nfa;
/**
* Class constructor. Calls appropriate methods to load machine fields and attributes before printing
* @param initialRead is the string containing input strings for the machine
* @param testStrings is the string containing test strings
* @param iteration is the identifying number for the current automata
* @throws IOException if file can't be written to
*/
public NFSA(String initialRead, ArrayList<String> testStrings, int iteration) throws IOException{
firstLine = initialRead;
testers = testStrings;
transitionArray = new ArrayList<>();
actualAlphabet = new ArrayList<>();
totalStates = 1;
//parse out total state number and alphabet
loadStates();
setFinalStates();
loadMachine();
printToFile(iteration);
//Create new DFSA from NFSA info
DFSA dfa = new DFSA(nfa, internalAlphabet,finalState, testers, iteration);
}
/**
* This method is responsible for printing to the file
* @param iteration is the FSA number being tested
* @throws IOException whenever file can't be written to
*/
private void printToFile(int iteration) throws IOException{
try {
FileWriter fw = new FileWriter("MachineOutput.txt", true);
BufferedWriter writer = new BufferedWriter(fw);
writer.write("-------------------------\n");
writer.write("Non-Finite State Automaton #" + iteration + "\n");
writer.write("(1) Number of States: " + totalStates + "\n");
writer.write("(2) Final States: " + printFinalStates() + "\n");
writer.write("(3) Alphabet: " + ALPHABET + "\n");
writer.write("(4) Transitions:\n");
printTransitions(writer);
writer.close();
}
catch(IOException i){
System.out.println("Unable to print.");
}
}
/**
* This method is responsible for printing the transitions loaded into the table by traversing through the array,
* looking for non empty sets.
* @param bw is used to write to the file
* @throws IOException if file can't be written to
*/
private void printTransitions(BufferedWriter bw) throws IOException {
//traverse through 2D array of sets to print transitions
for(int i = 0; i < nfa.length; i++){
for(int j = 0; j < nfa[i].length; j++){
if(!(nfa[i][j].isEmpty())){
//bw.write(" " + "i " + actualAlphabet.get(j).toString() + "\n");
transitionArray.add(" " + i + " " + actualAlphabet.get(j).toString() + " " + printSet(i,j) + "\n");
}
}
}
//write all transitions
for(String s : transitionArray){
bw.write(s + "\n");
}
}
/**
* This method navigates through given set and returns a string of all the integers in the set
* @param firstIndex is the index for the row array in 2D array
* @param secondIndex is the index for the column in the 2d Array
* @return string representing integers in the set
*/
private String printSet(int firstIndex, int secondIndex){
StringBuilder sb = new StringBuilder();
Set<Integer> tempSet = nfa[firstIndex][secondIndex];
for(Integer i : tempSet){
sb.append(i + " ");
}
return sb.toString();
}
/**
* This method is responsible for iterating through the FinalState array and printing out the indices that are final states
* @return String containing all final states represented as integers
*/
private String printFinalStates() {
int count = 0;
StringBuilder sb = new StringBuilder();
for(boolean b : finalState){
if(b){
sb.append(count + " ");
}
count++;
}
return sb.toString();
}
/**
* This method is responsible for adding transitions to the table
* Also keeps track of the alphabet and numbers them internally
*/
private void loadMachine(){
initializeSets();
int currentState = 0;
ArrayList<Character> tempAlphabet = new ArrayList<>();
//loop through characters in each string and add each one to the list of letters and the map to number it
//Also start creating nfa by adding transitions.
//currentState represents the count of state we are in
//We use the map to get the internal number for the letter
for(String input: initInput){
char[] temp = input.toCharArray();
for(char letter: temp){
currentState++;
//if the letter already is in list, go back to initial state
if(letter == temp[0]){
nfa[0][internalAlphabet.get(letter)].add((currentState));
}
else if(!(tempAlphabet.contains(letter)))
{
nfa[(currentState - 1)][internalAlphabet.get(letter)].add((currentState));
tempAlphabet.add(letter);
}
else{
nfa[currentState-1][internalAlphabet.get(letter)].add(currentState);
}
}
}
}
/**
* To intialize all sets within nfa in an effort to avoid NullPointerException
*/
private void initializeSets() {
nfa = new HashSet[totalStates][actualAlphabet.size()];
for(int i = 0; i < totalStates; i++){
for(int j = 0; j < actualAlphabet.size(); j++){
nfa[i][j] = new HashSet<Integer>();
}
}
}
/**
* This Method is responsible for setting the final states inside the boolean array
*/
private void setFinalStates(){
finalState = new boolean[totalStates];
int currentState = 0;
for(String input: initInput) {
currentState += (input.length());
finalState[currentState] = true;
}
}
/**
* This method first checks if line read is empty
* If not empty, then it splits the input strings into an array of strings and keeps count of total
* character count between all input strings
*
*/
private void loadStates(){
//check to see if line is empty
if(firstLine.isEmpty())
System.out.println("Error!");
else{
initInput = firstLine.split(" ");
int count = 0;
for(String input: initInput){
totalStates += input.length();
char[] temp = input.toCharArray();
//for each character, add unique ones to alphabet list
//also map
for(char state: temp){
if(!(actualAlphabet.contains(state)))
actualAlphabet.add(state);
if(!(internalAlphabet.containsKey(state))){
internalAlphabet.put(state, count);
count++;
}
}
}
}
}
}
<file_sep>/src/FileInput.java
/**
* Created by Andy on 2/13/18.
* This class is responsible for reading input from the file and passing along necessary information to
* NFSA class for Automata construction
* Most parsing is done by NFSA class
*/
import java.io.FileNotFoundException;
import java.util.*;
import java.io.*;
public class FileInput {
//declare appropriate data types for loading information from file to be passed to FSA
private static final String ALPHABET = "a b c d e f g h i j k l m n o p q r s t u v w x y z";
private String inputPath = "MachineInput.txt";
private String currentLine, initialRead, testLine;
private ArrayList<String> testStrings = new ArrayList<>();
/**
* Class constructor calls {@link #readFile() readFile} to begin file reading
*/
public FileInput() throws IOException{
readFile();
}
/**
* This method is responsible for reading from the file
* @throws IOException if file can't be read from
*/
private void readFile() throws IOException{
//iteration count of machine
int counter= 1;
currentLine=" ";
boolean exit = false;
initialRead = "";
try{
FileReader file = new FileReader(inputPath);
BufferedReader read = new BufferedReader(file);
//while currentLine is not empty
while(!exit && !(currentLine.isEmpty())){
//read current line
currentLine = read.readLine();
//if '*' then new FSA machine
if(("***").equals(currentLine)){
//Read appropriate information and parse when needed
initialRead = read.readLine();
testLine = read.readLine();
testStrings = getTesters();
//Pass on info to FSA
NFSA nfa = new NFSA(initialRead, testStrings, counter);
testStrings.clear();
counter++;
}
if(currentLine==null)
exit = true;
}
System.out.println("Done!");
read.close();
}
catch (FileNotFoundException e){
System.out.println("Can't open file.");
}
catch (IOException i){
System.out.println("Can't read file.");
}
}
/**
* This method parses the line with the test strings from the input file into an array list
* @return ArrayList populated with individual test strings
*/
private ArrayList<String> getTesters(){
String[] temp = testLine.split(" ");
for(String var : temp){
testStrings.add(var);
}
return testStrings;
}
}
| ec7caed282f325cae944babd657e12bcf848c1bf | [
"Java",
"Text"
]
| 3 | Text | ohheythereandy/CS311Project2 | d6135c6a5f57770fd24a7e4e863a7b91f40b01c8 | f293d3629a4bfc96227f8f1d69a48054f28ecde4 |
refs/heads/main | <file_sep>#pragma once
#include <iostream>
using namespace std;
class myString
{
private:
int len;
char* str;
void setString(const char* s);
public:
char* getString()const { return str; }
myString(const char* s);//constructor
myString(const myString& ms); //copy constructor
~myString(); //destructor
myString insert(int index, const char* str);
myString operator=(const myString& s)const;
bool operator< (const myString&)const;
bool operator> (const myString&)const;
bool operator<= (const myString&)const;
bool operator>= (const myString&)const;
bool operator!= (const myString&)const;
char& operator[](int index);
void print() const;
void eqtingBigSmall();
};
<file_sep>/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <cstring>
#include <string>
#pragma warning (disable: 4996)
#include "myString.h"
using namespace std;
int main()
{
//cout << "enter 2 words\n";
int n = 0,index;
char a1[50], b1[50], tav;
cin >> a1;
//cout << endl;
cin >> b1;
//cout << endl;
//cout<<"enter an index\n";
cin >> n;
myString a(a1), b(b1);
if (a > b)
cout << "a>b" << endl;
else
{
if (a < b)
cout << "a<b" << endl;
else
cout << "a=b" << endl;
}
//if (n > strlen(a1))
//{
// cout << "ERROR\n";
//for (int i = 0; i < strlen(a1); i++)
// *(a1 + i) = 0;
//*a1 = NULL;
//}
myString NewString = a.insert(n, b.getString());
NewString.print();
cin >> tav >> index;
NewString[index] = tav;
NewString.print();
return 0;
}
<file_sep>#include <cstring>
#include <string>
#pragma warning (disable: 4996)
#include "myString.h"
#include <iostream>
#include<cstdlib>
using namespace std;
myString::myString(const char* s)
{
setString(s);
}
void myString::setString(const char* s)
{
if (s)
{
len = strlen(s);
str = new char[len+1];
strcpy(str, s);
}
else
{
str = NULL;
len =0;
}
}
myString::myString(const myString& ms)
{
setString(ms.getString());
}
myString::~myString()
{
if (str)
delete[] str;
str = NULL;
len = 0;
}
myString myString::insert(int index, const char* str)
{
if (index < 0 || strlen(this->str) < index)
{
cout << "ERROR\n";
myString NewString(NULL);
return NewString;//i think i have an issue here
}
int newLen = strlen(this->str) + strlen(str);
char* temp=new char[newLen+1];
int i;
for (i = 0; i < index; i++)
temp[i] = str[i]; // the string 'b'
for (int j = 0; j < strlen(this->str);j++,i++)
temp[i] = this->str[j]; // The string 'a'
for (int k = index; k < strlen(this->str); k++, i++)
temp[i] = str[k];
temp[i] = '\0';
//delete[]this->str;
//this->str = temp;
myString NewStr(temp);
return NewStr;
}
bool myString::operator>(const myString& ms) const
{
myString New_a = *this;
myString New_b = ms;
New_a.eqtingBigSmall();
New_b.eqtingBigSmall();
if (strcmp(New_a.str, New_b.str) > 0)
return true;
return false;
}
bool myString::operator<(const myString& ms) const
{
myString New_a = *this;
myString New_b = ms;
New_a.eqtingBigSmall();
New_b.eqtingBigSmall();
if (strcmp(New_a.str, New_b.str) <0)
return true;
return false;
}
bool myString::operator>=(const myString& ms) const
{
myString New_a = *this;
myString New_b = ms;
New_a.eqtingBigSmall();
New_b.eqtingBigSmall();
if (strcmp(New_a.str, New_b.str) >= 0||strcmp(New_a.str, New_b.str)==0)
return true;
return false;
}
bool myString::operator<=(const myString& ms) const
{
myString New_a = *this;
myString New_b = ms;
New_a.eqtingBigSmall();
New_b.eqtingBigSmall();
if (strcmp(New_a.str, New_b.str) < 0 || strcmp(New_a.str, New_b.str)==0)
return true;
return false;
}
bool myString::operator!=(const myString& ms) const
{
myString New_a = *this;
myString New_b = ms;
New_a.eqtingBigSmall();
New_b.eqtingBigSmall();
if (strcmp(New_a.str, New_b.str) == 0)
return false;
return true;
}
char& myString::operator[](int index)
{
if(index >=0 && index < len)
return this->str[index];
cout << "ERROR" << endl;
exit(-1);
}
void myString::print() const
{
if (str!=NULL)
cout << str << endl;
}
void myString::eqtingBigSmall()
{
for (int i = 0; this->getString()[i]; i++)
{
if (this->getString()[i] > 65 && this->getString()[i] < 91)
this->getString()[i] += 32;
}
}
| 2af6d791b4f87f60c4be2e0c528ead46226f2f80 | [
"C++"
]
| 3 | C++ | shifrawexler/shifra | 87e1c43e141ee565aeee98b055d1f1208c95fc61 | af0a0d4a5d8cc2374a03a70909944d39db0dba66 |
refs/heads/master | <repo_name>Jorge-Mendoza/-IPC1-Proyecto2_201603184<file_sep>/Proyecto2/src/Habitacion.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author jorgi
*/
public class Habitacion {
int codHotel;
int noHabitacion;
int codReserv;
int cantPersonas;
int costo;
String clase;
Habitacion siguiente;
public Habitacion(){
codHotel=0;
noHabitacion=0;
codReserv=0;
cantPersonas=0;
costo=0;
clase=" ";
siguiente=null;
}
public int getCodHotel() {
return codHotel;
}
public void setCodHotel(int codHotel) {
this.codHotel = codHotel;
}
public int getNoHabitacion() {
return noHabitacion;
}
public void setNoHabitacion(int noHabitacion) {
this.noHabitacion = noHabitacion;
}
public int getCodReserv() {
return codReserv;
}
public void setCodReserv(int codReserv) {
this.codReserv = codReserv;
}
public int getCantPersonas() {
return cantPersonas;
}
public void setCantPersonas(int cantPersonas) {
this.cantPersonas = cantPersonas;
}
public int getCosto() {
return costo;
}
public void setCosto(int costo) {
this.costo = costo;
}
public String getClase() {
return clase;
}
public void setClase(String clase) {
this.clase = clase;
}
}
<file_sep>/Proyecto2/src/EntidadFinanciera.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author jorgi
*/
public class EntidadFinanciera {
int codEntidad;
int Dpi;
String tipo;
int codTarjeta;
int monto;
int maximo;
EntidadFinanciera siguiente;
public EntidadFinanciera(){
codEntidad=0;
Dpi=0;
tipo=" ";
codTarjeta=0;
monto=0;
maximo=0;
siguiente=null;
}
public int getCodEntidad() {
return codEntidad;
}
public void setCodEntidad(int codEntidad) {
this.codEntidad = codEntidad;
}
public int getDpi() {
return Dpi;
}
public void setDpi(int Dpi) {
this.Dpi = Dpi;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public int getCodTarjeta() {
return codTarjeta;
}
public void setCodTarjeta(int codTarjeta) {
this.codTarjeta = codTarjeta;
}
public int getMonto() {
return monto;
}
public void setMonto(int monto) {
this.monto = monto;
}
public int getMaximo() {
return maximo;
}
public void setMaximo(int maximo) {
this.maximo = maximo;
}
}
<file_sep>/Proyecto2/src/Clientes.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author jorgi
*/
public class Clientes {
int Dpi;
String nombres;
String apellidos;
int noTarjeta;
String fechaNac;
int numTel;
int numMov;
String direccion;
String frecuencia;
String monto;
Clientes siguiente;
public Clientes(){
Dpi=0;
nombres=" ";
apellidos=" ";
noTarjeta=0;
fechaNac=" ";
numTel=0;
numMov=0;
direccion=" ";
frecuencia="Anual";
monto=" ";
siguiente=null;
}
public int getDpi() {
return Dpi;
}
public void setDpi(int Dpi) {
this.Dpi = Dpi;
}
public String getNombres() {
return nombres;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public int getNoTarjeta() {
return noTarjeta;
}
public void setNoTarjeta(int noTarjeta) {
this.noTarjeta = noTarjeta;
}
public String getFechaNac() {
return fechaNac;
}
public void setFechaNac(String fechaNac) {
this.fechaNac = fechaNac;
}
public int getNumTel() {
return numTel;
}
public void setNumTel(int numTel) {
this.numTel = numTel;
}
public int getNumMov() {
return numMov;
}
public void setNumMov(int numMov) {
this.numMov = numMov;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getFrecuencia() {
return frecuencia;
}
public void setFrecuencia(String frecuencia) {
this.frecuencia = frecuencia;
}
public String getMonto() {
return monto;
}
public void setMonto(String monto) {
this.monto = monto;
}
}
<file_sep>/README.md
# -IPC1-Proyecto2_201603184
Proyecto 2 de IPC1
<file_sep>/Proyecto2/src/ListaReservacion.java
import java.io.*;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author jorge
*/
public class ListaReservacion {
static String aux=" ";
public String Leer(){
File f=null;
FileReader fr=null;
BufferedReader br=null;
try{
f = new File("C:\\Users\\jorgi\\Desktop\\ArchivosCSVPrueba - copia\\09 Reservaciones.csv");
fr=new FileReader(f);
br=new BufferedReader(fr);
String linea="hola";
linea=br.readLine();
while((linea=br.readLine())!=null){
System.out.println(linea);
aux= aux+"\n"+linea;
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
fr.close();
}catch(Exception e2){
e2.printStackTrace();
}
}
return aux;
}
public Reservacion Ver(String a){
Reservacion obj=new Reservacion();
String cadena[]=a.split(",");
obj.codReserv=Integer.parseInt(cadena[0]);
obj.codPaquete=Integer.parseInt(cadena[1]);
obj.Dpi=Integer.parseInt(cadena[2]);
obj.fReserv=cadena[3];
obj.fSalida=cadena[4];
obj.cantDias=Integer.parseInt(cadena[5]);
obj.estado=cadena[6];
obj.Saldo=Integer.parseInt(cadena[7]);
System.out.println("Reservacion no. "+obj.codReserv);
return obj;
}
static String atributos;
public void Separar(){
String reservaciones[]=aux.split("\n");
for(int i=1;i<reservaciones.length;i++){
System.out.println(reservaciones[i]+" y "+i);
StringBuffer l=new StringBuffer();
l=l.append(reservaciones[i]);
atributos=l.toString();
Enlistar(Ver(atributos));
System.out.println(atributos +" Y esto?");
}
}
public void Enlistar(Reservacion e){
e.siguiente=primero;
primero=e;
System.out.println("Esta es una prueba de que enlisté la reservacion: "+primero.codReserv+" y la "+primero.siguiente.codReserv);
}
public void Correr(){
Leer();
Separar();
System.out.println(atributos);
}
Reservacion primero;
public ListaReservacion(){
primero=new Reservacion();
}
}
<file_sep>/Proyecto2/src/Destino.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author jorgi
*/
public class Destino {
int codDestino;
String pais;
String ciudad;
String direccion;
String nombreDes;
String descripcion;
String seguridad;
Destino siguiente;
public Destino(){
siguiente=null;
codDestino=0;
pais=" ";
ciudad=" ";
direccion=" ";
nombreDes=" ";
descripcion=" ";
seguridad=" ";
}
public int getCodDestino() {
return codDestino;
}
public void setCodDestino(int codDestino) {
this.codDestino = codDestino;
}
public String getPais() {
return pais;
}
public void setPais(String pais) {
this.pais = pais;
}
public String getCiudad() {
return ciudad;
}
public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getNombreDes() {
return nombreDes;
}
public void setNombreDes(String nombreDes) {
this.nombreDes = nombreDes;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getSeguridad() {
return seguridad;
}
public void setSeguridad(String seguridad) {
this.seguridad = seguridad;
}
}
| ed605e75ae3f83bd34f62d96533cacc2a69b62ea | [
"Markdown",
"Java"
]
| 6 | Java | Jorge-Mendoza/-IPC1-Proyecto2_201603184 | 53fd2d37cf35a007cab3f28ab611fe9dd669f7e9 | af2aa1d9d33b2b637170ce4454cb97fe02a8b086 |
refs/heads/main | <repo_name>qq2457480027/springboot_supermarket<file_sep>/springboot_supermarket/src/main/java/com/hc/springboot/controller/SupplierinfoController.java
package com.hc.springboot.controller;
import com.hc.springboot.pojo.Supplierinfo;
import com.hc.springboot.service.SupplierinfoService;
import com.hc.springboot.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* <p>
* 前端控制器
* </p>
*
* @author vicente
* @since 2020-09-22
*/
@Controller
@RequestMapping("/supplierinfo")
public class SupplierinfoController {
@Autowired
SupplierinfoService supplierinfoService;
private PrintWriter out;
private boolean flag = false;
@GetMapping("/supplierinfos")
public String list(Model model, Supplierinfo supplierinfo, Page page){
if (page.getPageSize()==null || page.getPageSize()==0){
page.setPageSize(5);
}
page.setParam(supplierinfo);
model.addAttribute("suppPage",supplierinfoService.findSupplierinfoPage(page));
return "providerAdmin";
}
@GetMapping("/supp")
public String addPage(){
return "providerAdd";
}
@PostMapping("/supplierinfo")
@ResponseBody
public void add(Supplierinfo supplierinfo, HttpServletResponse response) throws IOException {
out = response.getWriter();
flag = supplierinfoService.save(supplierinfo);
if (flag) {
out.print(1);
} else {
out.print(0);
}
}
@GetMapping("/supplierinfo/{id}")
public String updatePage(Model model,@PathVariable("id") Integer id){
model.addAttribute("supp",supplierinfoService.getById(id));
return "providerModify";
}
@PutMapping("/supplierinfo")
@ResponseBody
public void update(Supplierinfo supplierinfo, HttpServletResponse response) throws IOException {
out = response.getWriter();
flag = supplierinfoService.updateById(supplierinfo);
if (flag) {
out.print(1);
} else {
out.print(0);
}
}
@DeleteMapping("/supplierinfo")
@ResponseBody
public void delete(Integer id, HttpServletResponse response) throws IOException {
out = response.getWriter();
flag = supplierinfoService.removeById(id);
if (flag) {
out.print(1);
} else {
out.print(0);
}
}
}
<file_sep>/springboot_supermarket/src/main/java/com/hc/springboot/pojo/Billinfo.java
package com.hc.springboot.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author vicente
* @since 2020-09-22
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Billinfo extends Model<Billinfo> {
private static final long serialVersionUID = 1L;
/**
* 账单id
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 商品名称
*/
@TableField("comName")
private String comName;
/**
* 商品描述
*/
@TableField("comDescribe")
private String comDescribe;
/**
* 账单时间
*/
@TableField("billDate")
private Date billDate;
/**
* 供应商编号
*/
@TableField("supId")
private Integer supId;
/**
* 是否付款
*/
private Integer payment;
/**
* 账单报价
*/
@TableField("billOffer")
private Double billOffer;
/**
* 商品数量
*/
@TableField("comQuantity")
private Integer comQuantity;
@Override
protected Serializable pkVal() {
return this.id;
}
}
<file_sep>/springboot_supermarket/src/test/java/com/hc/springboot/SpringbootSupermarketApplicationTests.java
package com.hc.springboot;
import com.hc.springboot.pojo.Userinfo;
import com.hc.springboot.service.UserinfoService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootSupermarketApplicationTests {
@Autowired
UserinfoService userinfoService;
@Test
void contextLoads() {
System.out.println(userinfoService.getById(13));
}
}
<file_sep>/springboot_supermarket/src/main/java/com/hc/springboot/service/BillinfoService.java
package com.hc.springboot.service;
import com.hc.springboot.pojo.Billinfo;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hc.springboot.pojo.vo.BillinfoImplVO;
import com.hc.springboot.util.Page;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author vicente
* @since 2020-09-22
*/
public interface BillinfoService extends IService<Billinfo> {
/**
* 分页查询
* @param page
* @return
*/
Page findBillinfoPage(Page page);
/**
* 新增供应商
* @param billinfo
* @return
*/
int addBillinfo(Billinfo billinfo);
/**
* 修改供应商
* @param billinfo
* @return
*/
int modifyBillinfo(Billinfo billinfo);
}
<file_sep>/springboot_supermarket/src/main/java/com/hc/springboot/controller/BillinfoController.java
package com.hc.springboot.controller;
import com.hc.springboot.pojo.Billinfo;
import com.hc.springboot.service.BillinfoService;
import com.hc.springboot.service.SupplierinfoService;
import com.hc.springboot.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
/**
* <p>
* 前端控制器
* </p>
*
* @author vicente
* @since 2020-09-22
*/
@Controller
@RequestMapping("/billinfo")
public class BillinfoController {
@Autowired
BillinfoService billinfoService;
@Autowired
SupplierinfoService supplierinfoService;
private PrintWriter out;
private int result = 0;
@GetMapping("/billinfos")
public String list(Model model, Billinfo billinfo, Page page){
if (page.getPageSize()==null || page.getPageSize()==0){
page.setPageSize(5);
}
page.setParam(billinfo);
model.addAttribute("billPage",billinfoService.findBillinfoPage(page));
return "admin_bill_list";
}
@GetMapping("/bill")
public String addPage(Model model){
model.addAttribute("suppliers",supplierinfoService.list());
return "add";
}
@PostMapping("/billinfo")
@ResponseBody
public void add(Billinfo billinfo, HttpServletResponse response) throws IOException {
out = response.getWriter();
billinfo.setBillDate(new Date());
result = billinfoService.addBillinfo(billinfo);
if (result > 0) {
out.print(1);
} else {
out.print(0);
}
}
@GetMapping("/billinfo/{id}")
public String updatePage(Model model,@PathVariable("id") Integer id){
model.addAttribute("bill",billinfoService.getById(id));
model.addAttribute("suppliers",supplierinfoService.list());
return "modify";
}
@PutMapping("/billinfo")
@ResponseBody
public void update(Billinfo billinfo, HttpServletResponse response) throws IOException {
out = response.getWriter();
result = billinfoService.modifyBillinfo(billinfo);
if (result > 0) {
out.print(1);
} else {
out.print(0);
}
}
@DeleteMapping("/billinfo")
@ResponseBody
public void delete(Integer id, HttpServletResponse response) throws IOException {
out = response.getWriter();
boolean flag = billinfoService.removeById(id);
if (flag) {
out.print(1);
} else {
out.print(0);
}
}
}
<file_sep>/springboot_supermarket/src/main/java/com/hc/springboot/pojo/Supplierinfo.java
package com.hc.springboot.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author vicente
* @since 2020-09-22
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Supplierinfo extends Model<Supplierinfo> {
private static final long serialVersionUID = 1L;
/**
* 供应商id
*/
@TableId(value = "supId", type = IdType.AUTO)
private Integer supId;
/**
* 供应商名称
*/
@TableField("supName")
private String supName;
/**
* 供应商简介
*/
@TableField("supIntro")
private String supIntro;
/**
* 供应商联系人
*/
@TableField("supContacts")
private String supContacts;
/**
* 供应商联系电话
*/
@TableField("supPhone")
private String supPhone;
/**
* 供应商地址
*/
@TableField("supSite")
private String supSite;
/**
* 供应商传真
*/
@TableField("supFax")
private String supFax;
@Override
protected Serializable pkVal() {
return this.supId;
}
}
<file_sep>/springboot_supermarket/src/main/java/com/hc/springboot/service/impl/BillinfoServiceImpl.java
package com.hc.springboot.service.impl;
import com.hc.springboot.pojo.Billinfo;
import com.hc.springboot.mapper.BillinfoMapper;
import com.hc.springboot.service.BillinfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hc.springboot.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* 服务实现类
* </p>
*
* @author vicente
* @since 2020-09-22
*/
@Service
public class BillinfoServiceImpl extends ServiceImpl<BillinfoMapper, Billinfo> implements BillinfoService {
@Autowired
BillinfoMapper billinfoMapper;
/**
* 分页查询
*
* @param page
* @return
*/
@Override
public Page findBillinfoPage(Page page) {
page.setTotalCount(billinfoMapper.totalCount(page));
Map<String,Object> map = new HashMap<>();
map.put("currentPageNo",(page.getCurrentPageNo()-1)*page.getPageSize());
page.setParamMap(map);
page.setList(billinfoMapper.searchBillinfoPage(page));
return page;
}
/**
* 新增账单
*
* @param billinfo
* @return
*/
@Override
public int addBillinfo(Billinfo billinfo) {
return billinfoMapper.insertBillinfo(billinfo);
}
/**
* 修改账单
*
* @param billinfo
* @return
*/
@Override
public int modifyBillinfo(Billinfo billinfo) {
return billinfoMapper.updateBillinfo(billinfo);
}
}
<file_sep>/springboot_supermarket/src/main/java/com/hc/springboot/service/impl/UserinfoServiceImpl.java
package com.hc.springboot.service.impl;
import com.hc.springboot.pojo.Userinfo;
import com.hc.springboot.mapper.UserinfoMapper;
import com.hc.springboot.service.UserinfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hc.springboot.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* 服务实现类
* </p>
*
* @author vicente
* @since 2020-09-22
*/
@Service
public class UserinfoServiceImpl extends ServiceImpl<UserinfoMapper, Userinfo> implements UserinfoService {
@Autowired
UserinfoMapper userinfoMapper;
/**
* 用户登录
*
* @param userinfo
* @return
*/
@Override
public Userinfo login(Userinfo userinfo) {
return userinfoMapper.searchUserinfoByUserNameAndUserPwd(userinfo);
}
/**
* 分页查询
*
* @param page
* @return
*/
@Override
public Page findUserinfoPage(Page page) {
page.setTotalCount(userinfoMapper.totalCount(page));
Map<String,Object> map = new HashMap<>();
map.put("currentPageNo",(page.getCurrentPageNo()-1)*page.getPageSize());
page.setParamMap(map);
page.setList(userinfoMapper.searchUserinfoPage(page));
return page;
}
/**
* 修改用户信息
*
* @param userinfo
* @return
*/
@Override
public int modifyUserinfo(Userinfo userinfo) {
return userinfoMapper.updateUserinfo(userinfo);
}
}
| 355d3edc51d79871a256ad25a9012e99db5f8d5c | [
"Java"
]
| 8 | Java | qq2457480027/springboot_supermarket | 7f89a5f2f329f68ea23e9e57c650f9b5fe8c2978 | e4a95a1fe59b65cac47126a308dd7559560fbc6b |
refs/heads/master | <file_sep>let questions = prompt("Ваше отношение к технике Apple"),
body = document.querySelector("body"),
header = document.getElementsByTagName("header"),
column = document.getElementsByClassName("column"),
adv = document.querySelector(".adv"),
promt = document.getElementById("prompt"),
title = document.getElementById("title"),
ul = document.querySelector(".menu"),
it = document.getElementsByTagName("li"),
li = document.createElement("li"),
litext = document.createTextNode("Пятый пункт");
body.style.backgroundImage = "url(./img/apple_true.jpg)";
li.classList.add("menu-item");
ul.appendChild(li);
li.appendChild(litext);
ul.insertBefore(it[2], it[1]);
column[1].removeChild(adv);
title.innerHTML = "Мы продаем только подлинную технику Apple";
promt.innerHTML = questions;
console.log(questions);
console.log(li); | b7fb3ec3e686c1b4a6a54525f20f161662851069 | [
"JavaScript"
]
| 1 | JavaScript | AlexeyRuchkin/JavaScript | d7bf3ef19f0084f642e77ba10e4c137101465b9f | 70f190cb30eea69b65c232c45c2f5705d88c5476 |
refs/heads/master | <file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tv.sonis.lobber;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Rectangle2D;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
/**
*
* @author skaviouz
*/
public class LobberLauncherPanel extends JPanel implements MouseListener, MouseMotionListener {
private Graphics2D g2d;
private String state = "";
private int x, y;
public boolean ViewGraph = true;
public JTabbedPane MainTab = new JTabbedPane();
public JPanel About, How, Version, Values, Ref;
public LobberLauncherPanel() {
super(new GridBagLayout(), true);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
private void initComponents() {
addMouseMotionListener(this);
addMouseListener(this);
MainTab.add("asdfasdf", new JPanel());
setVisible(true);
}
//@Override
public void paintComponent(Graphics g) {
if (ViewGraph) {
super.paintComponent(g);
return;
}
g2d = (Graphics2D) g;
int y = getHeight();
int x = getWidth();
Graphics2D g2d = (Graphics2D) g.create();
LobberGraphics:
{
Shape cirzzz;
//cirzzz = Ellipse2D.Double(x/2, y/2, 60, 120);
g2d.setColor(Color.red);
g2d.drawOval(x / 2, y / 2, 40, 60);
}
testString:
{
g2d.setColor(Color.red);
g2d.drawString("Hello", 50, 50);
}
box:
{
g2d.setColor(Color.red);
Rectangle2D r2d = new Rectangle2D.Double(15, 5, x - 25, y - 25);
g2d.draw(r2d);
}
copyrigbht:
{
g2d.setColor(new Color(0, 0, 0, 90));
g2d.drawRect(x - 96, y - 21, 93, 12);
g2d.drawString("\u00a9" + " Skaviouz 2009", x - 95, y - 10);
if (!state.equals("")) {
g2d.drawString("STATE: " + state, 5, 25);
}
}
g2d.dispose();
}
public void setState(String state) {
this.state = state;
}
public String getState() {
return state;
}
public void setX(int x) {
this.x = x;
repaint();
}
public void setY(int y) {
this.y = y;
repaint();
}
//MouseMotionListener
/*
* M/C + M MOVE
*/
@Override
public void mouseDragged(MouseEvent e) {
}
/*
* M MOVE
*/
@Override
public void mouseMoved(MouseEvent e) {
}
//MouseListener
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
<file_sep>package tv.sonis.lobber;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import tv.sonis.lobber.graphics.LobberCanvas;
/**
* Simple Application (JFrame)
*
* @author skaviouz
*/
public class LobberToolApplication extends javax.swing.JFrame {
public LobberToolApplication() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
BackgroundPanel = new javax.swing.JPanel();
canvas2 = new LobberCanvas(this);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
canvas2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
canvas2MouseClicked(evt);
}
});
canvas2.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
canvas2ComponentResized(evt);
}
});
//BackgroundPanel.add(getCanvas());
javax.swing.GroupLayout BackgroundPanelLayout = new javax.swing.GroupLayout(BackgroundPanel);
BackgroundPanel.setLayout(BackgroundPanelLayout);
BackgroundPanelLayout.setHorizontalGroup(
BackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 669, Short.MAX_VALUE)
.addGroup(BackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(canvas2, javax.swing.GroupLayout.DEFAULT_SIZE, 669, Short.MAX_VALUE))
);
BackgroundPanelLayout.setVerticalGroup(
BackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 433, Short.MAX_VALUE)
.addGroup(BackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(canvas2, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(BackgroundPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(BackgroundPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
public AboutDialogBox Aboutdialog = new AboutDialogBox(this, true) {
{
setVisible(true);
}
};
private void canvas2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_canvas2MouseClicked
if (evt.getButton() == 3) {
Aboutdialog.setVisible(true);
}
canvas2.repaint();
}//GEN-LAST:event_canvas2MouseClicked
private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
canvas2.repaint();
}//GEN-LAST:event_formKeyPressed
private void canvas2ComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_canvas2ComponentResized
((LobberCanvas) canvas2).resized();
}//GEN-LAST:event_canvas2ComponentResized
private void AboutJMenuItemActionPerformed2(java.awt.event.ActionEvent evt) {
AboutDialogBox Aboutdialog = new AboutDialogBox(this, true);
Aboutdialog.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LobberToolApplication().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel BackgroundPanel;
public java.awt.Canvas canvas2;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tv.sonis.lobber;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import tv.sonis.lobber.util.Constants;
import static tv.sonis.lobber.util.Constants.d2i;
import static tv.sonis.lobber.util.Constants.random;
/**
* LobberJFrame
*
* @author skaviouz
*/
public class LFrame extends JFrame {
public LCanvas jlp;
public LFrame(String str) {
super(str);
settings:
{
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Titlebar
setTitle(Constants.getTitle());
setIconImage(new ImageIcon("./resources/images/icon32_S.png").getImage());
}
Content:
{
jlp = new LCanvas();
setContentPane(jlp);
}
setScreenLocationInfo:
{
setLocationByPlatform(true);
setVisible(true);
}
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tv.sonis.lobber;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
/**
* new LobberApp() runs LFrame in swing thread
*
* @author skaviouz
*/
public class LobberApp {
public static LFrame gui;
/*
* Program starts here
*/
public static void main(String[] args) {
new LobberApp();
}
/*
* Program starts GUI
*/
public LobberApp() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
gui = new LFrame("Swing Paint Demo");
}
});
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tv.sonis.lobber.util;
import lombok.*;
import lombok.experimental.*;
/**
*
* @author Blitz
*/
@Getter @Setter @Accessors(chain = true)
public class Person {
public String Name = "";
public String Special = "";
public String Thanks = "";
public Person(String str){
Name = str;
}
}
<file_sep>package tv.sonis.lobber.util;
import java.awt.Point;
/**
* File that contains all the math functions
* @author skaviouz
*/
public class geometry {
/**
* returns a point for a hypothetical line starting at X,Y with Length of
* X/Y not to exceed MaxX/MaxY the point has an azimuth from the starting
* X,Y at DegreeAngle
*
* @param StartX
* @param StartY
* @param MaxX
* @param MaxY
* @param DegreeAngle
* @return
*/
public static int[] AzimuthLineBox(double StartX, double StartY, double MaxX, double MaxY, double DegreeAngle) {
double CorrectDegreeAngle = (DegreeAngle + 270) % 360;
double RadianAngle = CorrectDegreeAngle * Math.PI / 180;
double RadiusX = Math.abs(MaxX - StartX);
double RadiusY = Math.abs(MaxY - StartY);
double DestX = StartX + (RadiusX * Math.cos(RadianAngle));
double DestY = StartY + (RadiusY * Math.sin(RadianAngle));
return new int[]{(int)DestX, (int)DestY};
}
}
<file_sep>lobber
======

This program takes azimuth inputs and outputs graphical representations.
Programmer :
* <NAME> (Skaviouz)
From the inspiration of :
* <NAME>
Honorably mentioned :
* <NAME>
* <NAME>
This framework uses:
* SUN JNA
* lombok 0.11.8
* jspf 1.0.2
To run the application via pre-build example :
* https://codeload.github.com/skaviouz/lobber/zip/master (zip)
* https://github.com/skaviouz/lobber.git (git)
How to run: (multiple choice)
* open the zip and find ./lobber/dist/run.bat
* in windows7 run 'cmd' (control prompt)
- type 'cd c:/aProject/lobber/dist/run.bat' given if you extract zip to 'c:/aProject/lobber'
- type 'java -Dsun.java2d.noddraw=true -jar lobber.jar tv.sonis.lobber.LobberToolApplication
Netbeans:
- Working Dir : C:\aProject\lobber\bin
- VM Options : -Dsun.java2d.noddraw=true
Notes:
- add libraries to cp not the directory of jars.
Special Thanks to webpages:
- <NAME> - http://www.javacodegeeks.com/2012/09/transparent-jframe-using-jna.html
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tv.sonis.lobber.util;
import tv.sonis.lobber.*;
/**
* calls itself directly
* @author skaviouz
*/
public class lobberstatics {
public static LobberLauncherPanel lobapp = null;
}
| 1744d00ddf86e79dc3cae26bac7b65eaa2fb47c7 | [
"Markdown",
"Java"
]
| 8 | Java | skaviouz/lobber | 3670117408428047be5917fa6985e1a1c3c06b08 | da824d7069582ed095d69676dd759bec51cd2402 |
refs/heads/master | <file_sep>import React, { useRef, useEffect } from 'react';
import * as S from './styledComponents'
const Input = ({ userInput, updateInput, currentIndex,limit, setCurrentIndex,setIndexUpdated }) => {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
}, [inputRef])
useEffect(() => {
inputRef.current.setSelectionRange(currentIndex, currentIndex)
setIndexUpdated(true);
// eslint-disable-next-line
}, [currentIndex, userInput])
return (
<S.InputContainer>
{
userInput.split("").map((e, i) => {
return <S.OneChar isFocused={currentIndex === i } onClick={() => setCurrentIndex(i)} key={i}>{e}</S.OneChar>
})
}
<S.OneChar isFocused={currentIndex === userInput.length} hidden={userInput.length === limit} />
<S.HiddenInput
maxLength={limit}
ref={inputRef}
value={userInput}
onChange={({ target: { value } }) => {
updateInput('user_input', { value, index: inputRef.current.selectionStart })
}}
onKeyUp={({key}) => {
updateInput('user_keypress', { key, index: inputRef.current.selectionStart})
}}
onBlur={() => inputRef.current.focus()}
/>
</S.InputContainer>
);
}
export default Input;<file_sep>export let checkResponseStatus = (res) => {
if(res.ok){
return res;
}else{
throw Error(res.statusText)
}
}
export let getErrorMessage = (error) =>{
switch(error.message){
case 'Failed to fetch':
return "Couldn't connect!"
case 'Not Found':
return 'Not found!'
default :
return 'Something went wrong!'
}
}<file_sep>import React from 'react'
import Form from './Form/Form'
let SearchBox = ({ setQuery }) => {
let onFormSubmit = (e, userInput) => {
e.preventDefault()
let parsed = userInput.trim();
if(parsed)
setQuery(parsed)
}
return (
<Form
onFormSubmit={onFormSubmit}
/>
)
}
export default SearchBox<file_sep>import React from 'react';
import * as S from './styledComponents'
let Spinner = (props) => {
return <S.Spinner {...props}/>
}
export default Spinner;<file_sep>export let sizes = {
}<file_sep>import styled,{ css} from 'styled-components'
// import pokeball from '../../../assets/images/pokeball.png'
export let Form = styled.form`
width:100vw;
height:300px;
margin-top:60px;
display:flex;
flex-direction:column;
align-items:center;
justify-content:space-around;
position:relative;
transition:all 0.5s ease-in-out;
@media only screen and (max-width:577px) {
width:80%;
padding:0;
flex:1;
}
`
export let FormHeader = styled.h1`
margin:0;
font-size:2.5rem;
text-align:center;
transition:margin-bottom 0.5s ease-in-out;
@media only screen and (max-width:577px) {
font-size:2.2rem;
line-height:50px;
}
span{
color:#F44336;
}
`
export let Submit = styled.button`
height:33px;
padding:10px 20px;
border:0;
display:flex;
align-items:center;
justify-content:center;
position:relative;
background:white;
font-family:inherit;
font-size:0.8rem;
cursor:pointer;
box-shadow:${defaultShadows()};
&::before{
left:0%;
transform:translate(-380%,-50%) rotate(180deg);
}
&::after{
right:0%;
transform:translate(380%,-50%) rotate(-180deg);
}
&:active{
padding-top:15px;
box-shadow:
${defaultShadows()},
inset 0px 5px 0 black;
}
`
function defaultShadows(){
return `
5px 0 black,
0 5px black,
-5px 0 black,
0 -5px black,
-5px 5px #ccc,
-5px -5px #ccc,
5px 5px #ccc,
5px -5px #ccc
`
}
<file_sep>import {keyframes} from 'styled-components'
let pixelArray = [
//top right bottom left (3 each + corner)
{ x: -1, y: -1, radiusFor: 'y' },
{ x: 0, y: -1, radiusFor: 'y' },
{ x: 1, y: -1, radiusFor: 'y' },
{ x: 2, y: -2, radiusFor: '' },
{ x: 1, y: -1, radiusFor: 'x' },
{ x: 1, y: 0, radiusFor: 'x' },
{ x: 1, y: 1, radiusFor: 'x' },
{ x: 2, y: 2, radiusFor: '' },
{ x: 1, y: 1, radiusFor: 'y' },
{ x: 0, y: 1, radiusFor: 'y' },
{ x: -1, y: 1, radiusFor: 'y' },
{ x: -2, y: 2, radiusFor: '' },
{ x: -1, y: 1, radiusFor: 'x' },
{ x: -1, y: 0, radiusFor: 'x' },
{ x: -1, y: -1, radiusFor: 'x' },
{ x: -2, y: -2, radiusFor: '' }
]
let getPixel = (size, radius, index, color) => {
let { x, y, radiusFor } = pixelArray[index % pixelArray.length];
if (radiusFor === 'y') {
return `${size * x}px ${size * (radius + 1) * y}px ${color}`;
} else if (radiusFor === 'x') {
return `${size * (radius + 1) * x}px ${size * y}px ${color}`;
} else {
return `${size * x}px ${size * y}px ${color}`;
}
}
let colors = new Array(4).fill('black').concat(new Array(12).fill('transparent'))
let createKeyframes = (size, radius) => {
let keyF = ''
for (let i = 0; i < 17; i++) {
keyF += `
${i * 100 / 16}%{
box-shadow:
${pixelArray.map((e, j) => {
return getPixel(size, radius, j, colors[(j + i) % colors.length])
})}
}
`
}
return keyframes`${keyF}`
}
export default createKeyframes;
<file_sep>import styled from 'styled-components'
export let SearchBox = styled.div`
@import url('https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap');
width:100vw;
height:400px;
display:flex;
flex-direction:column;
align-items:center;
justify-content:space-around;
font-family:'Press Start 2P';
font-size:2em;
h1{
margin:0;
text-align:center;
font-size:1em;
transition:margin-bottom 0.5s ease-in-out;
@media only screen and (max-width:577px) {
margin-bottom:150px;
line-height:50px;
}
span{
color:#F44336;
}
}
`<file_sep>import React, {useState} from 'react'
import SearchBox from './SearchBox/SearchBox';
import PokemonShowcase from './PokemonShowcase/PokemonShowcase'
import * as S from './styledComponents'
import {useFetch} from '../../logic/hooks'
const URL = 'http://127.0.0.1:8080/getPokemon';
const PARAMS = {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
}
let Main = () => {
let [query, setQuery] = useState(null)
let [pokemon,error,isLoading] = useFetch(URL,PARAMS,query)
return (
<S.Main>
<SearchBox setQuery={setQuery}/>
{
// pokemon && <PokemonShowcase pokemon={pokemon} />
<PokemonShowcase pokemon={pokemon} error={error} isLoading={isLoading}/>
}
</S.Main>
)
}
export default Main;<file_sep>import { createGlobalStyle } from 'styled-components'
export let GlobalStyle = createGlobalStyle`
@import url('https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap');
html{
height:100%;
font-family:'Press Start 2P';
}
body{
min-height:100%;
width:100vw;
margin:0;
padding:0;
box-sizing:border-box;
background:#fffafa ;
>*{
margin:0;
padding:0;
box-sizing:border-box;
}
#root{
min-height:100%;
height:100%;
width:100vw;
display:flex;
align-items:center;
justify-content:center;
}
}
`<file_sep>import styled from 'styled-components'
import createKeyframes from './createKeyframes'
export let Spinner = styled.div`
width:${props => props.size ? props.size : '8'}px;
height:${props => props.size ? props.size : '8'}px;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
animation:${props => createKeyframes(props.size,props.radius)} 1s linear infinite;
`
| f8762d7d7c47f2cce16c2b2d1c6cb0ba010de717 | [
"JavaScript"
]
| 11 | JavaScript | janKozie1/pokemon-lookup | e9a4835b9c1f617703d8af345db75989746bfe63 | a46af22651a33148e147fc88917b60abf0475607 |
refs/heads/master | <repo_name>datasci-study/sunyong<file_sep>/안양시 미세먼지 공모전/안양시 미세먼지 iot센서 공모전 관련 리포.md
안양시 미세먼지 iot센서 공모전 관련 리포<file_sep>/README.md
# sunyong
Repository for ML study
<file_sep>/알고리즘/10주차.py
'''
V개의 노드 개수와 방향성이 없는 E개의 간선 정보가 주어진다.
주어진 출발 노드에서 최소 몇 개의 간선을 지나면 도착 노드에 갈 수 있는지 알아내는 프로그램을 만드시오.
예를 들어 다음과 같은 그래프에서 1에서 6으로 가는 경우, 두 개의 간선을 지나면 되므로 2를 출력한다.
노드 번호는 1번부터 존재하며, 노드 중에는 간선으로 연결되지 않은 경우도 있을 수 있다.
[입력]
첫 줄에 테스트 케이스 개수 T가 주어진다. 1<=T<=50
다음 줄부터 테스트 케이스의 첫 줄에 V와 E가 주어진다. 5<=V=50, 4<=E<=1000
테스트케이스의 둘째 줄부터 E개의 줄에 걸쳐, 간선의 양쪽 노드 번호가 주어진다.
E개의 줄 이후에는 출발 노드 S와 도착 노드 G가 주어진다.
입력
3
6 5
1 4
1 3
2 3
2 5
4 6
1 6
7 4
1 6
2 3
2 6
3 5
1 5
9 9
2 6
4 7
5 7
1 5
2 9
3 9
4 8
5 3
7 8
1 9'''
#BFS 함수
def bfs(queue):
count = 1
#큐가 빌때까지 반복
while queue:
#2개의 큐가 필요하므로 한개더 생성한다.
s_queue = []
#큐가 빌때까지 반복한다.
while queue:
#원소를 꺼내서
index = queue.pop()
#연결되어 있는 부분들을 확인한다.
for i in node[index]:
#이미 방문했다면 다른 index 확인한다
if visited[i]: continue
#도착지와 일치한다면 이동거리를 반환한다.
if i == end: return count
#위의 조건에 걸리지 않는다면 두번재 큐에 추가한다.
s_queue.append(i)
#방문처리를 한다.
visited[i] = 1
#모든 큐가 비었다면 카운트를 증가시킨다.
count += 1
#큐를 교체한다.
queue = s_queue
#여기까지 왔다면 목적지까지 도착할 수 없다.
return 0
T=int(input())
for test_case in range(1,T+1):
#V개의 노드, E개의 간선
V, E = map(int, input().split())
#리스트를 이용한 간선 표시
node = [[] for _ in range(V+1)]
#방문여부
visited = [0 for _ in range(V+1)]
#데이터 편집
for i in range(E):
a, b = map(int, input().split())
node[a].append(b)
node[b].append(a)
#시작노드와 끝나는 노드 저장
start, end = map(int, input().split())
#시작노드 방문처리
visited[start] = 1
#bfs 돌리기
print('#{} {}'.format(T, bfs([start]))) | 81526ea4f84cf947ec41157cce4a3f9e37a90ada | [
"Markdown",
"Python"
]
| 3 | Markdown | datasci-study/sunyong | be5dbc81d943b5103f344199723082cc62cacd96 | 3bf91c0d32334138d40aab04208a2f6e28cae8cb |
refs/heads/master | <file_sep>//Filename: app.js
define([
'jquery', // lib/jquery/jquery
'underscore'// lib/underscore/underscore
], function($, _){
function init() {
alert('initialization');
}
return {
initialize: init
};
});<file_sep>require.config({
paths: {
jquery: 'libraries/jquery/jquery',
underscore: 'libraries/underscore/underscore'
//backbone: 'libraries/backbone/backbone',
//angular: 'libraries/backbone/angular'
}
});
require([
'app',
], function(App){
App.initialize();
});<file_sep># BoilerPlate
THESE FILES ARE THE BOILER PLATES NEEDED FOR STARTING THE PROJECTS FOR BACKBONE OF ANGULAR FRAMEWORK PROJECTS
| 2aea4d0550f85090d7bb9f276d1f87be6b010f78 | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | poushy/BoilerPlate | 55b1b16b85221fa3d37b3c1673af06c45de8f26a | 213337bc230cae8e052ef333eb851570c99f9c58 |
refs/heads/master | <repo_name>DhimanDasgupta/CardRecylerPalette<file_sep>/app/src/main/java/com/dhimandasgupta/cardrecylerpalette/ui/fragments/MainFragment.java
package com.dhimandasgupta.cardrecylerpalette.ui.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.dhimandasgupta.cardrecylerpalette.R;
import com.dhimandasgupta.cardrecylerpalette.model.CardItemGenerator;
import com.dhimandasgupta.cardrecylerpalette.ui.adapters.CardAdapter;
/**
* Created by dhimandasgupta on 12/13/14.
*/
public class MainFragment extends Fragment {
private CardAdapter mCardAdapter;
public MainFragment() {
}
public static MainFragment newInstance() {
final MainFragment fragment = new MainFragment();
return fragment;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final RecyclerView recyclerView = (RecyclerView) view
.findViewById(R.id.fragment_main_recyler_view);
if (recyclerView != null) {
final int columnCount = view.getContext().getResources().getInteger(R.integer.column_count);
mCardAdapter = new CardAdapter(CardItemGenerator.getCardItems(), columnCount);
final GridLayoutManager layoutManager = new GridLayoutManager(
view.getContext(), columnCount, GridLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(mCardAdapter);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onDetach() {
super.onDetach();
}
}
<file_sep>/app/src/main/java/com/dhimandasgupta/cardrecylerpalette/ui/adapters/CardAdapter.java
package com.dhimandasgupta.cardrecylerpalette.ui.adapters;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.dhimandasgupta.cardrecylerpalette.R;
import com.dhimandasgupta.cardrecylerpalette.model.CardItem;
import com.dhimandasgupta.cardrecylerpalette.ui.views.SquareImageView;
import java.util.List;
/**
* Created by dhimandasgupta on 12/13/14.
*/
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {
private List<CardItem> mCardItems;
private int mColumns;
public CardAdapter(final List<CardItem> cardItems, final int columns) {
mCardItems = cardItems;
mColumns = columns;
}
@Override
public int getItemCount() {
return mCardItems.size();
}
@Override
public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final LayoutInflater inflater = LayoutInflater
.from(parent.getContext());
final View view = inflater.inflate(R.layout.adapter_card, parent, false);
final int itemWidth = (int) parent.getWidth() / mColumns;
final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(itemWidth, itemWidth);
view.setLayoutParams(params);
final CardViewHolder cardViewHolder = new CardViewHolder(view);
return cardViewHolder;
}
@Override
public void onBindViewHolder(final CardViewHolder holder, int position) {
holder.mImageView
.setImageResource(mCardItems.get(position).mDrawableResourceId);
holder.mTextView.setText(mCardItems.get(position).mItemName);
final BitmapDrawable bitmapDrawable = (BitmapDrawable) holder.mImageView.getDrawable();
Palette.generateAsync(bitmapDrawable.getBitmap(),
new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
final Palette.Swatch swatch = palette.getDarkMutedSwatch();
holder.mTextView.setBackgroundColor(swatch.getRgb());
holder.mTextView.setTextColor(swatch.getTitleTextColor());
}
});
}
public static class CardViewHolder extends RecyclerView.ViewHolder {
private SquareImageView mImageView;
private TextView mTextView;
public CardViewHolder(View itemView) {
super(itemView);
mImageView = (SquareImageView) itemView
.findViewById(R.id.adapter_card_square_image_view);
mTextView = (TextView) itemView
.findViewById(R.id.adapter_card_text_view);
}
@Override
public String toString() {
return mImageView.toString() + "X" + mTextView.toString();
}
}
}
| 671c2932d01ab23c2fa18c8ae9f978c0bdc4046e | [
"Java"
]
| 2 | Java | DhimanDasgupta/CardRecylerPalette | 45084bb69a4918054fe4e37d4591f50e047c51ba | ee3287303e225910e5fab686818fa9aa6af3a658 |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { EmployeeService } from '../shared/employee.services';
import { Router } from "@angular/router";
// @Component({
// selector: 'app-add-emp',
// templateUrl: './add-emp.component.html',
// styleUrls: ['./add-emp.component.css']
// })
@Component({
selector: 'app-employee-from',
templateUrl: './employee-from.component.html',
styleUrls: ['./employee-from.component.css']
})
export class EmployeeFromComponent implements OnInit {
empformlabel: string = 'Add Employee';
empformbtn: string = 'Save';
constructor(private formBuilder: FormBuilder, private router: Router, private empService: EmployeeService) {
}
addForm: FormGroup;
btnvisibility: boolean = true;
ngOnInit() {
this.addForm = this.formBuilder.group({
id: [],
employee_name: ['', Validators.required],
employee_salary: ['', [Validators.required, Validators.maxLength(9)]],
employee_age: ['', [Validators.required, Validators.maxLength(3)]]
});
let empid = localStorage.getItem('editEmpId');
if (+empid > 0) {
this.empService.getEmployeeById(+empid).subscribe(data => {
this.addForm.patchValue(data);
})
this.btnvisibility = false;
this.empformlabel = 'Edit Employee';
this.empformbtn = 'Update';
}
}
onSubmit() {
console.log('Create fire');
this.empService.createUser(this.addForm.value)
.subscribe(data => {
this.router.navigate(['list-emp']);
},
error => {
alert(error);
});
}
onUpdate() {
console.log('Update fire');
this.empService.updateEmployee(this.addForm.value).subscribe(data => {
this.router.navigate(['list-emp']);
},
error => {
alert(error);
});
}
}
// import { Component, OnInit } from '@angular/core';
// @Component({
// selector: 'app-employee-from',
// templateUrl: './employee-from.component.html',
// styleUrls: ['./employee-from.component.css']
// })
// export class EmployeeFromComponent implements OnInit {
// constructor() { }
// ngOnInit() {
// }
// }
// import { Component, OnInit } from '@angular/core';
// import { NgForm } from '@angular/forms'
// import { EmployeeService } from '../shared/employee.service'
// import { ToastrService } from 'ngx-toastr'
// @Component({
// selector: 'app-employee',
// templateUrl: './employee.component.html',
// styleUrls: ['./employee.component.css']
// })
// export class EmployeeComponent implements OnInit {
// constructor(private employeeService: EmployeeService, private toastr: ToastrService) { }
// ngOnInit() {
// this.resetForm();
// }
// resetForm(form?: NgForm) {
// if (form != null)
// form.reset();
// this.employeeService.selectedEmployee = {
// EmployeeID: null,
// FirstName: '',
// LastName: '',
// EmpCode: '',
// Position: '',
// Office: ''
// }
// }
// onSubmit(form: NgForm) {
// if (form.value.EmployeeID == null) {
// this.employeeService.postEmployee(form.value)
// .subscribe(data => {
// this.resetForm(form);
// this.employeeService.getEmployeeList();
// this.toastr.success('New Record Added Succcessfully', 'Employee Register');
// })
// }
// else {
// this.employeeService.putEmployee(form.value.EmployeeID, form.value)
// .subscribe(data => {
// this.resetForm(form);
// this.employeeService.getEmployeeList();
// this.toastr.info('Record Updated Successfully!', 'Employee Register');
// });
// }
// }
// }<file_sep>export class Employee {
ID? : number;
FirstName?:string;
LastName?:string;
EmpCode?:string;
Position?:string;
Office?:string;
}<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-receivables',
templateUrl: './receivables.component.html',
styleUrls: ['./receivables.component.css']
})
export class ReceivablesComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
}
// export class ReceivablesVoucher {
// VoucherID: string;
// VoucherNo: string;
// VoucherType:string;
// VoucherDate: Date;
// PartnerType:string;
// PartnerID:number;
// PartnerName:string;
// PartnerAddr:string;
// AcntDbID:string;
// CurrencyID:string;
// RateOfEx:number;
// Note:string;
// VCountAttach:string;
// PartDelegate:string;
// TtlAmount:number;
// TtlAmtInExc:number;
// TaxCode:string;
// IsNotWriteAcnt:boolean;
// UserWriter:string;
// UserUpdate:string;
// LineNum:string;
// AcntCrID:string;
// Amount:number;
// AmtInExc:number;
// NoteLine:string;
// Quantity:number;
// Price:number;
// }<file_sep> import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { Employee } from './employee.model';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
constructor(private http: HttpClient) { }
baseUrl: string = 'https://jsonplaceholder.typicode.com/users/';
// baseUrl: string = ' http://localhost:59452/api/Emp';
getEmps() {
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Methods':'GET, POST',
'Access-Control-Allow-Origin': '*'
});
let options = {
headers: headers
}
return this.http.get('http://localhost:59452/api/Emp',options);
}
getEmployees() {
return this.http.get<Employee[]>(this.baseUrl);
}
deleteEmployees(id: number) {
return this.http.delete<Employee[]>(this.baseUrl + id);
}
createUser(employee: Employee) {
return this.http.post(this.baseUrl, employee);
}
getEmployeeById(id: number) {
return this.http.get<Employee>(this.baseUrl + '/' + id);
}
updateEmployee(employee: Employee) {
return this.http.put(this.baseUrl + '/' + employee.ID, employee);
}
}
// import { Http, Response, Headers, RequestOptions, RequestMethod } from '@angular/http';
// // import { Observable } from 'rxjs/Observable';
// import 'rxjs/add/operator/map';
// import 'rxjs/add/operator/toPromise';
// import {Employee} from'./employee.model'
// @Injectable()
// export class EmployeeService {
// selectedEmployee : Employee;
// employeeList : Employee[];
// constructor(private http : Http) { }
// postEmployee(emp : Employee){
// var body = JSON.stringify(emp);
// var headerOptions = new Headers({'Content-Type':'application/json'});
// var requestOptions = new RequestOptions({method : RequestMethod.Post,headers : headerOptions});
// return this.http.post('http://localhost:28750/api/Employee',body,requestOptions).map(x => x.json());
// }
// putEmployee(id, emp) {
// var body = JSON.stringify(emp);
// var headerOptions = new Headers({ 'Content-Type': 'application/json' });
// var requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
// return this.http.put('http://localhost:28750/api/Employee/' + id,
// body,
// requestOptions).map(res => res.json());
// }
// getEmployeeList(){
// this.http.get('http://localhost:28750/api/Employee')
// .map((data : Response) =>{
// return data.json() as Employee[];
// }).toPromise().then(x => {
// this.employeeList = x;
// })
// }
// deleteEmployee(id: number) {
// return this.http.delete('http://localhost:28750/api/Employee/' + id).map(res => res.json());
// }
// }<file_sep>import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../shared/employee.services';
import { Employee } from '../shared/employee.model';
import { Router } from "@angular/router";
// @Component({
// selector: 'app-list-emp',
// templateUrl: './list-emp.component.html',
// styleUrls: ['./list-emp.component.css']
// })
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
employees: Employee[];
constructor(private empService: EmployeeService, private router: Router, ) { }
ngOnInit() {
// this.empService.getEmployees()
// .subscribe((data: Employee[]) => {
// this.employees = data;
// });
this.empService.getEmps()
.subscribe((data: Employee[]) => {
this.employees = data;
});
}
deleteEmp(employee: Employee): void {
this.empService.deleteEmployees(employee.ID)
.subscribe(data => {
this.employees = this.employees.filter(u => u !== employee);
})
}
editEmp(employee: Employee): void {
localStorage.removeItem('editEmpId');
localStorage.setItem('editEmpId', employee.ID.toString());
this.router.navigate(['add-emp']);
}
}
// import { Component, Input } from '@angular/core';
// interface Alert {
// type: string;
// message: string;
// }
// const ALERTS: Alert[] = [{
// type: 'success',
// message: 'This is an success alert',
// }, {
// type: 'info',
// message: 'This is an info alert',
// }, {
// type: 'warning',
// message: 'This is a warning alert',
// }, {
// type: 'danger',
// message: 'This is a danger alert',
// }, {
// type: 'primary',
// message: 'This is a primary alert',
// }, {
// type: 'secondary',
// message: 'This is a secondary alert',
// }, {
// type: 'light',
// message: 'This is a light alert',
// }, {
// type: 'dark',
// message: 'This is a dark alert',
// }
// ];
// @Component({
// selector: 'app-employee-list',
// templateUrl: './employee-list.component.html',
// styleUrls: ['./employee-list.component.css']
// })
// export class EmployeeListComponent {
// alerts: Alert[];
// constructor() {this.reset(); }
// close(alert: Alert) {
// this.alerts.splice(this.alerts.indexOf(alert), 1);
// }
// reset() {
// this.alerts = Array.from(ALERTS);
// }
// }
// import { Component, OnInit } from '@angular/core';
// import { EmployeeService } from '../shared/employee.service'
// import { Employee } from '../shared/employee.model';
// import { ToastrService } from 'ngx-toastr';
// @Component({
// selector: 'app-employee-list',
// templateUrl: './employee-list.component.html',
// styleUrls: ['./employee-list.component.css']
// })
// export class EmployeeListComponent implements OnInit {
// constructor(private employeeService: EmployeeService,private toastr : ToastrService) { }
// ngOnInit() {
// this.employeeService.getEmployeeList();
// }
// showForEdit(emp: Employee) {
// this.employeeService.selectedEmployee = Object.assign({}, emp);;
// }
// onDelete(id: number) {
// if (confirm('Are you sure to delete this record ?') == true) {
// this.employeeService.deleteEmployee(id)
// .subscribe(x => {
// this.employeeService.getEmployeeList();
// this.toastr.warning("Deleted Successfully","Employee Register");
// })
// }
// }
// }<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http' ;
import { ColorPickerModule } from 'ngx-color-picker';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ReceivablesComponent } from './shared/receivables/receivables.component';
import { NavbarComponent } from './navbar/navbar.component';
import { LinkComponent } from './home/link/link.component';
import { HeaderComponent } from './home/header/header.component';
import { AboutComponent } from './home/about/about.component';
import { LoginComponent } from './home/login/login.component';
import { EmployeeComponent } from './shared/employee/employee.component';
import { EmployeeListComponent } from './shared/employee/employee-list/employee-list.component';
import { EmployeeFromComponent } from './shared/employee/employee-from/employee-from.component';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { EmployeeService } from './shared/employee/shared/employee.services';
@NgModule({
declarations: [
AppComponent,
ReceivablesComponent,
NavbarComponent,
LinkComponent,
HeaderComponent,
AboutComponent,
LoginComponent,
EmployeeComponent,
EmployeeListComponent,
EmployeeFromComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ColorPickerModule,
NgbModule,
HttpClientModule
],
providers: [EmployeeService],
bootstrap: [AppComponent]
})
export class AppModule { }
| 6411454c3c0f89c617f15601ace4bc4410d9bfed | [
"TypeScript"
]
| 6 | TypeScript | xuanphi7895/AngularV6_2019 | 603f7626d2b4e7134387a5c660c2463e647ef9f5 | 303df340ff6fd78b5800c8b8ddde92c8e2950368 |
refs/heads/master | <file_sep>// Score Keeper
var p1Button = document.querySelector("#p1"),
p2Button = document.querySelector("#p2"),
p1Display = document.querySelector("#p1Display"),
p2Display = document.querySelector("#p2Display"),
resetScore = document.querySelector("#reset"),
numInput = document.querySelector("input"),
winningScoreDisplay = document.querySelector("p span"),
p1Score = 0,
p2Score = 0,
gameOver = false,
winningScore = 5;
// Add an event listener
p1Button.addEventListener("click",function(){
// The winning score hasn't been reached
if( !gameOver ) {
// increase the score
p1Score++;
// When the winning score is reached
if( p1Score === winningScore ) {
gameOver = true;
p1Display.classList.add("green-text");
}
// Display the score count
p1Display.textContent = p1Score;
}
});
// Player two score count
p2Button.addEventListener("click",function(){
// The winning score hasn't been reached
if( !gameOver ) {
// increase the score
p2Score++;
// When the winning score is reached
if( p2Score === winningScore ) {
gameOver = true;
p2Display.classList.add("green-text");
}
// Display the score count
p2Display.textContent = p2Score;
}
});
resetScore.addEventListener("click", function(){
reset();
});
numInput.addEventListener("change",function(){
winningScoreDisplay.textContent = this.value;
winningScore = Number(this.value);
reset();
});
function reset(){
p1Score = 0;
p2Score = 0;
p1Display.textContent = 0;
p2Display.textContent = 0;
p1Display.classList.remove("green-text");
p2Display.classList.remove("green-text");
gameOver = false;
}<file_sep>var express = require("express");
var app = express();
// home
app.get("/", function(req, res){
res.send("Welcome Home!");
});
// Animal & sounds
app.get("/speak/:animal", function(req, res){
var sounds = {
pig: "Oink",
cow: "Moo",
dog: "Woof",
fish: "..."
}
var animal = req.params.animal.toLowerCase();
var sound = sounds[animal];
res.send("The " + animal + " says '" + sound + "'");
});
// Repeat greeting
app.get("/repeat/:message/:times/", function(req, res){
var message = req.params.message;
var times = Number(req.params.times);
var result = "";
for( var i = 0; i < times; i++) {
result += message + ", " ;
}
// Send the response
res.send(result);
});
// Error page
app.get("*", function(req, res){
res.send("Sorry, page not found. What are you doing with your life?!!!");
});
// Start the server
app.listen(8080, function(){
console.log("Listening on port: " + 8080);
});<file_sep>/********************
*** Introduction ***
********************/
First thing to do --
1) Add myself to the course discussion
Seven Reasons to start a web/mobile application business --
1) It's very rewarding work
2) The bulk of money is in design & devolopment
3) Margins in web development are amazing
4) You set yourself up for startup success in the future
5) You get exposure to a variety of online disciplines
6) You can set it and forget it
7) You can add development as an extra service you offer
How to add development services to exisiting business --
1) List it on your website
2) Add it to your branding
3)
Attach development estimates to all projects
** Estimates are helpful for clients
Who is this course for? --
1) Anyone can do it
2) Coding skills are not mandatory
3) You can do it part-time
4) What skills do you need? Opinions, interest
5) Three main groups of people who can benefit
-- Programmers
-- Non-technical euntrpreneurs
-- Freelancer
/**********************
*** The Essentials ***
**********************/
Understanding the "Dev Stack" --
1) L.A.M.P - Linux, Apache, MySQL, PHP
2) Design Layer - HTML, JS, CSS
How to pick a stack --
1) If you are a programmer use the stack your are used to
2) The Languages in the stack do not matter, focus on the people
3) Focus on the people that give the best results
The startup timeline --
1) A lot of work upfront
2) Think about strategy
3) Decide what you want to do
4) Do some research on the market
5) Assess your skills and interests
6) Establish a web presence
7) Focus on how to capture clients -- Can do both at the same time
8) The trough of sorrow
9) People will always need development services
10) It takes time
11) You will figure out your reliable team
How does this work as a programmer/non technical --
1) Focussing on sub-contracting
2) Lead Developer or part-time dev, project manager
3) Look for good subcontractors
How do development firms typically work? --
<file_sep>"use strict";
/**********************
***** Code Along *****
**********************/
// create a key for knowing which keys are selectable
var keys = Object.keys(keyData);
$(keys).each( function(e){
$("#keyList").append("<li>" + "<span class='alpha'>" + $(this).selector + "</span> " + "</li>");
keySelector();
});
function keySelector(){
for( var i = 0; i < keys.length; i++ ){
if(keys[i].selector === keyStroke() ){
console.log( keys[i].selector, keyStroke() );
};
}
//return selectorKey;
}
function keyStroke() {
$(document).keypress(function( e ) {
var k = String.fromCharCode(e.which) // or e.keyCode
return k;
});
}
// Let the user choos background color varieties
// let the user add thir name
// let the user record their songs
// let the user download/review their soungs
<file_sep>#Intro to Node
* What us Node?
* Why are we learning Node?
* It is popular
* Javascript
* (it doesn't matter(long term))
#Using Node
* Interacting with Node
* Run a file with Node
*
node <filename>
<file_sep>// Plugins for brackets:
- Postman
- shell
- git
- theme: tonight's specials
- js lint
- gulp
- vagrant
- text-count
- node.js bindings
- extract
'npm init' creates a new package.json for us
Express Routes:
app.get('*', function(req, res){ res.send("404");});
- Route variables or route parameters
-
app.get('/directory/:subdirectory', function(req, res){ res.send("Welcome to a pattern of sub directory");});
app.get('/directory/:subdirectory/comments/:id/:title/', function(req, res){ res.send("Welcome to a pattern of sub directory");});
Rendering express templates
- res.render();
app.get("/love/:word", function(req, res){
var word = req.params.word
res.render("love.ejs", {word: word});
});
#EJS Control Flow
* Show examples of control flow in EJS templates
* Write if statements in an EJS file
* Write loops in an EjS file
Loop through all posts
make an entry div
title
tagline
...
#Styles and Partials
* Show how to properly include public assets
* Properly configure our app to use EJS
* Use partials to dry up our code
// Declare public directory
app.use(express.static("public"));
// Declare EJS for ease of use
app.set("view engine", "ejs");
<%= include partials/header %>
#Post Requests
* Write post routes, and test them with Postman
* Use a form to send a request
* Use body parser to get form data
#YelpCamp
* Add Landing Page
* Add Campgrounds page that lists all campgrounds
Each campground has:
* Name
* Image
#Layout and Styling
* Create our header and footer partials
* Add in bootstrap
#Creating New Campgrounds
* Setup new campground POST route
* Add in body-parser
* Setup route to show form
* Add basic unstyled form
#Databases
##Intro to DBs
* what is a database?
* SQL vs, NoSQL
# Our First Mongo Commands
* mongod
* mongo
* help
* showdbs
* use - use <db name>
* insert - db.insert({})
* find - db.<db name>.find()
* update - db.<db name>.update()
* remove
#Mongoose
# Associtions
##Intro to Associations
* Define associations
## Embedding Data
User
Post
## Referencing Data
# Git NOTES
** Deploying from Heroku
heroku create
git push heroku master
heroku logs
heroku run ls
export DATABASEURL=mongodb://localhost/yelp_camp_v4
mongodb://morgansegura:<EMAIL>:21182/yelpcamp
<file_sep>npm init -- for package.json
<file_sep>(function () {
'use strict';
var scores = [90, 98, 89, 100, 100, 86, 94];
// function average
function average(scores) {
// add all scores togther
var total = 0;
scores.forEach(function (score) {
total += score;
});
// divide by total number of scores
var avg = total / scores.length;
// round average
return Math.round(avg);
}
console.log(average(scores)); // returns 94
}());
<file_sep>var mongoode = require("mongoose");
mongoose.connect("mongodb:localhost/blog-demo");<file_sep># The Complete Guide to running a web development business Course
#### TODO: Add Notes to README file
<file_sep>var express = require("express");
var app = express();
// Declare public assets
app.use(express.static("public"));
// Declare EJS for ease of use
app.set("view engine", "ejs");
// Home page
app.get("/", function(req, res){
res.render("home");
});
// Subcategory
app.get("/love/:word", function(req, res){
var word = req.params.word
res.render("love", {word: word});
});
// Posts page
app.get("/posts", function(req, res) {
var posts = [
{title: "Hallogram Electric", author: "<NAME>."},
{title: "Girls, Girls, Girls", author: "<NAME>."},
{title: "After Hour Tower", author: "<NAME>."},
{title: "Random love bubble", author: "<NAME>."},
{title: "On any other day", author: "<NAME>."},
];
res.render("posts", {posts: posts});
});
app.listen(8080, function(){
console.log("Server listening on: 8080");
});
<file_sep># README for Web Developer Bootcamp Course
#### TODO: Add Notes to README file
<file_sep>// Toggle background
var button = document.querySelector("button"),
isPurple = false;
// Add an event listener
button.addEventListener("click", function(){
document.body.classList.toggle("purple");
});
/*
// function to toggle background
function toggleBackground(){
if( isPurple ){
document.body.style.background = "transparent";
} else {
document.body.style.background = "purple";
}
// Switch boolean
isPurple = !isPurple;
}
*/<file_sep># study
Courses for improvement
<file_sep>"use strict";
/*********************
***** Todo list *****
*********************/
// Check off Specific Todos by clicking
$("ul").on("click", "li", function(){
$(this).toggleClass("completed");
});
// Click on X to delete To-Do
$("ul").on("click", "span", function( e ){
// fadeout then remove this todo item
$(this).parent().fadeOut(500, function(){
$(this).remove();
});
// stop propagation
e.stopPropagation();
});
// add services for input field
$("input[type='text']").keypress(function( e ){
// if the user hits enter
if( e.which === 13 ) {
// get input value
var toDoItem = $(this).val();
$(this).val("");
// create a new li and add to ul
$("ul").append("<li><span><i class='fa fa-trash'></i></span>" + toDoItem + "</li>");
}
});
$(".fa-plus").click(function(){
// switch the icon on click toggle
$(this).toggleClass("fa-minus");
$("input[type='text']").fadeToggle("fast");
}); | 86ac642fd86b447998074db855d250a86b4059a5 | [
"JavaScript",
"Text",
"Markdown"
]
| 15 | JavaScript | morgansegura/study | 5ce55825141d0358d14101b524d6b26dd13b01f8 | e17873ae5ce03bb25685d60dc82b9a1b80a41503 |
refs/heads/master | <file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { HashRouter, Switch, Route } from 'react-router-dom';
import LoginScreenContainer from './containers/LoginScreenContainer';
import rootReducer from './store/reducers';
// Create a store from the rootReducer, and allow the devtools to hook in
const store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
ReactDOM.render((
<Provider store={store}>
<HashRouter>
<Switch>
<Route path='/' component={LoginScreenContainer} />
</Switch>
</HashRouter>
</Provider>
), document.getElementById('root'));
<file_sep>import {
SET_WATCHERS
} from './actions';
const initialState = {
selectedWatchers: []
};
export default function loginReducer(state = initialState, action) {
switch(action.type) {
case SET_WATCHERS:
return {
...state,
selectedWatchers: action.selectedWatchers,
};
default:
return state;
}
}<file_sep>'use strict';
import react, { Component } from 'react';
export default class App extends Component {
// This is the root component
}<file_sep>'use strict';
const host = 'localhost';
const port = 4001;
export const uri = `http://${host}:${port}`;
/**
* Reduce an object of WS Message Types for listening on.
*/
export const messageTypes = [
'welcome'
].reduce((accum, msg) => {
accum[msg] = msg;
return accum;
}, {});<file_sep>/**
* Set the selected watchers.
*
* This should use information provided by the WSS to remember the names and UUIDs of the watchers the user chooses
* They should then be written to the redux state, which can be used to generate the logStream tabs later
*
* selectedWatchers should be an array of objects containing a name and uuid
* [{ name: 'String', uuid: 'string' }]
*/
export const SET_WATCHERS = 'SET_WATCHERS';
export function setWatchers(selectedWatchers) {
return { type: SET_WATCHERS, selectedWatchers };
};
<file_sep>'use strict';
import io from 'socket.io-client';
import { messageTypes, uri } from '../constants/websocket.js';
const socket = io(uri);
export const init = (store) => {
Object.keys( messageTypes )
.forEach( type => socket.on(type, (payload) =>
store.dispatch({ type, payload })
)
);
};
/**
* Abstraction of the standard socket.io emission method
*
* @param {String} type
* @param {Object} payload
*/
export const emit = (type, payload) => socket.emit(type, payload); | 728d0a224a6cde1ee848302be9b4ea3a32d926c7 | [
"JavaScript"
]
| 6 | JavaScript | cpave3/nlog-react | 9ebf8a29cd73e67ccf38555587ebcbea6b5659ee | cafd5d65443f44d8b4c218c87e4b6e4f69d2979b |
refs/heads/master | <file_sep>// see https://github.com/Microsoft/monaco-editor
self.MonacoEnvironment = {
baseUrl: "/pxt-sample/"
};
importScripts("/pxt-sample/vs/base/worker/workerMain.js");<file_sep># Projects
```codecard
[
{
"name": "Tutorials",
"url": "/tutorials",
"imageUrl": "https://pxt.azureedge.net/blob/bd3236c80ed86cbf0b99ff39f26469683c512ebc/static/mb/projects/a1-display.png"
}
]
```
## See Also
[Tutorials](/tutorials)
<file_sep>var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/// <reference path="../libs/core/enums.d.ts"/>
var pxsim;
(function (pxsim) {
var hare;
(function (hare) {
/**
* This is hop
*/
//% blockId="sampleHop" block="hop %hop on color %color=colorNumberPicker"
//% hop.fieldEditor="gridpicker"
function hop(hop, color) {
}
hare.hop = hop;
//% blockId=sampleOnLand block="on land"
//% optionalVariableArgs
function onLand(handler) {
}
hare.onLand = onLand;
})(hare = pxsim.hare || (pxsim.hare = {}));
})(pxsim || (pxsim = {}));
(function (pxsim) {
var turtle;
(function (turtle) {
/**
* Moves the sprite forward
* @param steps number of steps to move, eg: 1
*/
//% weight=90
//% blockId=sampleForward block="forward %steps"
function forwardAsync(steps) {
return pxsim.board().sprite.forwardAsync(steps);
}
turtle.forwardAsync = forwardAsync;
/**
* Moves the sprite forward
* @param direction the direction to turn, eg: Direction.Left
* @param angle degrees to turn, eg:90
*/
//% weight=85
//% blockId=sampleTurn block="turn %direction|by %angle degrees"
//% angle.min=-180 angle.max=180
function turnAsync(direction, angle) {
var b = pxsim.board();
if (direction == 0 /* Left */)
b.sprite.angle -= angle;
else
b.sprite.angle += angle;
return Promise.delay(400);
}
turtle.turnAsync = turnAsync;
/**
* Triggers when the turtle bumps a wall
* @param handler
*/
//% blockId=onBump block="on bump"
function onBump(handler) {
var b = pxsim.board();
b.bus.listen("Turtle", "Bump", handler);
}
turtle.onBump = onBump;
})(turtle = pxsim.turtle || (pxsim.turtle = {}));
})(pxsim || (pxsim = {}));
(function (pxsim) {
var loops;
(function (loops) {
/**
* Repeats the code forever in the background. On each iteration, allows other code to run.
* @param body the code to repeat
*/
//% help=functions/forever weight=55 blockGap=8
//% blockId=device_forever block="forever"
function forever(body) {
pxsim.thread.forever(body);
}
loops.forever = forever;
/**
* Pause for the specified time in milliseconds
* @param ms how long to pause for, eg: 100, 200, 500, 1000, 2000
*/
//% help=functions/pause weight=54
//% block="pause (ms) %pause" blockId=device_pause
function pauseAsync(ms) {
return Promise.delay(ms);
}
loops.pauseAsync = pauseAsync;
})(loops = pxsim.loops || (pxsim.loops = {}));
})(pxsim || (pxsim = {}));
function logMsg(m) { console.log(m); }
(function (pxsim) {
var console;
(function (console) {
/**
* Print out message
*/
//%
function log(msg) {
logMsg("CONSOLE: " + msg);
// why doesn't that work?
pxsim.board().writeSerial(msg + "\n");
}
console.log = log;
})(console = pxsim.console || (pxsim.console = {}));
})(pxsim || (pxsim = {}));
(function (pxsim) {
/**
* A ghost on the screen.
*/
//%
var Sprite = /** @class */ (function () {
function Sprite() {
/**
* The X-coordiante
*/
//%
this.x = 100;
/**
* The Y-coordiante
*/
//%
this.y = 100;
this.angle = 90;
}
Sprite.prototype.foobar = function () { };
/**
* Move the thing forward
*/
//%
Sprite.prototype.forwardAsync = function (steps) {
var deg = this.angle / 180 * Math.PI;
this.x += Math.cos(deg) * steps * 10;
this.y += Math.sin(deg) * steps * 10;
pxsim.board().updateView();
if (this.x < 0 || this.y < 0)
pxsim.board().bus.queue("TURTLE", "BUMP");
return Promise.delay(400);
};
return Sprite;
}());
pxsim.Sprite = Sprite;
})(pxsim || (pxsim = {}));
(function (pxsim) {
var sprites;
(function (sprites) {
/**
* Creates a new sprite
*/
//% blockId="sampleCreate" block="createSprite"
function createSprite() {
return new pxsim.Sprite();
}
sprites.createSprite = createSprite;
})(sprites = pxsim.sprites || (pxsim.sprites = {}));
})(pxsim || (pxsim = {}));
/// <reference path="../node_modules/pxt-core/built/pxtsim.d.ts"/>
var pxsim;
(function (pxsim) {
/**
* This function gets called each time the program restarts
*/
pxsim.initCurrentRuntime = function () {
pxsim.runtime.board = new Board();
};
/**
* Gets the current 'board', eg. program state.
*/
function board() {
return pxsim.runtime.board;
}
pxsim.board = board;
/**
* Represents the entire state of the executing program.
* Do not store state anywhere else!
*/
var Board = /** @class */ (function (_super) {
__extends(Board, _super);
function Board() {
var _this = _super.call(this) || this;
_this.bus = new pxsim.EventBus(pxsim.runtime);
_this.element = document.getElementById('svgcanvas');
_this.spriteElement = _this.element.getElementById('svgsprite');
_this.hareElement = _this.element.getElementById('svgsprite2');
_this.sprite = new pxsim.Sprite();
_this.hare = new pxsim.Sprite();
return _this;
}
Board.prototype.initAsync = function (msg) {
document.body.innerHTML = ''; // clear children
document.body.appendChild(this.element);
return Promise.resolve();
};
Board.prototype.updateView = function () {
this.spriteElement.cx.baseVal.value = this.sprite.x;
this.spriteElement.cy.baseVal.value = this.sprite.y;
this.hareElement.cx.baseVal.value = this.hare.x;
this.hareElement.cy.baseVal.value = this.hare.y;
};
return Board;
}(pxsim.BaseBoard));
pxsim.Board = Board;
})(pxsim || (pxsim = {}));
<file_sep># Examples
Here are some fun programs for your board!
## Fun stuff
```codecard
[{
"name": "Flashing Heart",
"description": "Make an animated flashing heart.",
"url":"/tutorials/flashing-heart",
"imageUrl": "https://pxt.azureedge.net/blob/bd3236c80ed86cbf0b99ff39f26469683c512ebc/static/mb/projects/a1-display.png",
"cardType": "tutorial"
}, {
"name": "Name Tag",
"description": "Scroll your name on the screen",
"url": "/tutorials/name-tag",
"imageUrl": "https://pxt.azureedge.net/blob/e03f64a983c3650f5487009bd9952b1248954e45/static/mb/projects/name-tag.png",
"cardType": "tutorial"
},
{
"name": "Smiley Buttons",
"description": "Show different smiley images by pressing the buttons.",
"url": "/tutorials/smiley-buttons",
"imageUrl": "https://pxt.azureedge.net/blob/668a5a469bae3627ba78dab1f69b1a7e87972f28/static/mb/projects/a2-buttons.png",
"cardType": "tutorial"
},
{
"name": "Dice",
"description": "Shake the dice and see what number comes up!",
"url": "/tutorials/dice",
"imageUrl": "https://pxt.azureedge.net/blob/cb81642a25f424bc62d30f74f6072e07b6db85d9/static/mb/projects/dice.png",
"cardType": "tutorial"
},
{
"name": "Love Meter",
"description": "Is the micro:bit is feeling the love, see how much!",
"url": "/tutorials/love-meter",
"imageUrl": "https://pxt.azureedge.net/blob/5e81154127a6378383b7cab124bbb41ea9409a63/static/mb/projects/a3-pins.png",
"cardType": "tutorial"
},
{
"name": "Micro Chat",
"description": "Build your own social network made of micro:bits.",
"url": "/tutorials/micro-chat",
"imageUrl": "https://pxt.azureedge.net/blob/d8cf0f404e04aa67a9f8ed773b2386aa202776de/static/mb/projects/a9-radio.png",
"cardType": "tutorial"
}
]
```
| a5b6abf175dded55d2b7e4b942c346ddcde17fad | [
"JavaScript",
"Markdown"
]
| 4 | JavaScript | plantopia-code/turorials | 92da9eabfe544110d8912c40f67e96c74faf0d24 | 904ec41ff260e934faeacdb21251d6b0e71adb6c |
refs/heads/master | <repo_name>ngrundback/redpine<file_sep>/release/rand.sh
while :
do
./onebox_util rpine0 do_bgscan 0 1
i=$(($i+1))
sleep 1
if [ "$i" == "10000000000000" ]; then
break;
fi
done
<file_sep>/common_hal/Makefile
#/**
# * @file Makefile
# * @author
# * @version 1.0
# *
# * @section LICENSE
# *
# * This software embodies materials and concepts that are confidential to Redpine
# * Signals and is made available solely pursuant to the terms of a written license
# * agreement with Redpine Signals
# *
# * @section DESCRIPTION
# *
# * This is the HAL Makefile used for generating the GPL and NON-GPL modules.
# */
DRV_DIR=$(ROOT_DIR)/common_hal
RELEASE_DIR=$(ROOT_DIR)/release
OSI_DIR=osi
HOST_INTF_OSD_SDIO_DIR=intfdep/sdio/osd_sdio/linux
HOST_INTF_OSI_SDIO_DIR=intfdep/sdio/osi_sdio
HOST_INTF_OSD_USB_DIR=intfdep/usb/osd_usb/linux
HOST_INTF_OSI_USB_DIR=intfdep/usb/osi_usb
OSD_DIR=osd/linux
include $(ROOT_DIR)/.config
include $(ROOT_DIR)/config/make.config
EXTRA_CFLAGS += -DLINUX -Wimplicit -Wstrict-prototypes
EXTRA_CFLAGS += -DFLASH_BURNING
#EXTRA_CFLAGS += -DULP_GPIO_LP
#EXTRA_CFLAGS += -DRF_SUPPLY_19_V
#EXTRA_CFLAGS += -DRSI_IMX51
#EXTRA_CFLAGS += -DGPIO_HANDSHAKE
EXTRA_CFLAGS += -DPWR_SAVE_SUPPORT
EXTRA_CFLAGS += -DBGSCAN_SUPPORT
EXTRA_CFLAGS += -DRSI_SDIO_MULTI_BLOCK_SUPPORT
EXTRA_CFLAGS += -DSECURITY_SUPPORT
EXTRA_CFLAGS += -DDYNAMIC_VARIABLES
EXTRA_CFLAGS += -DRF_8111
#EXTRA_CFLAGS += -DDISABLE_TALOAD
EXTRA_CFLAGS += -I$(DRV_DIR)/include/linux
EXTRA_CFLAGS += -I$(DRV_DIR)/include/common
#EXTRA_CFLAGS += -DFPGA_VALIDATION
EXTRA_CFLAGS += -I$(NET80211_DIR)/osd_linux/include
EXTRA_CFLAGS += -g
ifeq ($(USE_DEVICE),"SDIO")
EXTRA_CFLAGS += -DUSE_SDIO_INTF
HOST_INTF_OSI_OBJ := $(HOST_INTF_OSI_SDIO_DIR)/onebox_sdio_main_osi.o \
$(HOST_INTF_OSI_SDIO_DIR)/onebox_host_intf_osi_callbacks.o
HOST_INTF_OSD_OBJ := $(HOST_INTF_OSD_SDIO_DIR)/onebox_sdio_main_osd.o \
$(HOST_INTF_OSD_SDIO_DIR)/onebox_host_intf_osd_callbacks.o
else
EXTRA_CFLAGS += -DUSE_USB_INTF
#EXTRA_CFLAGS += -DUSB_BUFFER_STATUS_INDI
HOST_INTF_OSI_OBJ := $(HOST_INTF_OSI_USB_DIR)/onebox_usb_main_osi.o \
$(HOST_INTF_OSI_USB_DIR)/onebox_host_intf_osi_callbacks.o
HOST_INTF_OSD_OBJ := $(HOST_INTF_OSD_USB_DIR)/onebox_usb_main_osd.o \
$(HOST_INTF_OSD_USB_DIR)/onebox_host_intf_osd_callbacks.o
endif
CORE_OBJ := $(OSI_DIR)/onebox_common_tx.o \
$(OSI_DIR)/onebox_common_rx.o \
$(OSI_DIR)/onebox_common_init.o \
$(OSI_DIR)/onebox_flashing.o \
$(OSI_DIR)/checksum_onescompliment.o \
$(OSI_DIR)/onebox_common_devops.o \
$(OSI_DIR)/onebox_common_callbacks.o \
$(OSI_DIR)/onebox_common_pwr_mngr.o \
$(OSI_DIR)/onebox_common_dev_config_params.o
ifeq ($(USE_DEVICE),"SDIO")
CORE_OBJ += $(OSI_DIR)/onebox_sdio_devops.o
else
CORE_OBJ += $(OSI_DIR)/onebox_usb_devops.o
endif
OSD_OBJ := $(OSD_DIR)/onebox_modules_init.o \
$(OSD_DIR)/onebox_proc.o \
$(OSD_DIR)/onebox_file_ops.o \
$(OSD_DIR)/onebox_thread.o \
$(OSD_DIR)/onebox_osd_ops.o \
$(OSD_DIR)/onebox_osd_callbacks.o \
$(OSD_DIR)/onebox_gpio.o
NONGPL_OBJS := $(CORE_OBJ) $(HOST_INTF_OSI_OBJ)
GPL_OBJS := $(HOST_INTF_OSD_OBJ) $(OSD_OBJ)
obj-m := onebox_gpl.o
onebox_gpl-objs := $(GPL_OBJS)
obj-m += onebox_nongpl.o
onebox_nongpl-objs := $(NONGPL_OBJS)
all:
@echo "Compiling gpl and non gpl modules"
make -C$(KERNELDIR) SUBDIRS=$(DRV_DIR) modules
# @echo "Copying gpl and nongpl modules..."
# @cp onebox_nongpl.ko onebox_gpl.ko $(RELEASE_DIR)/.
clean:
@echo "- Cleaning All Object and Intermediate Files"
@find . -name '*.ko' | xargs rm -rf
@find . -name '.*.ko.cmd' | xargs rm -rf
@find . -name '.*.ko.unsigned.cmd' | xargs rm -rf
@find . -name '*.ko.*' | xargs rm -rf
@find . -name '*.order' | xargs rm -rf
@find . -name '*.symvers' | xargs rm -rf
@find . -name '*.markers' | xargs rm -rf
@find . -name '*.o' | xargs rm -f
@find . -name '.*.ko.cmd' | xargs rm -rf
@find . -name '.*.o.cmd' | xargs rm -rf
@find $(OSD_DIR) -name '*.o' | xargs rm -f
@find $(HOST_INTF_DIR) -name '.*.o.cmd' | xargs rm -rf
@find . -name '*.mod.c' | xargs rm -rf
@echo "- Done"
<file_sep>/common_hal/include/common/onebox_sdio_intf.h
/**
* @file onebox_sdio_intf.h
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contians the function prototypes of related to sdio interface
*
*/
#ifndef __ONEBOX_SDIO_INTF__
#define __ONEBOX_SDIO_INTF__
#ifdef ARASAN_SDIO_STACK
#include "sdio.h"
#include "sdcard.h"
#include "sdio_hci.h"
#include "srb.h"
#include "sdioctl.h"
#else
#if((LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,18))&& \
(LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23)))
#include <linux/sdio/ctsystem.h>
#include <linux/sdio/sdio_busdriver.h>
#include <linux/sdio/_sdio_defs.h>
#include <linux/sdio/sdio_lib.h>
#elif (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,26))
#include <linux/mmc/card.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/host.h>
#include <linux/mmc/sdio_func.h>
#include <linux/mmc/sdio_ids.h>
#include <linux/mmc/sdio.h>
#include <linux/mmc/sd.h>
#include <linux/mmc/sdio_ids.h>
#endif
#endif
#ifdef USE_USB_INTF
#include <linux/usb.h>
#endif
#define ULP_RESET_REG 0x161
#define WATCH_DOG_TIMER_1 0x16c
#define WATCH_DOG_TIMER_2 0x16d
#define WATCH_DOG_DELAY_TIMER_1 0x16e
#define WATCH_DOG_DELAY_TIMER_2 0x16f
#define WATCH_DOG_TIMER_ENABLE 0x170
#define RESTART_WDT BIT(11)
#define BYPASS_ULP_ON_WDT BIT(1)
#define RF_SPI_PROG_REG_BASE_ADDR 0x40080000
#define GSPI_CTRL_REG0 (RF_SPI_PROG_REG_BASE_ADDR)
#define GSPI_CTRL_REG1 (RF_SPI_PROG_REG_BASE_ADDR + 0x2)
#define GSPI_DATA_REG0 (RF_SPI_PROG_REG_BASE_ADDR + 0x4)
#define GSPI_DATA_REG1 (RF_SPI_PROG_REG_BASE_ADDR + 0x6)
#define GSPI_DATA_REG2 (RF_SPI_PROG_REG_BASE_ADDR + 0x8)
#define GSPI_DMA_MODE BIT(13)
#define GSPI_2_ULP BIT(12)
#define GSPI_TRIG BIT(7)
#define GSPI_READ BIT(6)
#define GSPI_RF_SPI_ACTIVE BIT(8)
/*CONTENT OF THIS REG IS WRITTEN TO ADDRESS IN SD_CSA_PTR*/
#define SD_REQUEST_MASTER 0x10000
#define ONEBOX_SDIO_BLOCK_SIZE 256
#define onebox_likely(a) likely(a)
/* Abort related */
//#define SDIO_REG_ABORT_FEEDBACK 0xF1
//#define MAX_ABORT_FEEDBACK_RETRY 0x05
//#define SDIO_ABORT_FEEDBACK_VALUE 0x11
/* FOR SD CARD ONLY */
#define SDIO_RX_NUM_BLOCKS_REG 0x000F1
#define SDIO_FW_STATUS_REG 0x000F2
#define SDIO_NXT_RD_DELAY2 0x000F5 /* Next read delay 2 */
#define SDIO_FUN1_INT_REG 0x000F9 /* Function interrupt register*/
#define SDIO_READ_START_LVL 0x000FC
#define SDIO_READ_FIFO_CTL 0x000FD
#define SDIO_WRITE_FIFO_CTL 0x000FE
#define SDIO_WAKEUP_REG 0x000FF
/* common registers in SDIO function1 */
#define SDIO_FUN1_INTR_CLR_REG 0x0008
#define TA_SOFT_RESET_REG 0x0004
#define TA_TH0_PC_REG 0x0400
#define TA_HOLD_THREAD_REG 0x0844
#define TA_RELEASE_THREAD_REG 0x0848
#define TA_POLL_BREAK_STATUS_REG 0x085C
/* WLAN registers in SDIO function 1 */
#define SDIO_RF_CNTRL_REG 0x0000000C /* Lower MAC control register-1 */
#define SDIO_LMAC_CNTRL_REG 0x00000024 /* Lower MAC control register */
#define SDIO_LMAC_LOAD_REG 0x00000020 /* Lower MAC load register */
#define SDIO_TCP_CHK_SUM 0x0000006C /* TCP check sum enable register */
#define RF_SELECT 0x0000000c /* RF Select Register */
/* SDIO STANDARD CARD COMMON CNT REG(CCCR) */
/*IN THESE REGISTERS EACH BIT(0-7) REFERS TO A FUNCTION */
#define CCCR_REVISION 0x00
#define SD_SPEC_REVISION 0x01
#define SD_IO_ENABLE 0x02
#define SD_IO_READY 0x03
#define SD_INT_ENABLE 0x04
#define SD_INT_PENDING 0x05
#define SD_IO_ABART 0x06
#define SD_BUS_IF_CNT 0x07
#define SD_CARD_CAPABILITY 0x08
/*PTR to CARD'S COMMON CARD INFO STRUCT(CIS):0x09-0x0B*/
#define SD_CIS_PTR 0x09
#define SD_BUS_SUSPEND 0x0C
#define SD_FUNCTION_SELEC 0x0D
#define SD_EXEC_FLAGS 0x0E
#define SD_READY_FLAGS 0x0F
#define SD_FN0_BLK_SZ 0x10 /*FUNCTION0 BLK SIZE:0x10-0x11 */
#define SD_RESERVED 0x12 /*0x12-0xFF:reserved for future */
#define SDIO_REG_HIGH_SPEED 0x13
/* SDIO_FUN1_FIRM_LD_CTRL_REG register bits */
#define TA_SOFT_RST_CLR 0
#define TA_SOFT_RST_SET BIT(0)
#define TA_PC_ZERO 0
#define TA_HOLD_THREAD_VALUE 0xF
#define TA_RELEASE_THREAD_VALUE 0xF
#define TA_DM_LOAD_CLR BIT(21)
#define TA_DM_LOAD_SET BIT(20)
/* Function prototypes */
struct onebox_osd_host_intf_operations *onebox_get_osd_host_intf_operations(void);
struct onebox_osi_host_intf_operations *onebox_get_osi_host_intf_operations(void);
struct onebox_os_intf_operations *onebox_get_os_intf_operations(void);
struct onebox_os_intf_operations *onebox_get_os_intf_operations_from_origin(void);
ONEBOX_STATUS read_register(PONEBOX_ADAPTER adapter, uint32 Addr,uint8 *data);
int write_register(PONEBOX_ADAPTER adapter,uint8 reg_dmn,uint32 Addr,uint8 *data);
ONEBOX_STATUS host_intf_read_pkt(PONEBOX_ADAPTER adapter,uint8 *pkt,uint32 Len);
ONEBOX_STATUS host_intf_write_pkt(PONEBOX_ADAPTER adapter,uint8 *pkt,uint32 Len, uint8 queueno);
ONEBOX_STATUS send_pkt_to_coex(netbuf_ctrl_block_t* pkt, uint8 hal_queue);
ONEBOX_STATUS get_pkt_from_coex(PONEBOX_ADAPTER adapter,
netbuf_ctrl_block_t *netbuf_cb);
ONEBOX_STATUS read_register_multiple(PONEBOX_ADAPTER adapter,
uint32 Addr,
uint32 Count,
uint8 *data );
ONEBOX_STATUS write_register_multiple(PONEBOX_ADAPTER adapter,
uint32 Addr,
uint8 *data,
uint32 Count);
ONEBOX_STATUS ack_interrupt(PONEBOX_ADAPTER adapter,uint8 INT_BIT);
#ifdef USE_USB_INTF
void onebox_rx_urb_submit (PONEBOX_ADAPTER adapter, struct urb *urb, uint8 ep_num);
ONEBOX_STATUS write_ta_register_multiple(PONEBOX_ADAPTER adapter,
uint32 Addr,
uint8 *data,
uint32 Count);
ONEBOX_STATUS read_ta_register_multiple(PONEBOX_ADAPTER adapter,
uint32 Addr,
uint8 *data,
uint32 Count);
#endif
int register_driver(void);
void unregister_driver(void);
ONEBOX_STATUS remove(void);
#if KERNEL_VERSION_BTWN_2_6_(18, 22)
struct net_device * onebox_getcontext(PSDFUNCTION pfunction);
#elif KERNEL_VERSION_GREATER_THAN_2_6_(26)
void* onebox_getcontext(struct sdio_func *pfunction);
#endif
#if KERNEL_VERSION_BTWN_2_6_(18, 22)
VOID onebox_sdio_claim_host(PSDFUNCTION pFunction);
#elif KERNEL_VERSION_GREATER_THAN_2_6_(26)
VOID onebox_sdio_claim_host(struct sdio_func *pfunction);
#endif
#if KERNEL_VERSION_BTWN_2_6_(18, 22)
VOID onebox_sdio_release_host(PSDFUNCTION pFunction);
#elif KERNEL_VERSION_GREATER_THAN_2_6_(26)
VOID onebox_sdio_release_host(struct sdio_func *pfunction);
#endif
#if KERNEL_VERSION_BTWN_2_6_(18, 22)
VOID onebox_setcontext(PSDFUNCTION pFunction, void *adapter);
#elif KERNEL_VERSION_GREATER_THAN_2_6_(26)
VOID onebox_setcontext(struct sdio_func *pfunction, void *adapter);
#endif
ONEBOX_STATUS onebox_setupcard(PONEBOX_ADAPTER adapter);
ONEBOX_STATUS init_host_interface(PONEBOX_ADAPTER adapter);
#if KERNEL_VERSION_BTWN_2_6_(18, 22)
int32 onebox_sdio_release_irq(PSDFUNCTION pFunction);
#elif KERNEL_VERSION_GREATER_THAN_2_6_(26)
int32 onebox_sdio_release_irq(struct sdio_func *pfunction);
#endif
int32 deregister_sdio_irq(PONEBOX_ADAPTER adapter);
ONEBOX_STATUS onebox_setclock(PONEBOX_ADAPTER adapter, uint32 Freq);
ONEBOX_STATUS onebox_abort_handler(PONEBOX_ADAPTER Adapter );
ONEBOX_STATUS onebox_init_sdio_slave_regs(PONEBOX_ADAPTER adapter);
ONEBOX_STATUS disable_sdio_interrupt(PONEBOX_ADAPTER adapter);
#ifdef USE_USB_INTF
uint8 process_usb_rcv_pkt(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_recv_pkt, uint8 pkt_type);
ONEBOX_STATUS onebox_ulp_reg_write (struct usb_device *usbdev, uint32 reg,uint16 value, uint16 len);
ONEBOX_STATUS onebox_ulp_reg_read (struct usb_device *usbdev, uint32 reg, uint16 * value, uint16 len);
void onebox_rx_done_handler (struct urb *urb);
#endif
#endif
<file_sep>/wlan/net80211/linux/osd_linux/include/cfg80211_wrapper.h
#include <net/cfg80211.h>
#include "cfg80211_ioctl.h"
#define ONEBOX_STATUS int
#define ONEBOX_STATUS_FAILURE -1
#define ONEBOX_STATUS_SUCCESS 0
#define DFL_FRAG_THRSH 2346
#define DFL_RTS_THRSH 2346
#define ETH_ADDR_LEN 6
#define MAX_CHANNELS_24GHZ 14
#define MAX_CHANNELS_5GHZ 25
#define IEEE80211_IOC_APPIE 95/* application IE's */
#define IEEE80211_FC0_TYPE_MGT 0x00
#define IEEE80211_FC0_SUBTYPE_PROBE_REQ 0x40
#define STD_RATE_MCS7 0x82
#define STD_RATE_MCS6 0x75
#define STD_RATE_MCS5 0x68
#define STD_RATE_MCS4 0x4E
#define STD_RATE_MCS3 0x34
#define STD_RATE_MCS2 0x27
#define STD_RATE_MCS1 0x1A
#define STD_RATE_MCS0 0x0D
#define STD_RATE_54 0x6c
#define STD_RATE_48 0x60
#define STD_RATE_36 0x48
#define STD_RATE_24 0x30
#define STD_RATE_18 0x24
#define STD_RATE_12 0x18
#define STD_RATE_11 0x16
#define STD_RATE_09 0x12
#define STD_RATE_06 0x0C
#define STD_RATE_5_5 0x0B
#define STD_RATE_02 0x04
#define STD_RATE_01 0x02
/* cipher suite selectors */
#define WLAN_CIPHER_SUITE_USE_GROUP 0x000FAC00
#define WLAN_CIPHER_SUITE_WEP40 0x000FAC01
#define WLAN_CIPHER_SUITE_TKIP 0x000FAC02
/* reserved: 0x000FAC03 */
#define WLAN_CIPHER_SUITE_CCMP 0x000FAC04
#define WLAN_CIPHER_SUITE_WEP104 0x000FAC05
#define WLAN_CIPHER_SUITE_AES_CMAC 0x000FAC06
static const u32 cipher_suites[] = {
WLAN_CIPHER_SUITE_WEP40,
WLAN_CIPHER_SUITE_WEP104,
WLAN_CIPHER_SUITE_TKIP,
WLAN_CIPHER_SUITE_CCMP,
};
enum ieee80211_roamingmode {
IEEE80211_ROAMING_DEVICE= 0, /* driver/hardware control */
IEEE80211_ROAMING_AUTO = 1, /* 802.11 layer control */
IEEE80211_ROAMING_MANUAL= 2, /* application control */
};
struct ieee80211_rate ;
static struct ieee80211_rate bg_rsi_rates[] = {
{ .bitrate = STD_RATE_01 * 5},
{ .bitrate = STD_RATE_02 * 5},
{ .bitrate = STD_RATE_5_5 * 5},
{ .bitrate = STD_RATE_11 * 5},
{ .bitrate = STD_RATE_06 * 5},
{ .bitrate = STD_RATE_09 * 5},
{ .bitrate = STD_RATE_12 * 5},
{ .bitrate = STD_RATE_18 * 5},
{ .bitrate = STD_RATE_24 * 5},
{ .bitrate = STD_RATE_36 * 5},
{ .bitrate = STD_RATE_48 * 5},
{ .bitrate = STD_RATE_54 * 5},
{ .bitrate = STD_RATE_MCS0 * 5},
{ .bitrate = STD_RATE_MCS1 * 5},
{ .bitrate = STD_RATE_MCS2 * 5},
{ .bitrate = STD_RATE_MCS3 * 5},
{ .bitrate = STD_RATE_MCS4 * 5},
{ .bitrate = STD_RATE_MCS5 * 5},
{ .bitrate = STD_RATE_MCS6 * 5},
{ .bitrate = STD_RATE_MCS7 * 5}
};
struct ieee80211_supported_band band_24ghz, band_5ghz;
struct ieee80211_channel channels_24ghz[MAX_CHANNELS_24GHZ], channels_5ghz[MAX_CHANNELS_5GHZ];
struct ieee80211_scan_req {
int sr_flags;
u_int sr_duration; /* duration (ms) */
u_int sr_mindwell; /* min channel dwelltime (ms) */
u_int sr_maxdwell; /* max channel dwelltime (ms) */
int sr_nssid;
#define IEEE80211_NWID_LEN 32
#define IEEE80211_IOC_SCAN_MAX_SSID 3
struct
{
uint8_t len; /* length in bytes */
uint8_t ssid[IEEE80211_NWID_LEN]; /* ssid contents */
} sr_ssid[IEEE80211_IOC_SCAN_MAX_SSID];
#define IEEE80211_MAX_FREQS_ALLOWED 25
//#define IEEE80211_MAX_FREQS_ALLOWED 32
//#ifdef ENABLE_P2P_SUPPORT
uint16_t num_freqs;
uint16_t freqs[IEEE80211_MAX_FREQS_ALLOWED];
//#endif
};
/* Function prototypes */
uint8_t cfg80211_wrapper_attach(struct net_device *dev, void *dev_ptr, int size);
void cfg80211_wrapper_free_wdev(struct wireless_dev *wdev);
#if(LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 38))
ONEBOX_STATUS
onebox_cfg80211_set_txpower(struct wiphy *wiphy, enum nl80211_tx_power_setting type, int dbm);
#endif
#if(LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 38))
ONEBOX_STATUS onebox_cfg80211_del_key(struct wiphy *wiphy, struct net_device *ndev, uint8_t index,
const uint8_t *mac_addr );
ONEBOX_STATUS onebox_cfg80211_add_key(struct wiphy *wiphy,struct net_device *ndev,
uint8_t index, const uint8_t *mac_addr, struct key_params *params);
#else
ONEBOX_STATUS onebox_cfg80211_del_key(struct wiphy *wiphy, struct net_device *ndev, uint8_t index,
bool pairwise, const uint8_t *mac_addr );
ONEBOX_STATUS onebox_cfg80211_add_key(struct wiphy *wiphy,struct net_device *ndev,
uint8_t index, bool pairwise, const uint8_t *mac_addr, struct key_params *params);
#endif
ONEBOX_STATUS
onebox_cfg80211_set_default_key(struct wiphy *wiphy, struct net_device *ndev, uint8_t index, bool unicast, bool multicast);
ONEBOX_STATUS
onebox_cfg80211_get_station(struct wiphy *wiphy, struct net_device *ndev, uint8_t *mac, struct station_info *info);
ONEBOX_STATUS
onebox_cfg80211_connect(struct wiphy *wiphy, struct net_device *ndev, struct cfg80211_connect_params *params);
ONEBOX_STATUS
onebox_cfg80211_disconnect(struct wiphy *wiphy, struct net_device *ndev, uint16_t reason_code);
ONEBOX_STATUS onebox_cfg80211_set_wiphy_params(struct wiphy *wiphy, uint32_t changed);
ONEBOX_STATUS
onebox_cfg80211_scan(struct wiphy *wiphy,struct net_device *ndev,
struct cfg80211_scan_request *request);
struct wireless_dev* onebox_register_wiphy_dev(struct device *dev, int size);
int cfg80211_scan(void *temp_req, struct net_device *ndev, uint8_t num_chn, uint16_t *chan,
const uint8_t *ie, size_t ie_len, int n_ssids, void *ssids);
<file_sep>/release/testing_iw.sh
i=100
ssid=$1
bssid=$2
echo "bssid is $bssid"
ifconfig vap0 up
while test $i != 0
do
echo "$i"
iw dev vap0 scan > log &
iw dev vap0 connect $ssid $bssid
while :
do
`iw dev vap0 link > /home/rsi/release/log`
state=`grep -ri "Connected to" /home/rsi/release/log | cut -f 1,2 -d " "`
#echo "$state"
#state=`./wpa_cli -i vap0 status | grep -ir "wpa_state" | cut -f 2 -d "="`
if [ "$state" == "Connected to" ]; then
echo connected to AP
break;
#else
#echo "Not connected.. Wait"
fi
done
dhclient vap0
echo "got the ip address"
ping 10.0.0.220 -A -s 30000 -c 20
i=`expr $i - 1`
pkill dhclient
iw dev vap0 disconnect
done
<file_sep>/release/zigb_remove.sh
rmmod onebox_zigb_gpl.ko
rmmod onebox_zigb_nongpl.ko
<file_sep>/zigbee/Makefile
#
# @file Makefile
# @author
# @version 1.0.0
#
# @section LICENSE
#
# This software embodies materials and concepts that are confidential to Redpine
# Signals and is made available solely pursuant to the terms of a written license
# agreement with Redpine Signals
#
# @section DESCRIPTION
#
# Top level Makefile for compiling the hal components.
#
DRV_DIR=$(ROOT_DIR)/zigbee
RELEASE_DIR=$(DRV_DIR)/../release
OSI_DIR=osi_zigb
OSD_DIR=osd_zigb/linux
include $(ROOT_DIR)/.config
include $(ROOT_DIR)/config/make.config
EXTRA_CFLAGS += -DLINUX -Wimplicit -Wstrict-prototypes
EXTRA_CFLAGS += -DFLASH_BURNING
EXTRA_CFLAGS += -DPWR_SAVE_SUPPORT
#EXTRA_CFLAGS += -DENABLE_40MHZ_SUPPORT
EXTRA_CFLAGS += -DBGSCAN_SUPPORT
#EXTRA_CFLAGS += -DONEBOX_DEBUG_ENABLE
#EXTRA_CFLAGS += -DAMPDU_AGGR_SUPPORT
#EXTRA_CFLAGS += -DCHIP_ENABLED
#EXTRA_CFLAGS += -DAUTO_RATE_SUPPORT
#EXTRA_CFLAGS += -DEEPROM_READ_EN
EXTRA_CFLAGS += -DRSI_SDIO_MULTI_BLOCK_SUPPORT
EXTRA_CFLAGS += -DSECURITY_SUPPORT
#EXTRA_CFLAGS += -DENABLE_P2P_SUPPORT
#EXTRA_CFLAGS += -DENABLE_PER_MODE
#EXTRA_CFLAGS += -DENABLE_40_MHZ
EXTRA_CFLAGS += -DDYNAMIC_VARIABLES
EXTRA_CFLAGS += -DRF_8111
#EXTRA_CFLAGS += -DEEPROM_NOT_PRESENT
#EXTRA_CFLAGS += -DDISABLE_TALOAD
EXTRA_CFLAGS += -I$(DRV_DIR)/include/linux
EXTRA_CFLAGS += -I$(ROOT_DIR)/common_hal/include/common
#EXTRA_CFLAGS += -DFPGA_VALIDATION
EXTRA_CFLAGS += -I$(NET80211_DIR)/osd_linux/include
EXTRA_CFLAGS += -g
ifeq ($(USE_DEVICE),"SDIO")
EXTRA_CFLAGS += -DUSE_SDIO_INTF
else
EXTRA_CFLAGS += -DUSE_USB_INTF
endif
OSI_OBJ := $(OSI_DIR)/onebox_zigb_osi_init.o \
$(OSI_DIR)/onebox_zigb_rx.o \
$(OSI_DIR)/onebox_zigb_tx.o \
$(OSI_DIR)/onebox_zigb.o \
$(OSI_DIR)/onebox_zigb_osi_callbacks.o \
OSD_OBJ := $(OSD_DIR)/onebox_zigb_ioctl.o \
$(OSD_DIR)/onebox_zigb_nl.o \
$(OSD_DIR)/onebox_zigb_osd_init.o \
$(OSD_DIR)/onebox_zigb_osd_callbacks.o \
$(OSD_DIR)/onebox_zigb_proc.o
NONGPL_OBJS := $(OSI_OBJ)
GPL_OBJS := $(OSD_OBJ)
obj-m := onebox_zigb_gpl.o
onebox_zigb_gpl-objs := $(GPL_OBJS)
obj-m += onebox_zigb_nongpl.o
onebox_zigb_nongpl-objs := $(NONGPL_OBJS)
all:
@echo "Compiling non gpl module"
@cp ../common_hal/Module.symvers .
make -C$(KERNELDIR) SUBDIRS=$(DRV_DIR) modules
clean:
@echo "- Cleaning All Object and Intermediate Files"
@find . -name '*.ko' | xargs rm -rf
@find . -name '*.order' | xargs rm -rf
@find . -name '*.symvers' | xargs rm -rf
@find . -name '*.markers' | xargs rm -rf
@find . -name '*.o' | xargs rm -f
@find . -name '.*.ko.cmd' | xargs rm -rf
@find . -name '.*.o.cmd' | xargs rm -rf
@find $(OSD_DIR) -name '*.o' | xargs rm -f
@find $(HOST_INTF_DIR) -name '.*.o.cmd' | xargs rm -rf
@find . -name '*.mod.c' | xargs rm -rf
@echo "- Done"
<file_sep>/wlan/net80211/linux/osd_linux/src/cfg80211_ioctl.c
#ifdef ONEBOX_CONFIG_CFG80211
#include<linux/kernel.h>
#include<net80211/ieee80211_var.h>
#include<net80211/ieee80211_ioctl.h>
#include<net80211/ieee80211_crypto.h>
#include<net80211/ieee80211.h>
#include "cfg80211_ioctl.h"
void *temp_vap;
int onebox_prepare_ioctl_cmd(struct ieee80211vap *vap, uint8_t type, const void *data, int val, int len )
{
struct ieee80211req *ireq;
ireq = kmalloc(sizeof(struct ieee80211req), GFP_KERNEL);
ireq->i_type = type;
ireq->i_data = (void *)data;
ireq->i_val = val;
ireq->i_len = len;
return ieee80211_ioctl_set80211(vap, 0, ireq);
}
uint8_t onebox_add_key(struct net_device *ndev, uint8_t index,
const uint8_t *mac_addr, struct ieee80211_key_params *params)
{
struct ieee80211vap *vap = netdev_priv(ndev);
struct ieee80211req_key wk;
memset(&wk, 0, sizeof(wk));
// printk("NL80211 : In %s LINE %d\n",__func__,__LINE__);
if (params->cipher == WPA_ALG_NONE)
{
if (mac_addr == NULL ||
memcmp(mac_addr, "\xff\xff\xff\xff\xff\xff",
IEEE80211_ADDR_LEN) == 0)
{
return onebox_delete_key(ndev, NULL, index);
}
else
{
return onebox_delete_key(ndev, mac_addr, index);
}
}
// printk("NL80211 : In %s LINE %d params->cipher %x index %d\n",__func__,__LINE__, params->cipher, index);
switch (params->cipher)
{
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
{
if(index > 3)
{
break;
}
wk.ik_type = IEEE80211_CIPHER_WEP;
break;
}
case WLAN_CIPHER_SUITE_TKIP:
{
wk.ik_type = IEEE80211_CIPHER_TKIP;
break;
}
case WLAN_CIPHER_SUITE_CCMP:
{
wk.ik_type = IEEE80211_CIPHER_AES_CCM;
break;
}
default:
printk("%s: unknown alg=%d", __func__, params->cipher);
return -1;
break;
}
wk.ik_flags = IEEE80211_KEY_RECV ;
wk.ik_flags |= IEEE80211_KEY_XMIT;
/**need to set the flag based on transmission**/
/*need to fix
if(set_tx)
wk.ik_flags |= IEEE80211_KEY_XMIT;*/
if (mac_addr == NULL)
{
memset(wk.ik_macaddr, 0xff, IEEE80211_ADDR_LEN);
wk.ik_keyix = index;
}
else
{
memcpy(wk.ik_macaddr, mac_addr, IEEE80211_ADDR_LEN);
}
if (memcmp(wk.ik_macaddr, "\xff\xff\xff\xff\xff\xff",
IEEE80211_ADDR_LEN) == 0)
{
wk.ik_flags |= IEEE80211_KEY_GROUP;
wk.ik_keyix = index;
}
else
{
wk.ik_keyix = index == 0 ? IEEE80211_KEYIX_NONE : index;
}
//if (wk.ik_keyix != IEEE80211_KEYIX_NONE && set_tx)/* need to fix */
if (wk.ik_keyix != IEEE80211_KEYIX_NONE )/* FIXME */
{
wk.ik_flags |= IEEE80211_KEY_DEFAULT;
}
wk.ik_keylen = params->key_len;
memcpy(&wk.ik_keyrsc, params->seq, params->seq_len);
memcpy(wk.ik_keydata, params->key, params->key_len);
// printk("NL80211 : In %s LINE %d\n",__func__,__LINE__);
if(onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_WPAKEY, (void *)&wk, 0, sizeof(wk)) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
uint8_t
onebox_delete_key(struct net_device *ndev, const uint8_t *mac_addr, uint8_t index)
{
struct ieee80211vap *vap = netdev_priv(ndev);
struct ieee80211req_del_key wk;
if (mac_addr == NULL)
{
//printk("%s: key_idx=%d", __func__, index);
wk.idk_keyix = index;
}
else
{
//printk("%s: addr=" MACSTR, __func__, MAC2STR(addr));
memcpy(wk.idk_macaddr, mac_addr, IEEE80211_ADDR_LEN);
wk.idk_keyix = (u_int8_t) IEEE80211_KEYIX_NONE; /* XXX */
}
if(onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_DELKEY, (void *)&wk, 0, sizeof(wk)) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
int cfg80211_disconnect(struct net_device *ndev, int reason_code)
{
struct ieee80211req_mlme mlme;
struct ieee80211vap *vap = netdev_priv(ndev);
memset(&mlme, 0, sizeof(mlme));
mlme.im_op = IEEE80211_MLME_DISASSOC;
mlme.im_reason = reason_code;
if(reason_code == 99)
{
printk("In %s and %d \n", __func__, __LINE__);
return 0;
}
printk("In %s Line %d recvd disconnect reason code %d\n", __func__, __LINE__, reason_code);
if(onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_MLME, &mlme, 0, sizeof(mlme)) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
uint8_t
onebox_siwfrag(struct iw_param *frag)
{
struct ieee80211vap *vap;
struct ieee80211req ireq;
vap = temp_vap;
if (frag->disabled)
{
ireq.i_val = 2346;
}
else if ((frag->value < 256) || (frag->value > 2346))
{
return -EINVAL;
}
else
{
ireq.i_val = (frag->value & ~0x1);
}
ireq.i_type = IEEE80211_IOC_FRAGTHRESHOLD;
// printk("NL80211 : In %s LINE %d \n",__func__,__LINE__);
return ieee80211_ioctl_set80211(vap, 0, &ireq);
}
uint8_t
onebox_siwrts(struct iw_param *rts)
{
struct ieee80211vap *vap;
struct ieee80211req ireq;
vap = temp_vap;
// printk("NL80211 : In %s and %d vap %p\n",__func__,__LINE__, vap);
if (rts->disabled)
{
ireq.i_val = IEEE80211_RTS_MAX;
}
else if ((IEEE80211_RTS_MIN <= rts->value) &&
(rts->value <= IEEE80211_RTS_MAX))
{
ireq.i_val = rts->value;
}
else
{
return -EINVAL;
}
// printk("NL80211 : In %s and %d vap %p val %d\n",__func__,__LINE__, vap, ireq.i_val);
ireq.i_type = IEEE80211_IOC_RTSTHRESHOLD;
return ieee80211_ioctl_set80211(vap, 0, &ireq);
}
uint8_t tx_power(int dbm)
{
struct ieee80211vap *vap;
struct ieee80211req ireq;
vap = temp_vap;
ireq.i_val = dbm;
ireq.i_type = IEEE80211_IOC_TXPOWER;
// printk("NL80211 : In %s and %d vap %p dbm %d\n",__func__,__LINE__, vap, dbm);
return ieee80211_ioctl_set80211(vap, 0, &ireq);
}
int
onebox_set_if_media(struct net_device *dev, int media)
{
struct ieee80211vap *vap = netdev_priv(dev);
struct ifreq ifr;
// printk("STAIOCTL: %s %d \n", __func__, __LINE__);
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_ifru.ifru_ivalue = media;
if(ifmedia_ioctl(vap->iv_ifp, (struct ifreq *)&ifr, &vap->iv_media, SIOCSIFMEDIA) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
int
onebox_get_if_media(struct net_device *dev)
{
struct ifmediareq ifmr;
struct ieee80211vap *vap = netdev_priv(dev);
// printk("STAIOCTL: %s %d \n", __func__, __LINE__);
memset(&ifmr, 0, sizeof(ifmr));
if(ifmedia_ioctl(vap->iv_ifp, (struct ifreq *)&ifmr, &vap->iv_media, SIOCGIFMEDIA) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
return ifmr.ifm_current;
}
int
onebox_set_mediaopt(struct net_device *dev, uint32_t mask, uint32_t mode)
{
int media = onebox_get_if_media(dev);
if (media < 0)
{
printk("NL80211 : In %s and %d\n",__func__,__LINE__);
return -1;
}
media &= ~mask;
media |= mode;
if (onebox_set_if_media(dev, media) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
int
onebox_driver_nl80211_set_wpa(struct ieee80211vap *vap, int enabled)
{
return onebox_driver_nl80211_set_wpa_internal(vap, enabled ? 3 : 0, enabled);
}
int
onebox_driver_nl80211_set_wpa_internal(struct ieee80211vap *vap, int wpa, int privacy)
{
if (!wpa && onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_APPIE, NULL, IEEE80211_APPIE_WPA, 0) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
if (onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_PRIVACY, NULL, privacy, 0) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
if (onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_WPA, NULL, wpa, 0) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
return ONEBOX_STATUS_SUCCESS;
}
#if 0
int nl80211_ctrl_iface(struct net_device *ndev, int enable)
{
struct ifreq *ifr;
memset(&ifr, 0, sizeof(ifr));
os_nl_strlcpy(ifr->ifr_name, ndev->name, sizeof(ifr->ifr_name));
if(enable)
{
ifr->ifr_flags |= IFF_UP;
}
else
{
ifr->ifr_flags &= ~IFF_UP;
}
if(ieee80211_ioctl(ndev, ifr, SIOCSIFFLAGS) < 0)
{
printk("Failed to set Ioctl SIOCSIFFLAGS\n");
return -1;
}
return 0;
}
#endif
int cfg80211_scan(void *temp_req, struct net_device *ndev, uint8_t num_ch, uint16_t *chans,
const uint8_t *ie, size_t ie_len, int n_ssids, void *ssid)
{
struct ieee80211_ssid *ssids = (struct ieee80211_ssid *)ssid;
struct ieee80211vap *vap = netdev_priv(ndev);
struct ieee80211_scan_req sr;
uint8_t i;
temp_vap = vap;
memset(&sr, 0, sizeof(sr));
if(vap->iv_state == IEEE80211_S_RUN) //Fix made for bgscan
{
printk("NL80211 : In %s and %d \n" , __func__, __LINE__);
scan_done(scan_request, NULL);
return 0;
}
if(onebox_set_mediaopt(ndev, IFM_OMASK, 0))
{
printk("Failed to set operation mode\n");
return -1;
}
if(onebox_set_mediaopt(ndev, IFM_MMASK, 0))
{
printk("Failed to set modulation mode\n");
return -1;
}
if(onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_ROAMING, NULL, IEEE80211_ROAMING_AUTO, 0) < 0)
{
printk("Roaming Ioctl Not set\n");
return -1;
}
if(onebox_driver_nl80211_set_wpa(vap, 1) < 0)
{
printk("Failed to set WPA\n");
return -1;
}
#if 0
if(nl80211_ctrl_iface(ndev, 1) < 0)
{
printk("Failed to set interafce \n");
return -1;
}
#endif
if(ie && ie_len)
{
if(onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_APPIE, ie,
(IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ), ie_len) < 0)
{
printk("IE Ioctl not set\n");
return -1;
}
}
sr.sr_flags = IEEE80211_IOC_SCAN_ACTIVE | IEEE80211_IOC_SCAN_ONCE | IEEE80211_IOC_SCAN_NOJOIN;
sr.sr_duration = IEEE80211_IOC_SCAN_FOREVER;
if(n_ssids > 0)
{
sr.sr_nssid = n_ssids;
sr.sr_flags |= IEEE80211_IOC_SCAN_CHECK;
}
for (i = 0; i < sr.sr_nssid; i++)
{
sr.sr_ssid[i].len = ssids->ssid_len;
memcpy(sr.sr_ssid[i].ssid, ssids->ssid, sr.sr_ssid[i].len);
}
if(num_ch)
{
sr.num_freqs = num_ch;
for(i = 0; i < num_ch; i++)
{
sr.freqs[i] = chans[i];
printk("Scanning Selective channels mentioned by user %d\n", sr.freqs[i]);
}
}
else
{
sr.num_freqs = 0;
printk("Scanning All channels\n");
}
vap->scan_request = temp_req;
if(onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_SCAN_REQ, (void *)&sr, 0, sizeof(sr)) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
size_t os_nl_strlcpy(char *dest, const char *src, size_t siz)
{
const char *s = src;
size_t left = siz;
if (left) {
/* Copy string up to the maximum size of the dest buffer */
while (--left != 0) {
if ((*dest++ = *s++) == '\0')
break;
}
}
if (left == 0) {
/* Not enough room for the string; force NUL-termination */
if (siz != 0)
*dest = '\0';
while (*s++)
; /* determine total src string length */
}
return s - src - 1;
}
int cfg80211_inform_scan_results(void *arg, void *se_nl)
{
struct ieee80211vap *vap;
struct ieee80211_scan_entry *nl = (struct ieee80211_scan_entry *)se_nl;
unsigned char ssid[6];
unsigned short val, cap_info;
//int signal;
int chno;
int binfo_len;
struct ieee80211_channel *channel;
struct wireless_dev *wdev;
channel = NULL;
vap = temp_vap;
wdev = vap->wdev;
nl80211_memcp(ssid, nl->se_bssid, 6);
val = nl->se_intval;
cap_info = nl->se_capinfo;
channel = nl->se_chan;
// signal = nl->se_rssi;
chno = nl->se_chan->ic_ieee;
binfo_len = nl->se_ies.len;
// printk("NL80211 : In %s and %d vap %p temp_vap %p\n",__func__,__LINE__,vap, temp_vap);
// printk("NL80211 : In %s and %d wdev %p ssid %s val %d cap_info %d binfo_len %d\n",__func__,__LINE__,wdev, ssid, val, cap_info, binfo_len);
if(scan_results_sup(wdev, ssid, val, cap_info, channel, chno, nl->se_ies.data, binfo_len, nl->se_ssid) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
int scan_completed(struct ieee80211vap *vap)
{
if(vap->scan_request)
{
void *temp_scan_req;
temp_scan_req = vap->scan_request;
scan_done(temp_scan_req);
vap->scan_request = NULL;
return ONEBOX_STATUS_SUCCESS;
}
return -1;
}
void* nl80211_memcp(void *to, const void *from, int len)
{
return memcpy(to, from, len);
}
int cfg80211_connect_result_vap(struct ieee80211vap *vap, uint8_t mac[6])
{
struct wireless_dev *wdev = vap->wdev;
// printk("NL80211 : In %s and %d wdev %p\n",__func__,__LINE__, wdev);
connection_confirm(wdev, mac);
return ONEBOX_STATUS_SUCCESS;
}
int cfg80211_disconnect_result_vap(struct ieee80211vap *vap)
{
struct wireless_dev *wdev = vap->wdev;
disconnection_confirm(wdev);
return ONEBOX_STATUS_SUCCESS;
}
uint8_t onebox_wep_key(struct net_device *ndev, int index, uint8_t *mac_addr, uint8_t key_len, const uint8_t *key)
{
struct ieee80211vap *vap = netdev_priv(ndev);
struct ieee80211req_key wk;
memset(&wk, 0, sizeof(wk));
// printk("NL80211 : In %s LINE %d\n",__func__,__LINE__);
wk.ik_type = IEEE80211_CIPHER_WEP;
wk.ik_flags = IEEE80211_KEY_RECV ;
wk.ik_flags |= IEEE80211_KEY_XMIT;
/**need to set the flag based on transmission**/
/*need to fix
if(set_tx)
wk.ik_flags |= IEEE80211_KEY_XMIT;*/
printk("ASSOC CMD: In %s and %d mac_addr = %02x:%02x:%02x:%02x:%02x:%02x \n", __func__, __LINE__, mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
mac_addr = NULL;
if (mac_addr == NULL)
{
memset(wk.ik_macaddr, 0xff, IEEE80211_ADDR_LEN);
wk.ik_keyix = index;
}
else
{
memcpy(wk.ik_macaddr, mac_addr, IEEE80211_ADDR_LEN);
}
/*
* Deduce whether group/global or unicast key by checking
* the address (yech). Note also that we can only mark global
* keys default; doing this for a unicast key is an error.
*/
if (memcmp(wk.ik_macaddr, "\xff\xff\xff\xff\xff\xff",
IEEE80211_ADDR_LEN) == 0) {
wk.ik_flags |= IEEE80211_KEY_GROUP;
wk.ik_keyix = index;
} else {
wk.ik_keyix = index == 0 ? IEEE80211_KEYIX_NONE :
index;
}
//if (wk.ik_keyix != IEEE80211_KEYIX_NONE && set_tx)/* need to fix */
if (wk.ik_keyix != IEEE80211_KEYIX_NONE )/* need to fix */
wk.ik_flags |= IEEE80211_KEY_DEFAULT;
wk.ik_keylen = key_len;
// memcpy(&wk.ik_keyrsc, params->seq, params->seq_len);
memcpy(wk.ik_keydata, key, key_len);
// printk("NL80211 : In %s LINE %d\n",__func__,__LINE__);
if(onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_WPAKEY, (void *)&wk, 0, sizeof(wk)) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
int cfg80211_connect_res(struct net_device *ndev, int auth, const uint8_t *ie, size_t ie_len, unsigned char *ssid,
size_t ssid_len, unsigned char *bssid, int len, int privacy)
{
struct ieee80211vap *vap;
struct ieee80211req_mlme mlme;
int authmode;
vap = netdev_priv(ndev);
if(onebox_set_mediaopt(ndev, IFM_OMASK, 0) < 0)
{
printk("Failed to set Operation mode\n");
return -1;
}
if ((auth & WPA_AUTH_ALG_OPEN) &&
(auth & WPA_AUTH_ALG_SHARED))
{
authmode = IEEE80211_AUTH_AUTO;
}
else if (auth & WPA_AUTH_ALG_SHARED)
{
authmode = IEEE80211_AUTH_SHARED;
}
else
{
authmode = IEEE80211_AUTH_OPEN;
}
if(onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_AUTHMODE, NULL, authmode, 0) < 0)
{
printk("Authmode Not set\n");
return -1;
}
if(onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_APPIE, ie, IEEE80211_APPIE_WPA, ie_len) < 0)
{
printk("Appie Ioctl Not set\n");
return -1;
}
if(onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_PRIVACY, NULL, privacy, 0) < 0)
{
printk("Privacy Ioctl Not set\n");
return -1;
}
if((ie_len && onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_WPA, NULL, ie[0] == 48 ? 2 : 1, 0)) < 0)
{
printk("WPA Ioctl Not set\n");
return -1;
}
if(((ssid != NULL) && onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_SSID, ssid, 0, ssid_len)) < 0)
{
printk("SSID Ioctl Not set\n");
return -1;
}
memset(&mlme, 0, sizeof(mlme));
mlme.im_op = IEEE80211_MLME_ASSOC;
if(ssid != NULL)
{
memcpy(mlme.im_ssid, ssid, len);
}
if(bssid != NULL)
{
memcpy(mlme.im_macaddr, bssid, 6);
}
mlme.im_ssid_len = len;
if(onebox_prepare_ioctl_cmd(vap, IEEE80211_IOC_MLME, &mlme, 0, sizeof(mlme)) < 0)
{
printk("MLME Ioctl Not set\n");
return -1;
}
return 0;
}
#endif
<file_sep>/bt/osi_bt/onebox_bt.c
#include "onebox_core.h"
int32 bt_core_pkt_recv(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb)
{
ONEBOX_STATUS status;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("%s: sending to APP len %d, pkttype %d\n"),
__func__, netbuf_cb->len, netbuf_cb->bt_pkt_type));
status = adapter->osd_bt_ops->onebox_send_pkt_to_btstack(adapter, netbuf_cb);
return status;
}
int32 core_bt_init(PONEBOX_ADAPTER adapter)
{
int8 rc = -1;
adapter->os_intf_ops->onebox_netbuf_queue_init(&adapter->bt_tx_queue);
rc = adapter->osd_bt_ops->onebox_btstack_init(adapter);
if (rc) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: btstack_init fail %d\n"),__func__, rc));
return ONEBOX_STATUS_FAILURE;
}
adapter->core_init_done = 1;
return ONEBOX_STATUS_SUCCESS;
}
int32 core_bt_deinit(PONEBOX_ADAPTER adapter)
{
adapter->core_init_done = 0;
adapter->os_intf_ops->onebox_queue_purge(&adapter->bt_tx_queue);
adapter->osd_bt_ops->onebox_btstack_deinit(adapter);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Uninitialized Procfs\n"), __func__));
return ONEBOX_STATUS_SUCCESS;
}
int32 bt_xmit(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb)
{
/* Drop Zero Length Packets */
if (!netbuf_cb->len) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s:Zero Length packet\n"),__func__));
goto xmit_fail;
}
/* Drop Packets if FSM state is not open */
if (adapter->fsm_state != FSM_DEVICE_READY) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: FSM state not open\n"),__func__));
goto xmit_fail;
}
adapter->osi_bt_ops->onebox_send_pkt(adapter, netbuf_cb);
return ONEBOX_STATUS_SUCCESS;
xmit_fail:
adapter->stats.tx_dropped++;
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s:Failed to xmit packet\n"),__func__));
if (netbuf_cb) {
adapter->os_intf_ops->onebox_free_pkt(adapter,netbuf_cb,0);
}
return ONEBOX_STATUS_SUCCESS;
}
int core_bt_deque_pkts(PONEBOX_ADAPTER adapter)
{
netbuf_ctrl_block_t *netbuf_cb;
while(adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->bt_tx_queue))
{
netbuf_cb = adapter->os_intf_ops->onebox_dequeue_pkt((void *)&adapter->bt_tx_queue);
if(netbuf_cb == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("queue is empty but length is not zero in %s"), __func__));
return ONEBOX_STATUS_FAILURE;
}
adapter->osi_bt_ops->onebox_send_pkt(adapter, netbuf_cb);
}
return ONEBOX_STATUS_SUCCESS;
}
/**
* This routine dump the given data through the debugger..
*
* @param Debug zone.
* @param Pointer to data that has to dump.
* @param Length of the data to dump.
* @return VOID.
*/
void onebox_print_dump(int32 zone, UCHAR *vdata, int32 len)
{
uint16 ii;
if(!zone || !(zone & onebox_bt_zone_enabled))
return;
for (ii=0; ii< len; ii++) {
if (!(ii % 16) && ii) {
//ONEBOX_DEBUG(zone, (TEXT("\n%04d: "), ii));
ONEBOX_DEBUG(zone, (TEXT("\n")));
}
ONEBOX_DEBUG(zone,(TEXT("%02x "),(vdata[ii])));
}
ONEBOX_DEBUG(zone, (TEXT("\n")));
}
<file_sep>/release/wlan_remove.sh
#service dhcpd stop
#pkill dhcpd
#pkill dhclient
#ifconfig wifi0 down
killall -9 wpa_supplicant
killall -9 hostapd
sleep 2
rmmod onebox_wlan_gpl.ko
rmmod onebox_wlan_nongpl.ko
rmmod wlan_scan_sta.ko
rmmod wlan_xauth.ko
rmmod wlan_acl.ko
rmmod wlan_tkip.ko
rmmod wlan_ccmp.ko
rmmod wlan_wep.ko
rmmod wlan.ko
<file_sep>/common_hal/include/common/onebox_coex.h
/**
* @file onebox_coex.h
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contians the data structures and variables/ macros commonly
* used across all protocols .
*/
#ifndef __ONEBOX_COEX_H__
#define __ONEBOX_COEX_H__
#define GS_CARD_DETACH 0 /* card status */
#define GS_CARD_ABOARD 1
/**
* MODULE_REMOVED:
* modules are not installed or the modules are
* uninstalled after an installation.
*
* MODULE_INSERTED:
* modules are installled and the layer is not yet initialised.
* or the layer is deinitialized.
*
* MODULE_ACTIVE:
* modules are installed and the layer is initialised.
*
*/
#define MODULE_REMOVED 0
#define MODULE_INSERTED 1
#define MODULE_ACTIVE 2
#define FW_INACTIVE 0
#define FW_ACTIVE 1
#define BT_CARD_READY_IND 0x89
#define WLAN_CARD_READY_IND 0x0
#define ZIGB_CARD_READY_IND 0xff
#define COEX_Q 0
#define BT_Q 1
#define WLAN_Q 2
#define VIP_Q 3
#define ZIGB_Q 4
#define COEX_TX_Q 0
#define ZIGB_TX_Q 1
#define BT_TX_Q 2
#define WLAN_TX_M_Q 4
#define WLAN_TX_D_Q 5
#define COEX_PKT 0
#define ZIGB_PKT 1
#define BT_PKT 2
#define WLAN_PKT 3
#define MAX_IDS 3
#define WLAN_ID 0
#define BT_ID 1
#define ZB_ID 2
#define ASSET_NAME(id) \
(id == WLAN_ID) ? "wlan_asset" : \
((id == BT_ID) ? "bluetooth_asset" : \
((id == ZB_ID) ? "zigbee_asset" : "null"))
#define COMMAN_HAL_WAIT_FOR_CARD_READY 1
#define COMMON_HAL_SEND_CONFIG_PARAMS 2
#define COMMON_HAL_TX_ACESS 3
struct driver_assets {
uint32 card_state;
uint16 ta_aggr;
uint8 asset_role;
struct wireless_techs {
uint32 drv_state;
uint32 fw_state;
#ifdef USE_USB_INTF
uint32 buffer_status_reg_addr;
#endif
int32 (*inaugurate)(void);
int32 (*disconnect)(void);
ONEBOX_STATUS (*onebox_get_pkt_from_coex)(netbuf_ctrl_block_t *netbuf_cb);
ONEBOX_STATUS (*onebox_get_buf_status)(uint8 buf_status);
ONEBOX_STATUS (*onebox_get_ulp_sleep_status)(uint8 sleep_status);
void (*wlan_dump_mgmt_pending)(void);//remove me after coex optimisations
bool tx_intention;
bool tx_access; /* Per protocol tx access */
uint8 deregister_flags;
struct __wait_queue_head deregister_event;
void *priv;
uint32 default_ps_en;
} techs[MAX_IDS];
void *global_priv;
void *pfunc;
bool common_hal_tx_access;
bool sleep_entry_recvd;
bool ulp_sleep_ack_sent;
struct semaphore tx_access_lock;
struct semaphore wlan_init_lock;
struct semaphore bt_init_lock;
struct semaphore zigbee_init_lock;
void (*update_tx_status)(uint8 prot_id);
uint32 common_hal_fsm;
uint8 lp_ps_handshake_mode;
uint8 ulp_ps_handshake_mode;
uint8 rf_power_val;
uint8 device_gpio_type;
};
#define WLAN_TECH d_assets->techs[WLAN_ID]
#define BT_TECH d_assets->techs[BT_ID]
#define ZB_TECH d_assets->techs[ZB_ID]
extern struct driver_assets d_assets;
struct driver_assets *onebox_get_driver_asset(void);
/*
* Generic Netlink Sockets
*/
struct genl_cb {
uint8 gc_cmd, *gc_name;
int32 gc_seq, gc_pid;
int32 gc_assetid, gc_done;
int32 gc_n_ops;
void *gc_drvpriv;
struct nla_policy *gc_policy;
struct genl_family *gc_family;
struct genl_ops *gc_ops;
struct genl_info *gc_info;
struct sk_buff *gc_skb;
};
#if LINUX_VERSION_CODE <= KERNEL_VERSION(3, 6, 11)
# define get_portid(_info) (_info)->snd_pid
#else
# define get_portid(_info) (_info)->snd_portid
#endif
/*==========================================================/
* attributes (variables): the index in this enum is
* used as a reference for the type, userspace application
* has to indicate the corresponding type the policy is
* used for security considerations
*==========================================================*/
enum {
RSI_USER_A_UNSPEC,
RSI_USER_A_MSG,
__RSI_USER_A_MAX,
};
/*=================================================================/
* commands: enumeration of all commands (functions),
* used by userspace application to identify command to be executed
*=================================================================*/
enum {
RSI_USER_C_UNSPEC,
RSI_USER_C_CMD,
__RSI_USER_C_MAX,
};
#define RSI_USER_A_MAX (__RSI_USER_A_MAX - 1)
#define RSI_VERSION_NR 1
#endif
<file_sep>/release/host_ap.sh
sh wlan_insert.sh
./onebox_util rpine0 create_vap wifi1 ap
#sh form_bridge.sh
sleep 1
if [ "$1" == "" ]; then
echo "please specify a config file"
echo "example: sh host_ap.sh ap hostapd_open.conf"
else
./hostapd $1 -dddddtK > log_hap &
fi
<file_sep>/bt/osd_bt/linux/onebox_bt_osd_init.c
/**
* @file onebox_osd_main.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contains all the Linux network device specific code.
*/
#include "onebox_common.h"
#include "onebox_linux.h"
#include "onebox_sdio_intf.h"
static PONEBOX_ADAPTER adapter;
static ONEBOX_STATUS bt_gpl_read_pkt(netbuf_ctrl_block_t *netbuf_cb)
{
struct driver_assets *d_assets = onebox_get_driver_asset();
PONEBOX_ADAPTER b_adapter = (PONEBOX_ADAPTER)d_assets->techs[BT_ID].priv;
b_adapter->os_intf_ops->onebox_acquire_sem(&b_adapter->bt_gpl_lock, 0);
if (d_assets->techs[BT_ID].drv_state == MODULE_ACTIVE) {
bt_read_pkt(b_adapter, netbuf_cb);
} else {
printk("WLAN is being removed.. Dropping Pkt\n");
b_adapter->os_intf_ops->onebox_free_pkt(b_adapter, netbuf_cb, 0);
netbuf_cb = NULL;
}
b_adapter->os_intf_ops->onebox_release_sem(&b_adapter->bt_gpl_lock);
return ONEBOX_STATUS_SUCCESS;
}
/*
* This function deregisters BT firmware
* @param Pointer to adapter structure.
* @return 0 if success else -1.
*/
static ONEBOX_STATUS bt_deregister_fw(PONEBOX_ADAPTER adapter)
{
uint16 *frame_desc;
uint16 pkt_len;
netbuf_ctrl_block_t *netbuf_cb = NULL;
ONEBOX_STATUS status = ONEBOX_STATUS_SUCCESS;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("===> Deregister BT FW <===\n")));
netbuf_cb = adapter->os_intf_ops->onebox_alloc_skb(FRAME_DESC_SZ);
if(netbuf_cb == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: Unable to allocate skb\n"), __func__));
status = ONEBOX_STATUS_FAILURE;
return status;
}
adapter->os_intf_ops->onebox_add_data_to_skb(netbuf_cb, FRAME_DESC_SZ);
adapter->os_intf_ops->onebox_memset(netbuf_cb->data, 0, FRAME_DESC_SZ);
frame_desc = (uint16 *)netbuf_cb->data;
/* packet length without descriptor */
pkt_len = netbuf_cb->len - FRAME_DESC_SZ;
/* Assigning packet length */
frame_desc[0] = pkt_len & 0xFFF;
/* Assigning queue number */
frame_desc[0] |= (ONEBOX_CPU_TO_LE16(BT_INT_MGMT_Q) & 0x7) << 12;
/* Assigning packet type in Last word */
frame_desc[7] = ONEBOX_CPU_TO_LE16(BT_DEREGISTER);
netbuf_cb->tx_pkt_type = BT_TX_Q;
adapter->osi_bt_ops->onebox_dump(ONEBOX_ZONE_ERROR, netbuf_cb->data, FRAME_DESC_SZ);
status = adapter->onebox_send_pkt_to_coex(netbuf_cb, VIP_Q);
if (status != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT
("%s: Failed To Write The Packet\n"),__func__));
}
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
return status;
}
/**
* This function is triggered whenever BT module is
* inserted. Links BT module with common hal module
* @params void
* @return ONEBOX_STATUS_SUCCESS on success else ONEBOX_STATUS_FAILURE
*/
static int32 bt_insert(void)
{
int32 rc = 0;
struct onebox_osi_host_intf_operations *osi_host_intf_ops =
onebox_get_osi_host_intf_operations();
struct onebox_osd_host_intf_operations *osd_host_intf_ops =
onebox_get_osd_host_intf_operations();
struct onebox_os_intf_operations *os_intf_ops =
onebox_get_os_intf_operations();
struct onebox_bt_osd_operations *osd_bt_ops =
onebox_get_bt_osd_operations_from_origin();
struct onebox_osi_bt_ops *osi_bt_ops =
onebox_get_osi_bt_ops();
struct driver_assets *d_assets =
onebox_get_driver_asset();
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Initialization function called\n"), __func__));
os_intf_ops->onebox_acquire_sem(&d_assets->bt_init_lock, 0);
if(d_assets->techs[BT_ID].drv_state == MODULE_ACTIVE) {
printk("In %s Line %d BT Module is already initialized\n", __func__, __LINE__);
os_intf_ops->onebox_release_sem(&d_assets->bt_init_lock);
return ONEBOX_STATUS_SUCCESS;
}
if ((sizeof(ONEBOX_ADAPTER) % 32))
printk("size of onebox adapter is not 32 byte aligned\n");
adapter = os_intf_ops->onebox_mem_zalloc(sizeof(ONEBOX_ADAPTER), GFP_KERNEL);
if (!adapter) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s:Memory allocation for adapter failed\n"), __func__));
goto nomem;
}
os_intf_ops->onebox_memset(adapter, 0, sizeof(ONEBOX_ADAPTER));
/* Initialise the Core and device dependent operations */
adapter->osd_host_intf_ops = osd_host_intf_ops;
adapter->osi_host_intf_ops = osi_host_intf_ops;
adapter->os_intf_ops = os_intf_ops;
adapter->osd_bt_ops = osd_bt_ops;
adapter->osi_bt_ops = osi_bt_ops;
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Mutex init successfull\n"), __func__));
os_intf_ops->onebox_init_dyn_mutex(&adapter->bt_gpl_lock);
d_assets->techs[BT_ID].priv = (void *)adapter;
adapter->onebox_send_pkt_to_coex = send_pkt_to_coex;
os_intf_ops->onebox_strcpy(adapter->name, "onebox_bt");
adapter->fsm_state = FSM_DEVICE_READY;
rc = adapter->osi_bt_ops->onebox_core_init(adapter);
if (rc) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("%s: BT core init failed\n"), __func__));
goto nocoreinit;
}
init_waitqueue_head(&d_assets->techs[BT_ID].deregister_event);
d_assets->techs[BT_ID].default_ps_en = 1;
d_assets->techs[BT_ID].drv_state = MODULE_ACTIVE;
if (setup_bt_procfs(adapter))
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("%s: Failed to setup BT procfs entry\n"), __func__));
os_intf_ops->onebox_release_sem(&d_assets->bt_init_lock);
return ONEBOX_STATUS_SUCCESS;
nocoreinit:
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("%s: Failed to initialize BT error[%d]\n"), __func__, rc));
os_intf_ops->onebox_mem_free(adapter);
nomem:
os_intf_ops->onebox_release_sem(&d_assets->bt_init_lock);
return ONEBOX_STATUS_FAILURE;
}/* End <bt_insert> */
/**
* This function removes the wlan module safely..
*
* @param Pointer to sdio_func structure.
* @param Pointer to sdio_device_id structure.
* @return VOID.
*/
static int32 bt_remove(void)
{
int32 rc = 0;
struct onebox_os_intf_operations *os_intf_ops = onebox_get_os_intf_operations();
struct driver_assets *d_assets = onebox_get_driver_asset();
struct wireless_techs *bt_d;
adapter->os_intf_ops->onebox_acquire_sem(&adapter->bt_gpl_lock, 0);
FUNCTION_ENTRY(ONEBOX_ZONE_INFO);
if (d_assets->card_state != GS_CARD_DETACH) {
bt_d = &d_assets->techs[BT_ID];
bt_d->tx_intention = 1;
d_assets->update_tx_status(BT_ID);
if(!bt_d->tx_access) {
d_assets->techs[BT_ID].deregister_flags = 1;
if(wait_event_timeout((bt_d->deregister_event),
(d_assets->techs[BT_ID].deregister_flags == 0),
msecs_to_jiffies(6000))) {
bt_deregister_fw(adapter);
} else {
printk("Failed to get sleep exit\n");
}
} else
bt_deregister_fw(adapter);
BT_TECH.tx_intention = 0;
BT_TECH.tx_access = 0;
d_assets->update_tx_status(BT_ID);
}
d_assets->techs[BT_ID].fw_state = FW_INACTIVE;
destroy_bt_procfs();
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: calling core deinitialization\n"), __func__));
rc = adapter->osi_bt_ops->onebox_core_deinit(adapter);
if (rc)
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: failed to deinit BT, error[%d]\n"), __func__, rc));
adapter->os_intf_ops->onebox_release_sem(&adapter->bt_gpl_lock);
os_intf_ops->onebox_mem_free(adapter);
FUNCTION_EXIT(ONEBOX_ZONE_INFO);
return ONEBOX_STATUS_SUCCESS;
}/* End <bt_remove> */
ONEBOX_STATIC int32 onebox_bt_gpl_module_init(VOID)
{
int32 rc = 0;
struct driver_assets *d_assets =
onebox_get_driver_asset();
d_assets->techs[BT_ID].drv_state = MODULE_INSERTED;
d_assets->techs[BT_ID].inaugurate = bt_insert;
d_assets->techs[BT_ID].disconnect = bt_remove;
d_assets->techs[BT_ID].onebox_get_pkt_from_coex = bt_gpl_read_pkt;
if (d_assets->card_state == GS_CARD_ABOARD) {
if(d_assets->techs[BT_ID].fw_state == FW_ACTIVE) {
rc = bt_insert();
if (rc) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT ("%s: failed to insert "
"bt error[%d]\n"),__func__, rc));
return 0;
}
}
}
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("onebox_btgpl_module_init called and registering the gpl driver\n")));
return 0;
}
ONEBOX_STATIC VOID onebox_bt_gpl_module_exit(VOID)
{
struct driver_assets *d_assets =
onebox_get_driver_asset();
printk("BT : GPL module exit\n");
if (d_assets->techs[BT_ID].drv_state == MODULE_ACTIVE) {
bt_remove();
}
d_assets->techs[BT_ID].drv_state = MODULE_REMOVED;
d_assets->techs[BT_ID].inaugurate = NULL;
d_assets->techs[BT_ID].disconnect = NULL;
d_assets->techs[BT_ID].onebox_get_pkt_from_coex = NULL;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("onebox_btgpl_module_exit called and unregistering the gpl driver\n")));
return;
}
module_init(onebox_bt_gpl_module_init);
module_exit(onebox_bt_gpl_module_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Redpine Signals Inc");
MODULE_DESCRIPTION("Co-Existance solution from REDPINE SIGNALS");
MODULE_SUPPORTED_DEVICE("Godavari RS911x WLAN Modules");
MODULE_VERSION("0.1");
<file_sep>/release/testing_install_uninstall.sh
i=1000
while test $i != 0
do
echo "$i"
sh remove.sh
sh insert.sh
./onebox_util rpine0 create_vap vap0 sta no_sta_beacons
./wpa_supplicant -i vap0 -D nl80211 -c sta_settings.conf -dddddt > wpa_log &
while :
do
`iw dev vap0 link > /home/rsi/release/log`
state=`grep -ri "Connected to" /home/rsi/release/log | cut -f 1,2 -d " "`
#echo "$state"
#state=`./wpa_cli -i vap0 status | grep -ir "wpa_state" | cut -f 2 -d "="`
if [ "$state" == "Connected to" ]; then
echo connected to AP
break;
fi
done
dhclient vap0
echo "got the ip address"
ifconfig vap0
#ping 10.0.0.220 -A -s 30000 -c 20
i=`expr $i - 1`
done
<file_sep>/release/remove_all.sh
#service dhcpd stop
#pkill dhcpd
#pkill dhclient
#ifconfig wifi0 down
killall -9 wpa_supplicant
killall -9 hostapd
rm -rf /var/run/wpa_supplicant/
sleep 2
rmmod onebox_zigb_gpl.ko
rmmod onebox_zigb_nongpl.ko
rmmod onebox_bt_gpl.ko
rmmod onebox_bt_nongpl.ko
rmmod onebox_wlan_gpl.ko
rmmod onebox_wlan_nongpl.ko
rmmod wlan_scan_sta.ko
rmmod wlan_xauth.ko
rmmod wlan_acl.ko
rmmod wlan_tkip.ko
rmmod wlan_ccmp.ko
rmmod wlan_wep.ko
rmmod wlan.ko
rmmod onebox_gpl.ko
rmmod onebox_nongpl.ko
<file_sep>/release/common_insert.sh
cat /dev/null > /var/log/messages
#dmesg -c > /dev/null
#sh dump_msg.sh &
#dmesg -n 7
#Driver Mode 1 END-TO-END mode,
# 2 RF Evaluation Mode
DRIVER_MODE=1
#COEX MODE 1 WIFI ALONE
# 2 WIFI+BT Classic
# 3 WIFI+ZIGBEE
# 4 WIFI+BT LE (Low Engergy)
COEX_MODE=1
#To enable TA-level SDIO aggregation set 1 else set 0 to disable it.
TA_AGGR=4
#Disable Firmware load set 1 to skip FW loading through Driver else set to 0.
SKIP_FW_LOAD=0
#FW Download Mode
# 1 - Full Flash mode with Secondary Boot Loader
# 2 - Full RAM mode with Secondary Boot Loader
# 3 - Flash + RAM mode with Secondary Boot Loader
# 4 - Firmware loading WITHOUT Secondary Boot Loader
# Recommended to use the default mode 1
FW_LOAD_MODE=1
#ps_handshake_mode
# 1 - No hand shake Mode
# 2 - Packet hand shake Mode
# 3 - GPIO Hand shake Mode
###########Default is Packet handshake mode=2
HANDSHAKE_MODE=2
PARAMS=" driver_mode=$DRIVER_MODE"
PARAMS=$PARAMS" firmware_path=$PWD/firmware/"
PARAMS=$PARAMS" onebox_zone_enabled=0x1"
PARAMS=$PARAMS" coex_mode=$COEX_MODE"
PARAMS=$PARAMS" ta_aggr=$TA_AGGR"
PARAMS=$PARAMS" skip_fw_load=$SKIP_FW_LOAD"
PARAMS=$PARAMS" fw_load_mode=$FW_LOAD_MODE"
#PARAMS=$PARAMS" ps_handshake_mode=$HANDSHAKE_MODE"
insmod onebox_nongpl.ko $PARAMS
insmod onebox_gpl.ko
<file_sep>/bt/osi_bt/onebox_bt_osi_init.c
#include <linux/module.h>
#include <linux/kernel.h>
#include "onebox_datatypes.h"
#include "onebox_common.h"
uint32 onebox_bt_zone_enabled = ONEBOX_ZONE_INFO |
ONEBOX_ZONE_INIT |
ONEBOX_ZONE_OID |
ONEBOX_ZONE_MGMT_SEND |
ONEBOX_ZONE_MGMT_RCV |
ONEBOX_ZONE_DATA_SEND |
ONEBOX_ZONE_DATA_RCV |
ONEBOX_ZONE_FSM |
ONEBOX_ZONE_ISR |
ONEBOX_ZONE_MGMT_DUMP |
ONEBOX_ZONE_DATA_DUMP |
ONEBOX_ZONE_DEBUG |
ONEBOX_ZONE_AUTORATE |
ONEBOX_ZONE_PWR_SAVE |
ONEBOX_ZONE_ERROR |
0;
EXPORT_SYMBOL(onebox_bt_zone_enabled);
ONEBOX_STATIC int32 onebox_bt_nongpl_module_init(VOID)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("onebox_nongpl_module_init called and registering the nongpl driver\n")));
return 0;
}
ONEBOX_STATIC VOID onebox_bt_nongpl_module_exit(VOID)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("onebox_nongpl_module_exit called and unregistering the nongpl driver\n")));
printk("BT : NONGPL module exit\n");
return;
}
module_init(onebox_bt_nongpl_module_init);
module_exit(onebox_bt_nongpl_module_exit);
<file_sep>/release/run_ap.sh
sh post_vap.sh
sleep 0.1
iwpriv vap0 setparam 96 3
sleep 0.1
iwpriv vap0 short_gi 3
sleep 0.1
iwconfig vap0 essid Gdvr
sleep 0.1
ifconfig vap0 up
sleep 0.1
iwconfig
sleep 0.1
ifconfig vap0 192.168.5.15
sleep 0.1
echo 0 > /proc/onebox_ap/debug_zone
sleep 0.1
ifconfig vap0 192.168.5.15
<file_sep>/Makefile
#/**
# * @file Makefile
# * @author
# * @version 1.0
# *
# * @section LICENSE
# *
# * This software embodies materials and concepts that are confidential to Redpine
# * Signals and is made available solely pursuant to the terms of a written license
# * agreement with Redpine Signals
# *
# * @section DESCRIPTION
# *
# * This is the Top Level Makefile used for compiling all the folders present in the parent directory.
# * List of folders compiled by the top level Makefile are net80211, common_hal, supplicant, utils.
# */
ROOT_DIR:=$(PWD)
IEEE_DIR:=$(ROOT_DIR)/wlan/net80211/linux
WLAN_DIR:=$(ROOT_DIR)/wlan/wlan_hal
WLAN_DRV:=$(ROOT_DIR)/wlan
BT_DRV:=$(ROOT_DIR)/bt
ZIGB_DRV:=$(ROOT_DIR)/zigbee
COEX_DRV:=$(ROOT_DIR)/common_hal
DEST_DIR=$(ROOT_DIR)/release
SUPP_DIR:=$(ROOT_DIR)/wlan/supplicant/linux
HOSTAPD_DIR:=$(ROOT_DIR)/wlan/hostapd-2.3/hostapd
UTILS_DIR:=$(ROOT_DIR)/utils
CC=$(CROSS_COMPILE)gcc
#DEF_KERNEL_DIR := /lib/modules/$(shell uname -r)/build
DEF_KERNEL_DIR := /home/in2em/sourcecode/quadchip/riot/buildroot/output/build/linux-3.16
ifeq ($(KERNELDIR),)
KERNELDIR := $(DEF_KERNEL_DIR)
endif
include $(ROOT_DIR)/config/.config
include $(ROOT_DIR)/config/make.config
#include .config
#include make.config
all: menuconfig obx_common_hal onebox_wlan onebox_bt onebox_zigb onebox_utils
$(CROSS_COMPILE)strip --strip-unneeded $(DEST_DIR)/*.ko
@cp -r release /home/rsi
@echo -e "\033[32mCompilation done SUCCESSFULLY\033[0m"
wlan:obx_common_hal onebox_wlan onebox_utils
@echo -e "\033[32m Only WLAN Compilation done SUCCESSFULLY\033[0m"
bt:obx_common_hal onebox_bt
@echo -e "\033[32m Only BT Compilation done SUCCESSFULLY\033[0m"
zigbee:obx_common_hal onebox_zigb
@echo -e "\033[32m Only ZIGBEE Compilation done SUCCESSFULLY\033[0m"
obx_common_hal:
@echo -e "\033[32mCompiling Onebox HAL...\033[0m"
make -C$(COEX_DRV) ROOT_DIR=$(ROOT_DIR) KERNELDIR=$(KERNELDIR)
cp $(COEX_DRV)/*.ko $(DEST_DIR)
onebox_wlan:
@echo -e "\033[32mCompiling Onebox WLAN...\033[0m"
make -C$(WLAN_DRV) ROOT_DIR=$(ROOT_DIR) CC=$(CC) KERNELDIR=$(KERNELDIR)
cp $(IEEE_DIR)/*.ko $(DEST_DIR)
cp $(WLAN_DIR)/*.ko $(DEST_DIR)
cp $(SUPP_DIR)/wpa_supplicant/wpa_supplicant $(DEST_DIR)
cp $(SUPP_DIR)/wpa_supplicant/wpa_cli $(DEST_DIR)
cp $(HOSTAPD_DIR)/hostapd $(DEST_DIR)
cp $(HOSTAPD_DIR)/hostapd_cli $(DEST_DIR)
onebox_bt:
@echo -e "\033[32mCompiling Onebox BT...\033[0m"
make -C$(BT_DRV) ROOT_DIR=$(ROOT_DIR) KERNELDIR=$(KERNELDIR)
cp $(BT_DRV)/*.ko $(DEST_DIR)
onebox_zigb:
@echo -e "\033[32mCompiling Onebox Zigbee...\033[0m"
make -C$(ZIGB_DRV) ROOT_DIR=$(ROOT_DIR) KERNELDIR=$(KERNELDIR)
cp $(ZIGB_DRV)/*.ko $(DEST_DIR)
onebox_utils:
@echo -e "\033[32mCompiling onebox utils...\033[0m"
make CC=$(CC) -C $(UTILS_DIR)/
menuconfig:
$(MAKE) -C config/lxdialog lxdialog
$(CONFIG_SHELL) config/Menuconfig config/config.in
clean:
@echo "- Cleaning All Object and Intermediate Files"
@find . -name '*.ko' | xargs rm -rf
@find . -name '*.o' | xargs rm -f
@find . -name '.*.ko.cmd' | xargs rm -rf
@find . -name '.*.ko.unsigned.cmd' | xargs rm -rf
@find . -name '*.ko.*' | xargs rm -rf
@find . -name '.*.o.cmd' | xargs rm -rf
@find . -name '*.mod.c' | xargs rm -rf
@find . -name '.tmp_versions' | xargs rm -rf
@find . -name '*.markers' | xargs rm -rf
@find . -name '*.symvers' | xargs rm -rf
@find . -name '*.order' | xargs rm -rf
@find . -name '*.d' | xargs rm -rf
@find . -name 'wpa_priv' | xargs rm -rf
@find . -name 'onebox_util' | xargs rm -rf
@find . -name 'onebox_util' | xargs rm -rf
@find . -name 'nl80211_util' | xargs rm -rf
@find . -name 'bbp_util' | xargs rm -rf
@find . -name 'transmit' | xargs rm -rf
@find . -name 'transmit_packet' | xargs rm -rf
@find . -name 'receive' | xargs rm -rf
@find . -name 'sniffer_app' | xargs rm -rf
@find . -name 'CVS' | xargs rm -rf
@find . -name '*.swp' | xargs rm -rf
@rm -rf $(UTILS_DIR)/transmit_packet
@rm -rf $(SUPP_DIR)/core *~ *.o eap_*.so $(ALL) $(WINALL) eapol_test preauth_test
@rm -rf $(SUPP_DIR)/wpa_supplicant/wpa_supplicant
@rm -rf $(SUPP_DIR)/wpa_supplicant/wpa_cli
@rm -rf $(SUPP_DIR)/wpa_supplicant/wpa_gui
@rm -rf $(DEST_DIR)/wpa_supplicant
@rm -rf $(SUPP_DIR)/wpa_supplicant/wpa_passphrase
@rm -rf $(DEST_DIR)/wpa_cli
@rm -rf $(DEST_DIR)/wpa_gui
@rm -rf $(HOSTAPD_DIR)/core *~ *.o eap_*.so $(ALL) $(WINALL) eapol_test preauth_test
@rm -rf $(HOSTAPD_DIR)/hostapd/hostapd
@rm -rf $(HOSTAPD_DIR)/hostapd/hostapd_cli
@rm -rf $(HOSTAPD_DIR)/hostapd/hostapd_passphrase
@rm -rf $(DEST_DIR)/hostapd
@rm -rf $(DEST_DIR)/hostapd_cli
@echo "- Done"
<file_sep>/wlan/wlan_hal/include/linux/onebox_core.h
/**
* @file onebox_core.h
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contians the function prototypes used in the core module
*
*/
#ifndef __ONEBOX_CORE_H__
#define __ONEBOX_CORE_H__
#include "onebox_common.h"
uint8 core_determine_hal_queue(PONEBOX_ADAPTER adapter);
void core_qos_processor(PONEBOX_ADAPTER adapter);
uint32 wlan_core_pkt_recv(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb, int8 rs_rssi, int8 chno);
uint32 bt_core_pkt_recv(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb);
#ifdef BYPASS_RX_DATA_PATH
uint8 bypass_data_pkt(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb);
#endif
uint32 core_send_beacon(PONEBOX_ADAPTER adapter,netbuf_ctrl_block_t *netbuf_cb,
struct core_vap *core_vp);
netbuf_ctrl_block_t* core_dequeue_pkt(PONEBOX_ADAPTER adapter, uint8 q_num);
void core_queue_pkt(PONEBOX_ADAPTER adapter,netbuf_ctrl_block_t *netbuf_cb,
uint8 q_num);
/*onebox_core_hal_intf.c function declarations*/
uint32 core_init(PONEBOX_ADAPTER adapter);
uint32 core_deinit(PONEBOX_ADAPTER adapter);
uint32 core_update_tx_status(PONEBOX_ADAPTER adapter,struct tx_stat_s *tx_stat);
uint32 core_tx_data_done(PONEBOX_ADAPTER adapter,netbuf_ctrl_block_t *netbuf_cb);
/*onebox_core_os_intf.c function declarations*/
int core_xmit(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb);
int onebox_send_mgmt_pkt(struct ieee80211_node *ni,
netbuf_ctrl_block_m_t *netbuf_cb_m,
const struct ieee80211_bpf_params *bpf_params);
uint32 core_rcv_pkt(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb);
void core_radiotap_tx(PONEBOX_ADAPTER adapter, struct ieee80211vap *vap, netbuf_ctrl_block_t *netbuf_cb);
ONEBOX_STATUS stats_frame(PONEBOX_ADAPTER adapter);
int start_per_tx(PONEBOX_ADAPTER adapter);
int do_continuous_send(PONEBOX_ADAPTER adapter);
ONEBOX_STATUS prepare_per_pkt(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb);
ONEBOX_STATUS start_per_burst(PONEBOX_ADAPTER adapter);
ONEBOX_STATUS onebox_send_per_frame(PONEBOX_ADAPTER adapter,uint8 mode);
void onebox_print_dump(int32 dbg_zone_l, PUCHAR msg_to_print_p,int32 len);
void core_michael_failure( PONEBOX_ADAPTER, uint8 *msg);
ONEBOX_STATUS init_phy_layer (PONEBOX_ADAPTER adapter);
void set_region(struct ieee80211com *ic);
ONEBOX_STATUS send_per_ampdu_indiaction_frame(PONEBOX_ADAPTER adapter);
void check_traffic_pwr_save(struct ieee80211vap *vap, uint8 tx_path, uint32 payload_size);
void send_traffic_pwr_save_req(struct ieee80211vap *vap);
#endif
<file_sep>/wlan/wlan_hal/osi_wlan/devdep/rsi_9113/onebox_dev_ops.c
/**
*
* @file onebox_dev_ops.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* The file contains the initialization part of the SDBus driver and Loading of the
* TA firmware.
*/
/* include files */
#include "onebox_common.h"
#include "onebox_hal.h"
#include "onebox_linux.h"
#include "onebox_pktpro.h"
/**
* This function prepares the netbuf control block
*
* @param
* adapter pointer to the driver private structure
* @param
* buffer pointer to the packet data
* @param
* len length of the packet
* @return .This function returns ONEBOX_STATUS_SUCCESS.
*/
#if 0
static netbuf_ctrl_block_t * prepare_netbuf_cb(PONEBOX_ADAPTER adapter, uint8 *buffer,
uint32 pkt_len, uint8 extended_desc)
{
netbuf_ctrl_block_t *netbuf_cb = NULL;
uint8 payload_offset;
pkt_len -= extended_desc;
#ifdef BYPASS_RX_DATA_PATH
netbuf_cb = adapter->os_intf_ops->onebox_alloc_skb(pkt_len + FRAME_DESC_SZ);
#else
netbuf_cb = adapter->os_intf_ops->onebox_alloc_skb(pkt_len);
#endif
payload_offset = extended_desc + FRAME_DESC_SZ;
if(netbuf_cb == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("@@Error while allocating skb in %s:\n"), __func__));
return NULL;
}
/* Preparing The Skb To Indicate To core */
netbuf_cb->dev = adapter->dev;
adapter->os_intf_ops->onebox_add_data_to_skb(netbuf_cb, pkt_len);
//(*(uint16 *)(netbuf_cb->data)) = (*((uint16 *)buffer));
#ifdef BYPASS_RX_DATA_PATH
netbuf_cb->len = pkt_len + FRAME_DESC_SZ;
adapter->os_intf_ops->onebox_memcpy((netbuf_cb->data), (buffer), FRAME_DESC_SZ);
adapter->os_intf_ops->onebox_memcpy((netbuf_cb->data) + FRAME_DESC_SZ, (buffer + payload_offset), netbuf_cb->len - FRAME_DESC_SZ);
#else
netbuf_cb->len = pkt_len;
adapter->os_intf_ops->onebox_memcpy((netbuf_cb->data), (buffer + payload_offset), netbuf_cb->len);
#endif
//printk("Pkt to be indicated to Net80211 layer is len =%d\n", netbuf_cb->len);
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, netbuf_cb->data, netbuf_cb->len);
return netbuf_cb;
}
#endif
/**
* This function read frames from the SD card.
*
* @param Pointer to driver adapter structure.
* @param Pointer to received packet.
* @param Pointer to length of the received packet.
* @return 0 if success else -1.
*/
ONEBOX_STATUS wlan_read_pkt(PONEBOX_ADAPTER adapter,
netbuf_ctrl_block_t *netbuf_cb)
{
uint32 queueno;
uint8 extended_desc;
// uint32 pkt_len;
uint8 *frame_desc_addr = netbuf_cb->data;
// uint8 *frame_desc_addr = msg;
uint32 length = 0;
uint16 offset =0;
#ifndef BYPASS_RX_DATA_PATH
netbuf_ctrl_block_t *netbuf_cb = NULL;
struct ieee80211com *ic = &adapter->vap_com;
struct ieee80211vap *vap = NULL;
uint8 vap_id;
#endif
FUNCTION_ENTRY(ONEBOX_ZONE_DATA_RCV);
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("adapter = %p\n"),
adapter));
queueno = (uint32)((*(uint16 *)&frame_desc_addr[offset] & 0x7000) >> 12);
length = (*(uint16 *)&frame_desc_addr[offset] & 0x0fff);
extended_desc = (*(uint8 *)&frame_desc_addr[offset + 4] & 0x00ff);
ONEBOX_DEBUG(ONEBOX_ZONE_DATA_RCV, (TEXT("###Received in QNumber:%d Len=%d###!!!\n"), queueno, length));
switch(queueno)
{
case ONEBOX_WIFI_DATA_Q:
{
/* Check if aggregation enabled */
if (length > (ONEBOX_RCV_BUFFER_LEN * 4 ))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Toooo big packet %d\n"), __func__,length));
length = ONEBOX_RCV_BUFFER_LEN * 4 ;
}
if ((length < ONEBOX_HEADER_SIZE) || (length < MIN_802_11_HDR_LEN))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Too small packet %d\n"), __func__, length));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, frame_desc_addr, length);
}
if (!length)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: Dummy pkt has comes in\n"), __func__));
}
//printk("***WLAN RECEIVED DATA PKT ***\n");
ONEBOX_DEBUG(ONEBOX_ZONE_DATA_RCV,(TEXT("@@@ Rcvd Data Pkt b4 netbuf_cb preparation:\n")));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_DATA_RCV, (frame_desc_addr + offset), (length + extended_desc));
#if 0
#ifndef BYPASS_RX_DATA_PATH
netbuf_cb = prepare_netbuf_cb(adapter, (frame_desc_addr + offset), length, extended_desc);
if(netbuf_cb == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_DATA_RCV,(TEXT("@@@ Error in preparing the rcv packet:\n")));
return ONEBOX_STATUS_FAILURE;
}
#endif
#endif
#ifdef BYPASS_RX_DATA_PATH
onebox_reorder_pkt(adapter, netbuf_cb); /* coex */
//onebox_reorder_pkt(adapter, (frame_desc_addr + offset)); /* coex */
//onebox_reorder_pkt(adapter, (frame_desc_addr + offset));
#else
adapter->core_ops->onebox_dump(ONEBOX_ZONE_MGMT_RCV, netbuf_cb->data, netbuf_cb->len);
#ifdef PWR_SAVE_SUPPORT
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
/* vap_id and check only if that vap_id matches and vap is of STA mode*/
vap_id = ((netbuf_cb->data[14] & 0xf0) >> 4);
if(vap && (vap->hal_priv_vap->vap_id == vap_id)
&& (vap->iv_opmode == IEEE80211_M_STA)
&& (TRAFFIC_PS_EN)
&& (ps_params_def.ps_en))
{
vap->check_traffic(vap, 0, netbuf_cb->len);
break;
}
}
#endif
/* As these are data pkts we are not sending rssi and chno vales */
adapter->core_ops->onebox_indicate_pkt_to_net80211(adapter,
(netbuf_ctrl_block_t *)netbuf_cb, 0, 0);
#endif
}
break;
case ONEBOX_WIFI_MGMT_Q:
{
onebox_mgmt_pkt_recv(adapter, netbuf_cb);
}
break;
default:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: pkt from invalid queue\n"), __func__));
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
}
break;
} /* End switch */
FUNCTION_EXIT(ONEBOX_ZONE_INFO);
return ONEBOX_STATUS_SUCCESS;
}
EXPORT_SYMBOL(wlan_read_pkt);
/**
* This function set the AHB master access MS word in the SDIO slave registers.
*
* @param Pointer to the driver adapter structure.
* @param ms word need to be initialized.
* @return ONEBOX_STATUS_SUCCESS on success and ONEBOX_STATUS_FAILURE on failure.
*/
ONEBOX_STATUS onebox_sdio_master_access_msword(PONEBOX_ADAPTER adapter,
uint16 ms_word)
{
UCHAR byte;
uint8 reg_dmn;
ONEBOX_STATUS status=ONEBOX_STATUS_SUCCESS;
reg_dmn = 0; //TA domain
/* Initialize master address MS word register with given value*/
byte=(UCHAR)(ms_word&0x00FF);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: MASTER_ACCESS_MSBYTE:0x%x\n"), __func__,byte));
status = adapter->osd_host_intf_ops->onebox_write_register(adapter,reg_dmn,
SDIO_MASTER_ACCESS_MSBYTE,
&byte);
if(status != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: fail to access MASTER_ACCESS_MSBYTE\n"), __func__));
return ONEBOX_STATUS_FAILURE;
}
byte=(UCHAR)(ms_word >>8);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s:MASTER_ACCESS_LSBYTE:0x%x\n"), __func__,byte));
status = adapter->osd_host_intf_ops->onebox_write_register(adapter,reg_dmn,
SDIO_MASTER_ACCESS_LSBYTE,
&byte);
if(status != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: fail to access MASTER_ACCESS_LSBYTE\n"), __func__));
return ONEBOX_STATUS_FAILURE;
}
return ONEBOX_STATUS_SUCCESS;
} /* End <onebox_sdio_master_access_msword */
/**
* This function schedules the packet for transmission.
*
* @param pointer to the adapter structure .
* @return Returns 8 if the file is of UNIX type else returns 9 if
* the file is of DOS type .
*/
void schedule_pkt_for_tx(PONEBOX_ADAPTER adapter)
{
adapter->os_intf_ops->onebox_set_event(&(adapter->sdio_scheduler_event));
}
static void wlan_thread_waiting_for_event(PONEBOX_ADAPTER adapter)
{
uint32 status= 0;
if(!adapter->beacon_event)
{
if (adapter->buffer_full)
{
/* Wait for 2ms, by the time firmware clears the buffer full interrupt */
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("%s: Event wait for 2ms \n"), __func__));
status = adapter->os_intf_ops->onebox_wait_event(&adapter->sdio_scheduler_event, 2);
}
else
{
adapter->os_intf_ops->onebox_wait_event(&adapter->sdio_scheduler_event, EVENT_WAIT_FOREVER);
}
}
adapter->os_intf_ops->onebox_reset_event(&adapter->sdio_scheduler_event);
adapter->sdio_thread_counter++;
}
/**
* This is a kernel thread to send the packets to the device
*
* @param
* data Pointer to driver's private data
* @return
* None
*/
void sdio_scheduler_thread(void *data)
{
PONEBOX_ADAPTER adapter = (PONEBOX_ADAPTER)data;
FUNCTION_ENTRY(ONEBOX_ZONE_DEBUG);
do
{
if (adapter->beacon_event)
{
adapter->beacon_event = 0;
if (adapter->hal_vap[adapter->beacon_event_vap_id].vap != NULL)
{
if (IEEE80211_IS_MODE_BEACON(adapter->hal_vap[adapter->beacon_event_vap_id].vap->iv_opmode))
{
//printk("Calling vap_load_beacon\n");
adapter->core_ops->onebox_vap_load_beacon(adapter, adapter->beacon_event_vap_id);
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT ("!!Enabling Beacon path!!!!!!!!!!!\n")));
}
}
}
if(adapter->core_init_done)
{
adapter->core_ops->onebox_core_qos_processor(adapter);
}
wlan_thread_waiting_for_event(adapter);
/* If control is coming up to end schedule again */
}
#if KERNEL_VERSION_BTWN_2_6_(18,26)
while(!onebox_signal_pending());
#elif KERNEL_VERSION_GREATER_THAN_2_6_(27)
while(adapter->os_intf_ops->onebox_atomic_read(&adapter->txThreadDone) == 0);
ONEBOX_DEBUG(ONEBOX_ZONE_WARN,
(TEXT("sdio_scheduler_thread: Came out of do while loop\n")));
adapter->os_intf_ops->onebox_completion_event(&adapter->txThreadComplete,0);
ONEBOX_DEBUG(ONEBOX_ZONE_WARN,
(TEXT("sdio_scheduler_thread: Completed onebox_completion_event \n")));
#endif
FUNCTION_EXIT(ONEBOX_ZONE_DEBUG);
}
uint16* hw_queue_status(PONEBOX_ADAPTER adapter)
{
return NULL;
}
<file_sep>/wlan/Makefile
#/**
# * @file Makefile
# * @author
# * @version 1.0
# *
# * @section LICENSE
# *
# * This software embodies materials and concepts that are confidential to Redpine
# * Signals and is made available solely pursuant to the terms of a written license
# * agreement with Redpine Signals
# *
# * @section DESCRIPTION
# *
# * This is the Top Level Makefile used for compiling all the folders present in the parent directory.
# * List of folders compiled by the top level Makefile are net80211, hal, supplicant, utils.
# */
IEEE_DIR:=$(ROOT_DIR)/wlan/net80211/linux
ONEBOX_WLAN:=$(ROOT_DIR)/wlan/wlan_hal
DEST_DIR=$(ROOT_DIR)/release
SUPP_DIR:=$(ROOT_DIR)/wlan/supplicant/linux
HOSTAPD_DIR:=$(ROOT_DIR)/wlan/hostapd-2.3/hostapd
include $(ROOT_DIR)/config/.config
include $(ROOT_DIR)/config/make.config
all:ieee80211 wlan_onebox wpa_supplicant
#all:ieee80211 wlan_onebox wpa_supplicant hostapd
#all:ieee80211 wpa_supplicant
wlan_onebox:
@cp $(ROOT_DIR)/wlan/net80211/linux/Module.symvers $(ROOT_DIR)/wlan/wlan_hal/
make -C$(ONEBOX_WLAN) ROOT_DIR=$(ROOT_DIR) KERNELDIR=$(KERNELDIR)
ieee80211:
@echo -e "\033[32mCompiling net80211...\033[0m"
@cp $(ROOT_DIR)/common_hal/Module.symvers $(IEEE_DIR)/
make -C$(KERNELDIR) SUBDIRS=$(IEEE_DIR) ROOT_DIR=$(ROOT_DIR) KERNELDIR=$(KERNELDIR)
wpa_supplicant:
@echo -e "\033[32mCompiling wpa supplicant...\033[0m"
make CC=$(CC) -C $(SUPP_DIR)/wpa_supplicant
hostapd:
@echo -e "\033[32mCompiling hostapd...\033[0m"
make CC=$(CC) -C $(HOSTAPD_DIR)
<file_sep>/release/sbl_upgrade.sh
cat /dev/null > /var/log/messages
dmesg -c > /dev/null
#sh dump_msg.sh &
#dmesg -n 7
SKIP_FW_LOAD=0
#Upgrade Software Boot loader
DRIVER_MODE=9
FW_LOAD_MODE=1
insmod onebox_nongpl.ko driver_mode=$DRIVER_MODE firmware_path=$PWD/firmware/ onebox_zone_enabled=0xffffffff skip_fw_load=$SKIP_FW_LOAD fw_load_mode=$FW_LOAD_MODE
insmod onebox_gpl.ko
<file_sep>/zigbee/osi_zigb/onebox_zigb.c
#include "onebox_core.h"
int32 core_zigb_init(PONEBOX_ADAPTER adapter)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("Entered core_bt_init in %s function\n"),__func__));
adapter->os_intf_ops->onebox_netbuf_queue_init(&adapter->zigb_rx_queue);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("Finished netbuf_queue_init in %s function\n"),__func__));
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("Before onebox_init_proc in %s function\n"),__func__));
/********************************************************************************
adding for Netlink sockets
*********************************************************************/
if (adapter->zigb_osd_ops->onebox_zigb_register_genl(adapter)) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("Finished Zigbeestack_init in %s function\n"), __func__));
return ONEBOX_STATUS_FAILURE;
}
adapter->core_init_done = 1;
return ONEBOX_STATUS_SUCCESS;
}
int32 core_zigb_deinit(PONEBOX_ADAPTER adapter)
{
adapter->core_init_done = 0;
adapter->os_intf_ops->onebox_queue_purge(&adapter->zigb_rx_queue);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Uninitialized Procfs\n"), __func__));
/**********************************************************************
adding for Netlink sockets
*******************************************************************/
if(adapter->zigb_osd_ops->onebox_zigb_deregister_genl(adapter)) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("Finished Zigbeestack_ deinit in %s function\n"),__func__));
return ONEBOX_STATUS_FAILURE;
}
return 0;
}
/**
* This routine dump the given data through the debugger..
*
* @param Debug zone.
* @param Pointer to data that has to dump.
* @param Length of the data to dump.
* @return VOID.
*/
void onebox_print_dump(int32 zone,UCHAR *vdata, int32 len )
{
uint16 ii;
if(!zone || !(zone & onebox_zigb_zone_enabled))
return;
for(ii=0; ii< len; ii++)
{
if(!(ii % 16) && ii)
{
//ONEBOX_DEBUG(zone, (TEXT("\n%04d: "), ii));
ONEBOX_DEBUG(zone, (TEXT("\n")));
}
ONEBOX_DEBUG(zone,(TEXT("%02x "),(vdata[ii])));
}
ONEBOX_DEBUG(zone, (TEXT("\n")));
}
<file_sep>/wlan/net80211/linux/Makefile
#/**
# * @file Makefile
# * @author
# * @version 1.0
# *
# * @section LICENSE
# *
# * This software embodies materials and concepts that are confidential to Redpine
# * Signals and is made available solely pursuant to the terms of a written license
# * agreement with Redpine Signals
# *
# * @section DESCRIPTION
# *
# * This is the Net80211 Makefile used for compiling the osi and osd wrappers in Net80211.
# */
#KERNELDIR=/lib/modules/$(KERNELRELEASE)/build
KERNELDIR=/home/in2em/sourcecode/quadchip/riot/buildroot/output/build/linux-3.16
#KERNELRELEASE=$(shell uname -r)
DRV_DIR=$(ROOT_DIR)/wlan/net80211/linux
RELEASE_DIR=release
SRC_DIR=osi_net80211/src
OSD_DIR=osd_linux/src
include $(ROOT_DIR)/.config
include $(ROOT_DIR)/config/make.config
EXTRA_CFLAGS += -DLINUX -Wimplicit -Wstrict-prototypes
#EXTRA_CFLAGS += -DANDROID_PLATFORM
ifeq ($(USE_DEVICE),"SDIO")
EXTRA_CFLAGS += -DUSE_SDIO_INTF
EXTRA_CFLAGS += -DPWR_SAVE_SUPPORT
endif
#EXTRA_CFLAGS += -DIEEE80211_AMPDU_AGE
#EXTRA_CFLAGS += -DENABLE_P2P_SUPPORT
#EXTRA_CFLAGS += -DINET
#EXTRA_CFLAGS += -Dnet80211_s
#EXTRA_CFLAGS += -DIEEE80211_DEBUG
#EXTRA_CFLAGS += -I./include/linux
#EXTRA_CFLAGS += -I$(DRV_DIR)/inc/
#EXTRA_CFLAGS += -I$(DRV_DIR)/inc/osd/linux/
#EXTRA_CFLAGS += -I$(DRV_DIR)/inc/osi/
EXTRA_CFLAGS += -I$(ROOT_DIR)/common_hal/include/common
EXTRA_CFLAGS += -I$(DRV_DIR)/osd_linux/include/
EXTRA_CFLAGS += -I$(DRV_DIR)/osi_net80211/net80211/
EXTRA_CFLAGS += -I$(DRV_DIR)/osi_net80211/
EXTRA_CFLAGS += -g
#EXTRA_CFLAGS += -DONEBOX_ENABLE_RX_DC_OFFSET
#EXTRA_CFLAGS += -DONEBOX_ENABLE_SSB_CAL
wlan_wep-objs := $(SRC_DIR)/ieee80211_crypto_wep.o
wlan_tkip-objs := $(SRC_DIR)/ieee80211_crypto_tkip.o
wlan_scan_sta-objs := $(SRC_DIR)/ieee80211_scan_sta.o
wlan_ccmp-objs := $(SRC_DIR)/ieee80211_crypto_ccmp.o
wlan_xauth-objs := $(SRC_DIR)/ieee80211_xauth.o
wlan_acl-objs := $(SRC_DIR)/ieee80211_acl.o
wlan-objs :=$(SRC_DIR)/ieee80211.o \
$(SRC_DIR)/ieee80211_linux.o \
$(SRC_DIR)/ieee80211_ioctl.o \
$(SRC_DIR)/ieee80211_node.o \
$(SRC_DIR)/ieee80211_action.o \
$(SRC_DIR)/ieee80211_adhoc.o \
$(SRC_DIR)/ieee80211_ageq.o \
$(SRC_DIR)/ieee80211_crypto.o \
$(SRC_DIR)/ieee80211_crypto_none.o \
$(SRC_DIR)/ieee80211_dfs.o \
$(SRC_DIR)/ieee80211_quiet.o \
$(SRC_DIR)/ieee80211_ht.o \
$(SRC_DIR)/ieee80211_hwmp.o \
$(SRC_DIR)/ieee80211_input.o \
$(SRC_DIR)/ieee80211_mesh.o \
$(SRC_DIR)/ieee80211_monitor.o \
$(SRC_DIR)/ieee80211_phy.o \
$(SRC_DIR)/ieee80211_proto.o \
$(SRC_DIR)/ieee80211_ratectl.o \
$(SRC_DIR)/ieee80211_regdomain.o \
$(SRC_DIR)/ieee80211_wds.o \
$(SRC_DIR)/ieee80211_scan.o \
$(SRC_DIR)/ieee80211_sta.o \
$(SRC_DIR)/ieee80211_superg.o \
$(SRC_DIR)/ieee80211_hostap.o \
$(SRC_DIR)/ieee80211_radiotap.o \
$(SRC_DIR)/ieee80211_power.o \
$(SRC_DIR)/ieee80211_output.o\
$(SRC_DIR)/ieee80211_p2p.o\
$(OSD_DIR)/mbuf.o \
$(OSD_DIR)/sysctl.o \
$(OSD_DIR)/ndiface.o \
$(OSD_DIR)/ioctl.o \
$(OSD_DIR)/linux.o \
$(OSD_DIR)/cfg80211_ioctl.o \
$(OSD_DIR)/cfg80211_wrapper.o \
# $(SRC_DIR)/ieee80211_ddb.o
# $(SRC_DIR)/ieee80211_tdma.o
MOD_INSTALL := wlan.o wlan_wep.o wlan_tkip.o wlan_ccmp.o wlan_xauth.o wlan_scan_sta.o wlan_acl.o
obj-m := $(MOD_INSTALL)
all:
@echo "Compiling Onebox code"
make -C$(KERNELDIR) SUBDIRS=$(DRV_DIR) modules
#@cp *.ko ../release
clean:
@echo "- Cleaning All Object and Intermediate Files"
@find . -name '*.ko' | xargs rm -rf
@find . -name '*.order' | xargs rm -rf
@find . -name '*.symvers' | xargs rm -rf
@find . -name '*.markers' | xargs rm -rf
@find . -name '*.o' | xargs rm -f
@find . -name '.*.ko.cmd' | xargs rm -rf
@find . -name '.*.ko.unsigned.cmd' | xargs rm -rf
@find . -name '*.ko.*' | xargs rm -rf
@find . -name '.*.o.cmd' | xargs rm -rf
@find $(OSD_DIR) -name '*.o' | xargs rm -f
@find $(HOST_INTF_DIR) -name '.*.o.cmd' | xargs rm -rf
@find . -name '*.mod.c' | xargs rm -rf
@echo "- Done"
<file_sep>/wlan/wlan_hal/osi_wlan/core/onebox_core_hal_intf.c
#include "onebox_core.h"
/* ***************** Core 2 HAL functions **************** */
/**
* This function updates the autorate stats.
*
* @param Pointer to the driver private structure.
* @param Pointer to transmit stats structure.
* @return ONEBOX_STATUS_SUCCESS on success else negative number on failure.
*/
uint32 core_update_tx_status(PONEBOX_ADAPTER adapter,struct tx_stat_s *tx_stat)
{
int i;
for(i=0;i<tx_stat->count;i++)
{
adapter->autorate_stats[tx_stat->staid][tx_stat->stat[i].rate_idx].total_success = tx_stat->stat[i].success;
adapter->autorate_stats[tx_stat->staid][tx_stat->stat[i].rate_idx].total_attempts = tx_stat->stat[i].attempts;
}
return ONEBOX_STATUS_SUCCESS;
}
/* Tx data done processing */
/**
* This function process the data packets to send.
*
* @param Pointer to the Adapter structure.
* @param Pointer to netbuf control block structure.
* @return ONEBOX_STATUS_SUCCESS on success else negative number on failure.
*/
uint32 core_tx_data_done(PONEBOX_ADAPTER adapter,netbuf_ctrl_block_t *netbuf_cb)
{
if(netbuf_cb)
{
adapter->os_intf_ops->onebox_free_pkt(adapter,netbuf_cb,0);
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("\nCORE_MSG: tx done error")));
}
return ONEBOX_STATUS_SUCCESS;
}
/**
* This function does the core initialization.
*
* @param pointer to the Adapter structure.
* return ONEBOX_STATUS_SUCCESS on success else negative number on failure.
*
*/
uint32 core_init(PONEBOX_ADAPTER adapter)
{
uint32 count;
//adapter->init_done = 0;
for (count = 0; count < ONEBOX_VAPS_DEFAULT; count++)
{
adapter->sec_mode[count] = IEEE80211_CIPHER_NONE;
}
/* attach net80211 */
//core_net80211_attach(adapter);
/* Rate adaptation initialization */
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("%s:Registering Autorate\n"),__func__));
adapter->sc_rc = (struct onebox_ratectrl *)core_rate_attach(adapter);
if (adapter->sc_rc == NULL)
{
goto out;
}
adapter->core_init_done = 1;
//adapter->init_done = 1;
return ONEBOX_STATUS_SUCCESS;
out:
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("%s:out\n"),__func__));
return ONEBOX_STATUS_FAILURE;
}
/**
* This functions deinitializes the core.
*
* @param Pointer to driver private structure.
* return ONEBOX_STATUS_SUCCESS on success else negative number on failure.
*/
uint32 core_deinit(PONEBOX_ADAPTER adapter)
{
uint8 ii;
//struct ieee80211com *ic = &adapter->vap_com;
adapter->core_init_done = 0;
/* Detach net80211 */
/* Clean up the Net80211 Module */
core_net80211_detach(adapter);
/* Purge the mgmt transmit queue */
/* Purge the Data transmit queue */
for (ii = 0; ii < NUM_SOFT_QUEUES; ii++)
{
adapter->os_intf_ops->onebox_queue_purge(&adapter->host_tx_queue[ii]);
}
/* detach autorate */
core_rate_detach(adapter);
return ONEBOX_STATUS_SUCCESS;
}
<file_sep>/wlan/net80211/linux/osd_linux/src/cfg80211_wrapper.c
/*
* @file
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contians the code specific to Litefi-AP architecture.
*/
#ifdef ONEBOX_CONFIG_CFG80211
#include <net/cfg80211.h>
#include <linux/rtnetlink.h>
#include <linux/version.h>
#include <linux/hardirq.h>
#include "linux/wireless.h"
#include "cfg80211_wrapper.h"
#include "cfg80211_ioctl.h"
static struct cfg80211_ops onebox_cfg80211_ops = {
.set_wiphy_params = onebox_cfg80211_set_wiphy_params,
#if(LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 38))
.set_tx_power = onebox_cfg80211_set_txpower,
#endif
.scan = onebox_cfg80211_scan,
.connect = onebox_cfg80211_connect,
.disconnect = onebox_cfg80211_disconnect,
.add_key = onebox_cfg80211_add_key,
.del_key = onebox_cfg80211_del_key,
.set_default_key = onebox_cfg80211_set_default_key,
.get_station = onebox_cfg80211_get_station,
};
/**
* This function sets the wiphy parameters if changed.
*
* @param Pointer to wiphy structure.
* @param Value that indicates which wiphy parameter changed.
* @return GANGES_STATUS_SUCCESS on success else negative number on failure.
*/
ONEBOX_STATUS
onebox_cfg80211_set_wiphy_params(struct wiphy *wiphy, uint32_t changed)
{
struct iw_param rts;
struct iw_param frag;
if (changed & WIPHY_PARAM_RTS_THRESHOLD)
{
rts.value = wiphy->rts_threshold;
rts.disabled = 0;
if(onebox_siwrts(&rts) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
if (changed & WIPHY_PARAM_FRAG_THRESHOLD)
{
frag.value = wiphy->frag_threshold;
frag.disabled = 0;
if(onebox_siwfrag(&frag) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
return ONEBOX_STATUS_SUCCESS;
}
#if(LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 38))
ONEBOX_STATUS onebox_cfg80211_add_key(struct wiphy *wiphy,struct net_device *ndev,
uint8_t index, const uint8_t *mac_addr, struct key_params *params)
#else
ONEBOX_STATUS onebox_cfg80211_add_key(struct wiphy *wiphy,struct net_device *ndev,
uint8_t index, bool pairwise, const uint8_t *mac_addr, struct key_params *params)
#endif
{
if(onebox_add_key(ndev, index, mac_addr, (struct ieee80211_key_params *)params) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
/**
* This function deletes the key of particular key_index.
*
* @param Pointer to wiphy structure.
* @param Pointer to network device structure.
* @param Key Index to be deleted.
* @param Value to identify pairwise or group key.
* @param Pointer to the MAC address of the station to delete keys.
* @return GANGES_STATUS_SUCCESS on success else negative number on failure.
*/
#if(LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 38))
ONEBOX_STATUS
onebox_cfg80211_del_key(struct wiphy *wiphy, struct net_device *ndev, uint8_t index,
const uint8_t *mac_addr )
#else
ONEBOX_STATUS
onebox_cfg80211_del_key(struct wiphy *wiphy, struct net_device *ndev, uint8_t index,
bool pairwise, const uint8_t *mac_addr )
#endif
{
if(onebox_delete_key(ndev, mac_addr, index) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
/**
* This function sets the various connection params for infra mode.
*
* @param Pointer to wiphy structure.
* @param Pointer to network device structure.
* @param Mode to set Infrastructure/IBSS.
* @param Pointer to flags.
* @param Pointer to interface parameters.
* @return GANGES_STATUS_SUCCESS on success else negative number on failure.
*/
ONEBOX_STATUS
onebox_cfg80211_connect(struct wiphy *wiphy, struct net_device *ndev, struct cfg80211_connect_params *params)
{
int privacy = params->privacy;
int auth = params->auth_type;
// printk("ASSOC CMD: In %s and %d mac_addr = %02x:%02x:%02x:%02x:%02x:%02x ssid = %s \n", __func__, __LINE__, params->bssid[0], params->bssid[1], params->bssid[2], params->bssid[3], params->bssid[4], params->bssid[5], params->ssid);
if(params->key)
{
if(onebox_wep_key(ndev, params->key_idx, params->bssid, params->key_len, params->key) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
}
if(cfg80211_connect_res(ndev, auth, params->ie, params->ie_len, params->ssid,
params->ssid_len, params->bssid, params->ssid_len, privacy) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
uint8_t cfg80211_wrapper_attach(struct net_device *vap_dev, void *dev_ptr, int size)
{
struct device *device;
struct wireless_dev *wdev;
device = (struct device *)dev_ptr;
wdev = onebox_register_wiphy_dev(device, size);
if (!wdev)
{
printk("Failed to create wireless device\n");
return ONEBOX_STATUS_FAILURE;
}
vap_dev->ieee80211_ptr = wdev;
SET_NETDEV_DEV(vap_dev, wiphy_dev(wdev->wiphy));
wdev->netdev = vap_dev;
//FIXME: Assuming default mode of operation is Station
wdev->iftype = NL80211_IFTYPE_STATION;
return ONEBOX_STATUS_SUCCESS;
}
#if(LINUX_VERSION_CODE < KERNEL_VERSION(3, 3, 3))
EXPORT_SYMBOL(cfg80211_wrapper_attach);
#endif
/**
* This function registers our device as a wiphy device and registers the
* initial wiphy parameters. We allocate space for wiphy parameters.
*
* @param Pointer to our device(pfunc).
* @return Pointer to the wireless dev structure obtained after registration.
*/
struct wireless_dev* onebox_register_wiphy_dev(struct device *dev, int size)
{
struct wireless_dev *wdev = NULL;
#if(LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 38))
int rtnl_locked = rtnl_is_locked();
#endif
/* XXX: Mac address read from eeprom */
uint8_t addr[ETH_ADDR_LEN] = {0x00, 0x23, 0xa7,0x0f, 0x03, 0x06};
uint8_t ii = 0, ret = 0;
uint16_t freq_list[] = { 5180, 5200, 5220, 5240, 5260, 5280,
5300, 5320, 5500, 5520, 5540, 5560,
5580, 5600, 5620, 5640, 5660, 5680,
5700, 5745, 5765, 5785, 5805, 5825};
wdev = kzalloc(sizeof(struct wireless_dev), GFP_KERNEL);
if (!wdev)
{
printk("mem allocation failed");
return NULL;
}
/*FIXME: second arg is the private data area to allocate
* Make sure the size of priv data is provided correctly
*/
// printk("NL80211 : In %s LINE %d size %d\n",__func__,__LINE__, size);
wdev->wiphy = wiphy_new(&onebox_cfg80211_ops, size);
// printk("NL80211 : In %s LINE %d wdev->wiphy %p\n",__func__,__LINE__,wdev->wiphy);
if (!wdev->wiphy)
{
printk("Couldn't allocate wiphy device\n");
kfree(wdev);
return NULL;
}
set_wiphy_dev(wdev->wiphy, dev);
band_24ghz.bitrates = bg_rsi_rates;
band_24ghz.n_bitrates = ARRAY_SIZE(bg_rsi_rates);
band_24ghz.n_channels = (MAX_CHANNELS_24GHZ - 1);
band_5ghz.bitrates = (bg_rsi_rates + 4);
band_5ghz.n_bitrates = (ARRAY_SIZE(bg_rsi_rates) - 4);
band_5ghz.n_channels = (MAX_CHANNELS_5GHZ - 1);
for (ii = 0; ii < MAX_CHANNELS_24GHZ - 1; ii++)
{
channels_24ghz[ii].center_freq = (2412 + ii * 5);
} /* End for loop */
channels_24ghz[ii].center_freq = 2484;
for (ii = 0; ii < MAX_CHANNELS_5GHZ - 1; ii++)
{
channels_5ghz[ii].center_freq = freq_list[ii];
}
band_24ghz.band = IEEE80211_BAND_2GHZ;
band_24ghz.channels = &channels_24ghz[0];
wdev->wiphy->bands[IEEE80211_BAND_2GHZ] = &band_24ghz;
band_5ghz.band = IEEE80211_BAND_5GHZ;
band_5ghz.channels = &channels_5ghz[0];
wdev->wiphy->bands[IEEE80211_BAND_5GHZ] = &band_5ghz;
wdev->wiphy->n_addresses = 1;
wdev->wiphy->addresses = (struct mac_address *)&addr[0];
wdev->wiphy->max_scan_ssids = 1;
wdev->wiphy->interface_modes = (BIT(NL80211_IFTYPE_STATION));
wdev->wiphy->signal_type = CFG80211_SIGNAL_TYPE_UNSPEC;
wdev->wiphy->frag_threshold = DFL_FRAG_THRSH - 28;
wdev->wiphy->rts_threshold = DFL_RTS_THRSH - 28;
wdev->wiphy->cipher_suites = cipher_suites;
wdev->wiphy->n_cipher_suites = ARRAY_SIZE(cipher_suites);
#if 0
wdev->wiphy->wowlan.flags = WIPHY_WOWLAN_MAGIC_PKT |
WIPHY_WOWLAN_DISCONNECT |
WIPHY_WOWLAN_GTK_REKEY_FAILURE |
WIPHY_WOWLAN_SUPPORTS_GTK_REKEY |
WIPHY_WOWLAN_EAP_IDENTITY_REQ |
WIPHY_WOWLAN_4WAY_HANDSHAKE;
wdev->wiphy->wowlan.n_patterns = 4;
wdev->wiphy->wowlan.pattern_min_len = 1;
wdev->wiphy->wowlan.pattern_max_len = 64;
wdev->wiphy->max_sched_scan_ssids = 10;
#endif
#if(LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 38))
if(rtnl_locked)
{
rtnl_unlock();
}
ret = wiphy_register(wdev->wiphy);
rtnl_lock();
#else
ret = wiphy_register(wdev->wiphy);
#endif
if (ret < 0)
{
//ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("Couldn't register wiphy device\n")));
printk("Couldn't register wiphy device\n");
wiphy_free(wdev->wiphy);
return NULL;
}
return wdev;
}
/**
* This function triggers the scan.
*
* @param Pointer to wiphy structure.
* @param Pointer to network device structure.
* @param Pointer to the cfg80211_scan_request structure
* that has the scan parameters.
* @return GANGES_STATUS_SUCCESS on success else negative number on failure.
*/
ONEBOX_STATUS
onebox_cfg80211_scan(struct wiphy *wiphy, struct net_device *ndev,struct cfg80211_scan_request *request)
{
uint16_t *channels= NULL;
uint8_t n_channels = 0;
ONEBOX_STATUS status = ONEBOX_STATUS_SUCCESS;
if(request->n_channels > 0 && (request->n_channels <= IEEE80211_MAX_FREQS_ALLOWED ))
{
uint8_t i;
n_channels = request->n_channels;
channels = kzalloc(n_channels * sizeof(uint16_t), GFP_KERNEL);
if (channels == NULL)
{
printk("failed to set scan channels, scan all channels");
n_channels = 0;
}
for (i = 0; i < n_channels; i++)
{
channels[i] = request->channels[i]->center_freq;
printk("%s %d:selected chans are %d\n", __func__, __LINE__, request->channels[i]->center_freq);
}
}
else
{
request->n_channels = 0;
}
if(cfg80211_scan(request, ndev, n_channels, channels, request->ie, request->ie_len, request->n_ssids, request->ssids))
{
status = ONEBOX_STATUS_FAILURE;
}
else
{
/* No code here */
}
if(channels)
{
kfree(channels);
}
return status;
}
#if(LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 38))
ONEBOX_STATUS
onebox_cfg80211_set_txpower(struct wiphy *wiphy, enum nl80211_tx_power_setting type, int dbm)
{
dbm = (dbm / 100); //convert mbm to dbm
if (type == NL80211_TX_POWER_FIXED)
{
if (dbm < 0)
{
dbm = 0;
}
else if (dbm > 20) /* FIXME - Check the max */
{
dbm = 20;
}
else
{
/* No code here */
} /* End if <condition> */
}
else
{
/* Automatic adjustment */
dbm = 0xff;
} /* End if <condition> */
return tx_power(dbm);
}
#endif
ONEBOX_STATUS
onebox_cfg80211_set_default_key(struct wiphy *wiphy, struct net_device *ndev, uint8_t index, bool unicast, bool multicast)
{
return ONEBOX_STATUS_SUCCESS;
}
ONEBOX_STATUS
onebox_cfg80211_disconnect(struct wiphy *wiphy, struct net_device *ndev, uint16_t reason_code)
{
printk("<<< Recvd Disassoc In %s Line %d reason code %d >>>\n", __func__, __LINE__, reason_code);
if(cfg80211_disconnect(ndev, reason_code) < 0)
{
return ONEBOX_STATUS_FAILURE;
}
else
{
return ONEBOX_STATUS_SUCCESS;
}
}
ONEBOX_STATUS
onebox_cfg80211_get_station(struct wiphy *wiphy, struct net_device *ndev, uint8_t *mac, struct station_info *info)
{
return ONEBOX_STATUS_SUCCESS;
}
void cfg80211_wrapper_free_wdev(struct wireless_dev *wdev)
{
if(!wdev)
{
return;
}
wiphy_unregister(wdev->wiphy);
wiphy_free(wdev->wiphy);
kfree(wdev);
}
#if(LINUX_VERSION_CODE < KERNEL_VERSION(3, 3, 3))
EXPORT_SYMBOL(cfg80211_wrapper_free_wdev);
#endif
int scan_results_sup(struct wireless_dev *wdev, unsigned char ssid[6], int val, int cap_info,
struct ieee80211_channel *channel1, int chan, uint8_t *binfo, int binfo_len, uint8_t *network_ssid)
{
struct wiphy *wiphy = wdev->wiphy;
struct ieee80211_mgmt *mgmt = NULL;
struct cfg80211_bss *bss = NULL;
char *temp;
BEACON_PROBE_FORMAT *frame;
int frame_len = 0;
uint8_t band;
int freq;
struct ieee80211_channel *channel = NULL;
nl80211_mem_alloc((void **)&mgmt, sizeof(struct ieee80211_mgmt) + 512, GFP_ATOMIC);
nl80211_memcpy(mgmt->bssid, ssid, 6);
mgmt->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT);
frame = (BEACON_PROBE_FORMAT *)(&mgmt->u.beacon);
temp = (unsigned char *)&frame->timestamp[0];
memset(temp, 0, 8);
frame->beacon_intvl = cpu_to_le16(val);
frame->capability = cpu_to_le16(cap_info);
temp = frame->variable;
/** Added the below 3 lines code to give ssid field in the data ie **/
/** Made this change for Hidden mode AP's **/
if((binfo[0] == WLAN_EID_SSID && binfo[1] == 0))
{
*temp++ = WLAN_EID_SSID;
*temp++ = network_ssid[1];
memcpy(temp, &network_ssid[2], network_ssid[1]);
temp = temp + network_ssid[1];
frame_len = network_ssid[1];
nl80211_memcpy(temp, binfo, binfo_len );
binfo_len -= 2;
binfo += 2 ;
}
nl80211_memcpy(temp, binfo, binfo_len );
frame_len += offsetof(struct ieee80211_mgmt, u.beacon.variable);
frame_len += binfo_len;
if (chan <= 14)
band = IEEE80211_BAND_2GHZ;
else
band = IEEE80211_BAND_5GHZ;
#if(LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 38))
freq = ieee80211_channel_to_frequency(chan);
#else
freq = ieee80211_channel_to_frequency(chan, band);
#endif
channel = ieee80211_get_channel(wiphy, freq);
if (!wiphy || !channel || !mgmt ||
frame_len < offsetof(struct ieee80211_mgmt, u.beacon.variable))
{
kfree(mgmt);
printk("Error Informing Frame %d \n", __LINE__);
return ONEBOX_STATUS_FAILURE;
}
bss = cfg80211_inform_bss_frame(wiphy, channel, mgmt,
cpu_to_le16(frame_len),
0, GFP_ATOMIC);
if (!bss)
{
kfree(mgmt);
printk("Error Informing Frame \n");
return ONEBOX_STATUS_FAILURE;
}
cfg80211_put_bss(bss);/*this is needed to update bss list */
kfree(mgmt);
return ONEBOX_STATUS_SUCCESS;
}
int scan_done(void *temp_scan_req)
{
struct cfg80211_scan_request *req;
req = scan_req;
if(req == NULL)
{
cfg80211_cqm_rssi_notify(wdev->netdev, 3, GFP_ATOMIC);
return 0;
}
cfg80211_scan_done(req, 0);
req = NULL;
return ONEBOX_STATUS_SUCCESS;
}
void nl80211_mem_alloc(void **ptr, unsigned short len, unsigned short flags)
{
*ptr = kmalloc(len, flags);
}
void* nl80211_memcpy(void *to, const void *from, int len)
{
return memcpy(to,from,len);
}
int connection_confirm(struct wireless_dev *wdev, uint8_t mac[6])
{
printk("ASSOC CMD: In %s and %d mac_addr = %02x:%02x:%02x:%02x:%02x:%02x\n", __func__, __LINE__, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
cfg80211_connect_result(wdev->netdev, mac, NULL, 0, NULL, 0, 0, GFP_ATOMIC);
return ONEBOX_STATUS_SUCCESS;
}
int disconnection_confirm(struct wireless_dev *wdev)
{
wdev = wdev->netdev->ieee80211_ptr;
wdev->iftype = NL80211_IFTYPE_STATION;
cfg80211_disconnected(wdev->netdev, 0, NULL, 0, GFP_ATOMIC);
return ONEBOX_STATUS_SUCCESS;
}
#endif
<file_sep>/zigbee/osi_zigb/onebox_zigb_rx.c
/**
*
* @file onebox_dev_ops.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
*/
/* include files */
#include "onebox_common.h"
#include "onebox_linux.h"
#include "onebox_pktpro.h"
/**
* This function read frames from the SD card.
*
* @param Pointer to driver adapter structure.
* @param Pointer to received packet.
* @param Pointer to length of the received packet.
* @return 0 if success else -1.
*/
ONEBOX_STATUS zigb_read_pkt(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb1)
{
FUNCTION_ENTRY(ONEBOX_ZONE_DATA_RCV);
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("adapter = %p\n"),
adapter));
/* Queuing the packets here so that zigbee will poll and receive them*/
adapter->os_intf_ops->onebox_genl_app_send(adapter->genl_cb, netbuf_cb1);
FUNCTION_EXIT(ONEBOX_ZONE_INFO);
return ONEBOX_STATUS_SUCCESS;
}
EXPORT_SYMBOL(zigb_read_pkt);
<file_sep>/common_hal/osi/onebox_common_init.c
#include <linux/module.h>
#include <linux/kernel.h>
#include "onebox_datatypes.h"
#include "onebox_common.h"
#include "onebox_pktpro.h"
#include "onebox_sdio_intf.h"
uint32 onebox_zone_enabled = ONEBOX_ZONE_INFO |
ONEBOX_ZONE_INIT |
ONEBOX_ZONE_OID |
ONEBOX_ZONE_MGMT_SEND |
ONEBOX_ZONE_MGMT_RCV |
ONEBOX_ZONE_DATA_SEND |
ONEBOX_ZONE_DATA_RCV |
ONEBOX_ZONE_FSM |
ONEBOX_ZONE_ISR |
ONEBOX_ZONE_MGMT_DUMP |
ONEBOX_ZONE_DATA_DUMP |
ONEBOX_ZONE_DEBUG |
ONEBOX_ZONE_AUTORATE |
ONEBOX_ZONE_PWR_SAVE |
ONEBOX_ZONE_ERROR |
0;
struct driver_assets d_assets = {0};
static uint sdio_clock = 0;
static bool enable_high_speed = 0;
//uint8 firmware_path[256] = "/system/lib/wifi/firmware_wifi/";
uint8 firmware_path[256] = "/home/rsi/release/firmware/";
static uint16 driver_mode = 1;
static uint16 coex_mode = 1; /*Default coex mode is WIFI alone */
static uint16 ta_aggr = 0;
static uint16 skip_fw_load = 0; /* Default disable skipping fw loading */
static uint16 fw_load_mode = 1; /* Default fw loading mode is full flash with Secondary Boot loader*/
static uint16 lp_ps_handshake_mode = 0; /* Default No HandShake mode*/
static uint16 ulp_ps_handshake_mode = 2; /* Default PKT HandShake mode*/
static uint16 rf_power_val = 0; /* Default 3.3V */
static uint16 device_gpio_type = TA_GPIO; /* Default TA GPIO */
module_param(lp_ps_handshake_mode,ushort,0);
MODULE_PARM_DESC(lp_ps_handshake_mode, "Enable (0) No HandShake Mode \
Enable (1) GPIO HandShake Mode");
module_param(ulp_ps_handshake_mode,ushort,0);
MODULE_PARM_DESC(ulp_ps_handshake_mode, "Enable (0) No HandShake Mode \
Enable (1) GPIO HandShake Mode \
Enable (2) Packet HandShake Mode");
module_param(rf_power_val,ushort,0);
MODULE_PARM_DESC(rf_power_val, "Enable (0) 3.3 Volts power for RF \
Enable (1) 1.9 Volts power for RF");
module_param(device_gpio_type,ushort,0);
MODULE_PARM_DESC(device_gpio_type, "Enable (TA_GPIO) selects TA GPIO \
Enable (ULP_GPIO) selects ULP GPIO");
module_param(driver_mode,ushort,0);
MODULE_PARM_DESC(driver_mode, "Enable (1) WiFi mode or Enable (2) RF Eval mode \
Enable (3) RF_EVAL_LPBK_CALIB mode (4) RF_EVAL_LPBK mode \
Enable (5) QSPI BURNING mode");
module_param(coex_mode,ushort,0);
MODULE_PARM_DESC(coex_mode, "(1) WiFi ALONE (2) WIFI AND BT \
(3) WIFI AND ZIGBEE");
module_param(ta_aggr, ushort, 0);
MODULE_PARM_DESC(ta_aggr, "No of pkts to aggregate from TA to host");
module_param(fw_load_mode, ushort, 0);
MODULE_PARM_DESC(fw_load_mode, " FW Download Mode \
1 - Full Flash mode with Secondary Boot Loader\
2 - Full RAM mode with Secondary Boot Loader \
3 - Flash + RAM mode with Secondary Boot Loader\
4 - Flash + RAM mode without Secondary Boot Loader");
module_param(skip_fw_load, ushort, 0);
MODULE_PARM_DESC(skip_fw_load, " 1 to Skip fw loading else 2");
module_param(onebox_zone_enabled,uint,0);
module_param(sdio_clock, uint, 0);
module_param(enable_high_speed, bool, 0);
MODULE_PARM_DESC(enable_high_speed, "Enable (1) or Disable (0) High speed mode");
MODULE_PARM_DESC(sdio_clock, "SDIO Clock frequency in MHz");
module_param_string(firmware_path, firmware_path, sizeof(firmware_path), 0);
MODULE_PARM_DESC(firmware_path, "Location of firmware files");
ONEBOX_STATUS read_reg_parameters (PONEBOX_ADAPTER adapter)
{
struct driver_assets *d_assets = onebox_get_driver_asset();
if(lp_ps_handshake_mode == 0)
{
d_assets->lp_ps_handshake_mode = NO_HAND_SHAKE;
}
else if(lp_ps_handshake_mode == 1)
{
d_assets->lp_ps_handshake_mode = GPIO_HAND_SHAKE;
}
if(ulp_ps_handshake_mode == 0)
{
d_assets->ulp_ps_handshake_mode = NO_HAND_SHAKE;
}
else if(ulp_ps_handshake_mode == 2)
{
d_assets->ulp_ps_handshake_mode = PACKET_HAND_SHAKE;
}
else if(ulp_ps_handshake_mode == 1)
{
d_assets->ulp_ps_handshake_mode = GPIO_HAND_SHAKE;
}
if (rf_power_val == 0)
d_assets->rf_power_val = RF_POWER_3_3;
else
d_assets->rf_power_val = RF_POWER_1_9;
if (device_gpio_type == TA_GPIO)
d_assets->device_gpio_type = TA_GPIO;
else
d_assets->device_gpio_type = ULP_GPIO;
if (driver_mode == WIFI_MODE_ON)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: WiFi mode on\n"), __func__));
adapter->Driver_Mode = WIFI_MODE_ON;
}
else if (driver_mode == RF_EVAL_MODE_ON)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: RF Evaluation mode on\n"), __func__));
adapter->Driver_Mode = RF_EVAL_MODE_ON;
}
else if (driver_mode == RF_EVAL_LPBK_CALIB)
{
/*FIXME: Try to optimize these conditions */
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: RF Eval LPBK CALIB mode on\n"), __func__));
adapter->Driver_Mode = RF_EVAL_LPBK_CALIB; /* RF EVAL mode */
}
else if (driver_mode == RF_EVAL_LPBK)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: RF Eval LPBK mode on\n"), __func__));
adapter->Driver_Mode = RF_EVAL_LPBK; /* RF EVAL mode */
}
else if (driver_mode == QSPI_FLASHING)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: QSPI_FLASHING mode on\n"), __func__));
adapter->Driver_Mode = QSPI_FLASHING;
adapter->flashing_mode = QSPI_FLASHING;
}
else if (driver_mode == QSPI_UPDATE)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: QSPI_UPDATE mode on\n"), __func__));
adapter->Driver_Mode = QSPI_FLASHING;
adapter->flashing_mode = QSPI_UPDATE;
}
else if (driver_mode == SNIFFER_MODE)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: Sniffer mode on\n"), __func__));
adapter->Driver_Mode = SNIFFER_MODE;
}
else if (driver_mode == SWBL_FLASHING_NOSBL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: Sw Bootloader Flashing mode on\n"), __func__));
adapter->Driver_Mode = QSPI_FLASHING;
adapter->flashing_mode = SWBL_FLASHING_NOSBL;
}
else if (driver_mode == SWBL_FLASHING_NOSBL_FILE)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: Sw Bootloader Flashing mode on with Calib from file\n"), __func__));
adapter->Driver_Mode = QSPI_FLASHING;
adapter->flashing_mode = SWBL_FLASHING_NOSBL_FILE;
}
else if (driver_mode == SWBL_FLASHING_SBL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: Sw Bootloader Flashing mode on\n"), __func__));
adapter->Driver_Mode = QSPI_FLASHING;
adapter->flashing_mode = SWBL_FLASHING_SBL;
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: WiFi mode on\n"), __func__));
adapter->Driver_Mode = WIFI_MODE_ON;
} /* End if <condition> */
if(coex_mode == WIFI_ALONE) {
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: WiFi ALONE\n"), __func__));
adapter->coex_mode = WIFI_ALONE;
}
else if(coex_mode == WIFI_BT_CLASSIC) {
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: WiFi + BT Classic Mode\n"), __func__));
adapter->coex_mode = WIFI_BT_CLASSIC;
}
else if(coex_mode == WIFI_ZIGBEE) {
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: WiFi + Zigbee Mode\n"), __func__));
adapter->coex_mode = WIFI_ZIGBEE;
}
else if(coex_mode == WIFI_BT_LE) {
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: WiFi + BT Low Energy Mode\n"), __func__));
adapter->coex_mode = WIFI_BT_LE;
}
else {
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: DEFAULT WiFi ALONE selelcted as no priority is Mentioned\n"), __func__));
adapter->coex_mode = WIFI_ALONE;
}
if (fw_load_mode == FULL_FLASH_SBL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: Full flash mode with Secondary Bootloader\n"), __func__));
adapter->fw_load_mode = FULL_FLASH_SBL;
}
else if (fw_load_mode == FULL_RAM_SBL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: Full RAM mode with Secondary Bootloader\n"), __func__));
adapter->fw_load_mode = FULL_RAM_SBL;
}
else if (fw_load_mode == FLASH_RAM_SBL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: Flash + RAM mode with Secondary Bootloader\n"), __func__));
adapter->fw_load_mode = FLASH_RAM_SBL;
}
else if (fw_load_mode == FLASH_RAM_NO_SBL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: Flash + RAM mode without/No Secondary Bootloader\n"), __func__));
adapter->fw_load_mode = FLASH_RAM_NO_SBL;
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: Default Full flash mode with Secondary Bootloader\n"), __func__));
adapter->fw_load_mode = FULL_FLASH_SBL;
}
adapter->skip_fw_load = skip_fw_load;
#if LINUX_VERSION_CODE == KERNEL_VERSION(2, 6, 18)
if (enable_high_speed)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("%s: High speed mode on\n"), __func__));
adapter->sdio_high_speed_enable = 1;
}
else
{
adapter->sdio_high_speed_enable = 0;
} /* End if <condition> */
#endif
adapter->sdio_clock_speed = sdio_clock;
d_assets->ta_aggr = ta_aggr;
d_assets->asset_role = adapter->Driver_Mode;
return ONEBOX_STATUS_SUCCESS;
}
/* This function initializes the common hal */
ONEBOX_STATUS common_hal_init(struct driver_assets *d_assets, PONEBOX_ADAPTER adapter)
{
//struct onebox_os_intf_operations *os_intf_ops = onebox_get_os_intf_operations_from_origin();
struct onebox_coex_osi_operations *coex_osi_ops = onebox_get_coex_osi_operations();
int count;
printk("In %s Line %d initializing common Hal init \n", __func__, __LINE__);
for (count = 0; count < COEX_SOFT_QUEUES; count++)
adapter->os_intf_ops->onebox_netbuf_queue_init(&adapter->coex_queues[count]);
adapter->os_intf_ops->onebox_netbuf_queue_init(&adapter->deferred_rx_queue);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Mutex init successfull\n"), __func__));
adapter->os_intf_ops->onebox_init_event(&(adapter->coex_tx_event));
adapter->os_intf_ops->onebox_init_event(&(adapter->flash_event));
adapter->os_intf_ops->onebox_init_dyn_mutex(&d_assets->tx_access_lock);
adapter->os_intf_ops->onebox_init_dyn_mutex(&d_assets->wlan_init_lock);
adapter->os_intf_ops->onebox_init_dyn_mutex(&d_assets->bt_init_lock);
adapter->os_intf_ops->onebox_init_dyn_mutex(&d_assets->zigbee_init_lock);
d_assets->update_tx_status = &update_tx_status;
if (adapter->os_intf_ops->onebox_init_thread(&(adapter->sdio_scheduler_thread_handle),
"COEX-TX-Thread",
0,
coex_osi_ops->onebox_coex_transmit_thread,
adapter) != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("%s: Unable to initialize thrd\n"), __func__));
adapter->os_intf_ops->onebox_mem_free(adapter->DataRcvPacket);
printk("In %s Line %d initializing common Hal init \n", __func__, __LINE__);
return ONEBOX_STATUS_FAILURE;
}
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Initialized thread & Event\n"), __func__));
/* start the transmit thread */
adapter->os_intf_ops->onebox_start_thread( &(adapter->sdio_scheduler_thread_handle));
printk("Common hal: Init proc entry call\n");
/* Create proc filesystem */
if (adapter->os_intf_ops->onebox_init_proc(adapter) != 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("%s: Failed to initialize procfs\n"), __func__));
printk("In %s Line %d initializing common Hal init \n", __func__, __LINE__);
return ONEBOX_STATUS_FAILURE;
}
d_assets->common_hal_fsm = COMMAN_HAL_WAIT_FOR_CARD_READY;
printk("In %s Line %d initializing common Hal init \n", __func__, __LINE__);
#ifdef USE_WORKQUEUES
/* coex workqeue */
printk("HAL : Using WORKQUEUES as the interrupt bottom halfs\n");
adapter->int_work_queue = adapter->os_intf_ops->onebox_create_work_queue("onebox_workerQ");
if (!adapter->int_work_queue) {
printk("HAL : Unable to create work queue\n");
return ONEBOX_STATUS_FAILURE;
}
INIT_WORK((struct work_struct *)&adapter->defer_work, &deferred_rx_packet_parser);
#endif
#ifdef USE_TASKLETS
printk("HAL : Using TASKLETS as the interrupt bottom halfs\n");
tasklet_init(&adapter->int_bh_tasklet,
&deferred_rx_tasklet,
adapter);
#endif
#ifdef GPIO_HANDSHAKE
adapter->os_intf_ops->onebox_gpio_init();
#endif
return ONEBOX_STATUS_SUCCESS;
}
/**
* This Function Initializes The HAL
*
* @param pointer to HAL control block
* @return
* ONEBOX_STATUS_SUCCESS on success, ONEBOX_STATUS_FAILURE on failure
*/
ONEBOX_STATUS device_init(PONEBOX_ADAPTER adapter, uint8 fw_load)
{
ONEBOX_STATUS status = ONEBOX_STATUS_SUCCESS;
uint32 regout_val = 0;
uint8 bl_req = 0;
FUNCTION_ENTRY(ONEBOX_ZONE_INIT);
if(adapter->Driver_Mode == QSPI_FLASHING)
adapter->fsm_state = FSM_CARD_NOT_READY;
else
adapter->fsm_state = FSM_DEVICE_READY;
if(adapter->fw_load_mode == FULL_FLASH_SBL ||
adapter->fw_load_mode == FULL_RAM_SBL ||
adapter->fw_load_mode == FLASH_RAM_SBL) {
bl_req = 1;
} else if(adapter->fw_load_mode == FLASH_RAM_NO_SBL) {
bl_req = 0;
} else {
printk("Unexpected fw load mode %d.. Returning failure\n",adapter->fw_load_mode);
goto fail;
}
if(fw_load && !adapter->skip_fw_load) {
bl_cmd_start_timer(adapter, BL_CMD_TIMEOUT);
while(!adapter->bl_timer_expired) {
if(adapter->osd_host_intf_ops->onebox_master_reg_read(adapter,
SWBL_REGOUT, ®out_val, 2) < 0) {
printk("%s:%d REGOUT reading failed..\n",__func__,
__LINE__);
goto fail;
}
if((regout_val >> 8) == REGOUT_VALID) {
break;
}
}
if(adapter->bl_timer_expired) {
printk("%s:%d REGOUT reading timed out..\n",__func__,
__LINE__);
printk("Software Boot loader Not Present\n");
if(bl_req) {
printk("Expecting Software boot loader tobe present."
"Enable/flash Software boot loader\n");
goto fail;
} else {
printk("Software boot loader is disabled as expected\n");
}
} else {
bl_cmd_stop_timer(adapter);
printk("Software Boot loader Present\n");
if(bl_req) {
printk("Software boot loader is enabled as expected\n");
} else {
printk("Expecting Software boot loader tobe disabled\n");
goto fail;
}
}
printk("Received Board Version Number is %x\n",(regout_val & 0xff));
if((adapter->osd_host_intf_ops->onebox_master_reg_write(adapter,
SWBL_REGOUT, (REGOUT_INVALID | REGOUT_INVALID << 8), 2)) < 0) {
printk("%s:%d REGOUT writing failed..\n",__func__,
__LINE__);
goto fail;
}
if(adapter->fw_load_mode == FLASH_RAM_NO_SBL)
status = load_ta_instructions(adapter);
else
status = load_fw_thru_sbl(adapter);
}
FUNCTION_EXIT(ONEBOX_ZONE_INIT);
return status;
fail:
return ONEBOX_STATUS_FAILURE;
} /* onebox_device_init */
/**
* This Function Free The Memory Allocated By HAL Module
*
* @param pointer to HAL control block
*
* @return
* ONEBOX_STATUS_SUCCESS on success, ONEBOX_STATUS_FAILURE on failure
*/
ONEBOX_STATUS device_deinit(PONEBOX_ADAPTER adapter)
{
FUNCTION_ENTRY(ONEBOX_ZONE_INFO);
//adapter->coex_osi_ops->onebox_core_deinit(adapter);
#ifdef GPIO_HANDSHAKE
adapter->os_intf_ops->onebox_gpio_deinit();
#endif
FUNCTION_EXIT(ONEBOX_ZONE_INFO);
return ONEBOX_STATUS_SUCCESS;
}
static struct onebox_os_intf_operations *os_intf_ops;
int onebox_register_os_intf_operations (struct onebox_os_intf_operations *os_intf_opeartions)
{
os_intf_ops = os_intf_opeartions;
return 0;
}
struct onebox_os_intf_operations *onebox_get_os_intf_operations(void)
{
return os_intf_ops;
}
ONEBOX_STATIC int32 onebox_nongpl_module_init(VOID)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("onebox_nongpl_module_init called and registering the nongpl driver\n")));
return 0;
}
ONEBOX_STATIC VOID onebox_nongpl_module_exit(VOID)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("onebox_nongpl_module_exit called and unregistering the nongpl driver\n")));
return;
}
module_init(onebox_nongpl_module_init);
module_exit(onebox_nongpl_module_exit);
EXPORT_SYMBOL(onebox_zone_enabled);
EXPORT_SYMBOL(onebox_register_os_intf_operations);
EXPORT_SYMBOL(onebox_get_os_intf_operations);
//FIXME This should be passed through adapter, should not be exported
EXPORT_SYMBOL(firmware_path);
<file_sep>/wlan/wlan_hal/include/linux/onebox_pktpro.h
/**
* @file onebox_pktpro.h
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contians the function prototypes used for sending /receiving packets to/from the
* driver
*
*/
#ifndef __ONEBOX_PKTPRO_H__
#define __ONEBOX_PKTPRO_H__
#include "onebox_datatypes.h"
#include "onebox_common.h"
#define IEEE80211_FCTL_STYPE 0xF0
#define ONEBOX_80211_FC_PROBE_RESP 0x50
/* Function Prototypes */
void interrupt_handler(PONEBOX_ADAPTER adapter);
ONEBOX_STATUS onebox_read_pkt(PONEBOX_ADAPTER adapter);
ONEBOX_STATUS send_beacon(PONEBOX_ADAPTER adapter,
netbuf_ctrl_block_t *netbuf_cb,
struct core_vap *core_vp,
int8 dtim_beacon);
ONEBOX_STATUS send_onair_data_pkt(PONEBOX_ADAPTER adapter,
netbuf_ctrl_block_t *netbuf_cb,
int8 q_num);
ONEBOX_STATUS send_bt_pkt(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb);
ONEBOX_STATUS send_zigb_pkt(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb);
ONEBOX_STATUS onebox_load_config_vals(PONEBOX_ADAPTER adapter);
int32 load_ta_instructions(PONEBOX_ADAPTER adapter);
void sdio_scheduler_thread(void *data);
ONEBOX_STATUS device_init(PONEBOX_ADAPTER adapter);
ONEBOX_STATUS device_deinit(PONEBOX_ADAPTER adapter);
ONEBOX_STATUS device_queues_status(PONEBOX_ADAPTER adapter, uint8 q_num);
int hal_set_sec_wpa_key(PONEBOX_ADAPTER adapter,const struct ieee80211_node *ni_sta, uint8 key_type);
uint32 hal_send_sta_notify_frame(PONEBOX_ADAPTER adapter, struct ieee80211_node *sta_addr, int32 sta_id);
#endif
<file_sep>/zigbee/include/linux/onebox_common.h
/**
* @file onebox_common.h
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contians the data structures and variables/ macros commonly
* used in the driver .
*/
#ifndef __ONEBOX_COMMON_H__
#define __ONEBOX_COMMON_H__
#include <linux/netdevice.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/etherdevice.h>
#include <linux/if.h>
#include <linux/wireless.h>
#include <linux/version.h>
#include <linux/vmalloc.h>
#include <linux/mutex.h>
#ifdef USE_USB_INTF
#include <linux/usb.h>
#endif
/*Bluetooth Specific */
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include <linux/workqueue.h>
#ifdef USE_USB_INTF
#define onebox_likely(a) likely(a)
#define USB_VENDOR_REGISTER_READ 0x15
#define USB_VENDOR_REGISTER_WRITE 0x16
#endif
#if((LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,18))&& \
(LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23)))
#include <linux/sdio/ctsystem.h>
#include <linux/sdio/sdio_busdriver.h>
#include <linux/sdio/_sdio_defs.h>
#include <linux/sdio/sdio_lib.h>
#elif (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,26))
#include <linux/mmc/card.h>
#include <linux/mmc/sdio_func.h>
#include <linux/mmc/sdio_ids.h>
#endif
#include "onebox_datatypes.h"
/* Kernel version between and including a & b */
#define KERNEL_VERSION_BTWN_2_6_(a,b) \
((LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,a)) && \
(LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,b)))
#define KERNEL_VERSION_EQUALS_2_6_(a) \
(LINUX_VERSION_CODE == KERNEL_VERSION(2,6,a))
/* Kernel version greater than equals */
#define KERNEL_VERSION_GREATER_THAN_2_6_(a) \
(LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,a))
/* Kernel version less than or equal to */
#define KERNEL_VERSION_LESS_THAN_3_6(a) \
(LINUX_VERSION_CODE <= KERNEL_VERSION(3,6,a))
#define KERNEL_VERSION_LESS_THAN_3_12_(a) \
(LINUX_VERSION_CODE <= KERNEL_VERSION(3,12,a))
//#define USE_INTCONTEXT
#define USE_WORKQUEUES
//#define USE_TASKLETS
#ifdef USE_TASKLETS
#include <linux/interrupt.h>
#endif
#ifndef IN
#define IN
#endif
#ifndef OUT
#define OUT
#endif
#define ONEBOX_BIT(n) (1 << (n))
#define ONEBOX_ZONE_ERROR ONEBOX_BIT(0) /* For Error Msgs */
#define ONEBOX_ZONE_WARN ONEBOX_BIT(1) /* For Warning Msgs */
#define ONEBOX_ZONE_INFO ONEBOX_BIT(2) /* For General Status Msgs */
#define ONEBOX_ZONE_INIT ONEBOX_BIT(3) /* For Driver Init Seq Msgs */
#define ONEBOX_ZONE_OID ONEBOX_BIT(4) /* For IOCTL Path Msgs */
#define ONEBOX_ZONE_MGMT_SEND ONEBOX_BIT(5) /* For TX Mgmt Path Msgs */
#define ONEBOX_ZONE_MGMT_RCV ONEBOX_BIT(6) /* For RX Mgmt Path Msgs */
#define ONEBOX_ZONE_DATA_SEND ONEBOX_BIT(7) /* For TX Data Path Msgs */
#define ONEBOX_ZONE_DATA_RCV ONEBOX_BIT(8) /* For RX Data Path Msgs */
#define ONEBOX_ZONE_FSM ONEBOX_BIT(9) /* For State Machine Msgs */
#define ONEBOX_ZONE_ISR ONEBOX_BIT(10) /* For Interrupt Specific Msgs */
#define ONEBOX_ZONE_MGMT_DUMP ONEBOX_BIT(11) /* For Dumping Mgmt Pkts */
#define ONEBOX_ZONE_DATA_DUMP ONEBOX_BIT(12) /* For Dumping Data Pkts */
#define ONEBOX_ZONE_CLASSIFIER ONEBOX_BIT(13) /* For Classification Msgs */
#define ONEBOX_ZONE_PROBE ONEBOX_BIT(14) /* For Probe Req & Rsp Msgs */
#define ONEBOX_ZONE_EXIT ONEBOX_BIT(15) /* For Driver Unloading Msgs */
#define ONEBOX_ZONE_DEBUG ONEBOX_BIT(16) /* For Extra Debug Messages */
#define ONEBOX_ZONE_PWR_SAVE ONEBOX_BIT(17) /* For Powersave Blk Msgs */
#define ONEBOX_ZONE_AGGR ONEBOX_BIT(18) /* For Aggregation Msgs */
#define ONEBOX_ZONE_DAGGR ONEBOX_BIT(19) /* For Deaggregation Msgs */
#define ONEBOX_ZONE_AUTORATE ONEBOX_BIT(20) /* For Autorate Msgs */
#define ONEBOX_STATUS_SUCCESS 0
#define ONEBOX_STATUS_FAILURE -1
#define INVALID_QUEUE 0xff
#define NO_STA_DATA_QUEUES 4
#define ONEBOX_HEADER_SIZE 18 /* Size of PS_POLL */
#define TX_VECTOR_SZ 12
#define ONEBOX_TOTAL_PWR_VALS_LEN 30
#define ONEBOX_BGN_PWR_VALS_LEN 30
#define ONEBOX_AN_PWR_VALS_LEN 18
#define ONEBOX_EXTERN extern
#define ONEBOX_STATIC static
#define HEX_FILE 1
#define BIN_FILE 0
#define ONEBOX_SDIO_FRM_TRF_SIZE (256 - 16)
#define FRAME_DESC_SZ 16
#define OFFSET_EXT_DESC_SIZE 4
#define ONEBOX_DESCRIPTOR_SZ 64
#define ONEBOX_EXTENDED_DESCRIPTOR 12
#define ONEBOX_RCV_BUFFER_LEN 2000
typedef int ONEBOX_STATUS;
/***************************** START MACROS ********************************/
#define ONEBOX_PRINT printk
#define ONEBOX_SPRINTF sprintf
#ifdef ONEBOX_DEBUG_ENABLE
#define ONEBOX_DEBUG1 ONEBOX_PRINT
#define PRINT_MAC_ADDR(zone, buf) do {\
if (zone & onebox_zigb_zone_enabled) {\
ONEBOX_PRINT("%02x:%02x:%02x:%02x:%02x:%02x\n",\
buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);\
}\
} while (0);
#define ONEBOX_ASSERT(exp) do {\
if (!(exp)) {\
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,\
("===> ASSERTION FAILED <===\n"));\
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,\
("Expression: %s\n", #exp));\
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,\
("Function : %s()\n", __FUNCTION__));\
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,\
("File: %s:%d\n", __FILE__, __LINE__));\
}\
} while (0)
#define FUNCTION_ENTRY(zone) do {\
if (zone & onebox_zigb_zone_enabled) {\
ONEBOX_PRINT("+%s()\n", __FUNCTION__);\
}\
} while (0);
#define FUNCTION_EXIT(zone) do {\
if (zone & onebox_zigb_zone_enabled) {\
ONEBOX_PRINT("-%s()\n", __FUNCTION__);\
}\
} while (0);
#else
#define PRINT_MAC_ADDR(zone, buf)
#define ONEBOX_ASSERT(exp)
#define FUNCTION_ENTRY(zone)
#define FUNCTION_EXIT(zone)
#endif
#ifndef DANUBE_ADDRESSING
#define ONEBOX_HOST_VIR_TO_PHY(virt_addr) virt_to_phys((void *)virt_addr)
#define ONEBOX_HOST_PHY_TO_VIR(phy_addr) phys_to_virt((uint32)phy_addr)
#else
#define ONEBOX_HOST_VIR_TO_PHY(virt_addr) ((void *)(((uint32)virt_addr) & 0x5FFFFFFF))
#define ONEBOX_HOST_PHY_TO_VIR(phy_addr) (((uint32)phy_addr) | 0xA0000000)
#endif
#define ONEBOX_CPU_TO_LE16(x) cpu_to_le16(x)
#define ONEBOX_CPU_TO_LE32(x) cpu_to_le32(x)
#define ONEBOX_CPU_TO_BE16(x) cpu_to_be16(x)
#define ETH_PROTOCOL_OFFSET 12
#define ETH_HDR_OFFSET 0
#define ETH_HDR_LEN 14
#define DMA_MEMORY 1
#define NORMAL_MEMORY 0
#define LMAC_VER_OFFSET 0x200
/*BT specific */
#define MAX_BER_PKT_SIZE 1030
#define GANGES_BER_QUEUE_LEN 100
/* BT device states */
#define BT_STAND_BY 0
#define BT_INQUIRY 1
#define BT_PAGE 2
#define BT_INQUIRY_SCAN 3
#define BT_PAGE_SCAN 4
#define BT_INQUIRY_RESP 5
#define BT_SLAVE_PAGE_RESP 6
#define BT_MASTER_PAGE_RESP 6
#define BT_CONN 7
#define BT_PARK 8
#define BT_SLAVE_PAGE_RESP_2 6
#define BT_MASTER_PAGE_RESP_2 6
#define BT_CLASSIC_MODE 0
#define BT_LE_MODE 1
#define FREQ_HOP_ENABLE 0
#define FREQ_HOP_DISABLE 1
/* zigbee queues */
//#define BT_TA_MGMT_Q 0x0
//#define ZB_INTERNAL_MGMT_Q 0x0
#define BT_TA_MGMT_Q 0x6
#define ZB_DATA_Q 0x7
#define ZB_INTERNAL_MGMT_Q 0x6
#define E2E_MODE_ON 1
/* Bluetooth Queues */
#define BT_DATA_Q 0x7
#define BT_TA_MGMT_Q 0x6
#define BT_INT_MGMT_Q 0x6
/* EPPROM_READ_ADDRESS */
#define WLAN_MAC_EEPROM_ADDR 40
#define WLAN_MAC_MAGIC_WORD_LEN 01
#define WLAN_HOST_MODE_LEN 04
#define MAGIC_WORD 0x5A
/* Rx filter word defines */
#define PROMISCOUS_MODE 0x0001
#define ALLOW_ANY_DATA 0x0002
#define ALLOW_ANY_MGMT 0x0004
#define ALLOW_ANY_CTRL 0x0008
#define ALLOW_DATA_ASSOC_PEER 0x0010
#define ALLOW_MGMT_ASSOC_PEER 0x0020
#define ALLOW_CTRL_ASSOC_PEER 0x0040
#define ALLOW_ANY_BEACON 0x0080
#define ALLOW_ANY_PROBE_REQ 0x0100
#define ALLOW_ANY_PROBE_RESP 0x0200
#define ALLOW_BEACON_ASSOC 0x0400
/* sifs and slot time defines */
#define SIFS_TX_11N_VALUE 580
#define SIFS_TX_11B_VALUE 346
#define SHORT_SLOT_VALUE 360
#define LONG_SLOT_VALUE 640
#define OFDM_ACK_TOUT_VALUE 2720
#define CCK_ACK_TOUT_VALUE 9440
#define LONG_PREAMBLE 0x0000
#define SHORT_PREAMBLE 0x0001
#define REQUIRED_HEADROOM_FOR_BT_HAL 16
#define ONEBOX_DEBUG_MESG_RECVD 1
/*Master access types*/
#define ONEBOX_MASTER_READ 11
#define ONEBOX_MASTER_WRITE 22
#define ONEBOX_MASTER_ACK 33
typedef struct
{
uint16 major;
uint16 minor;
uint8 release_num;
uint8 patch_num;
union
{
struct
{
uint8 fw_ver[8];
}info;
}ver;
}__attribute__ ((packed))version_st;
#define ZIGB_DEREGISTER 0xff
typedef struct onebox_priv ONEBOX_ADAPTER, *PONEBOX_ADAPTER;
#include "onebox_netbuf.h"
#include "onebox_coex.h"
#include "onebox_mgmt.h"
#include "onebox_zigb_ops.h"
#include "onebox_os_intf_ops.h"
#include "onebox_sdio_intf.h"
/* Adapter structure */
struct onebox_priv
{
struct net_device *dev; /* Stores the netdevice pointer */
/* Network Interface Specific Variables */
onebox_netbuf_head_t zigb_rx_queue;
#define NAME_MAX_LENGTH 32
uint8 name[NAME_MAX_LENGTH];
struct net_device_stats stats;
uint8 mac_addr[6];
uint32 fsm_state;
uint32 core_init_done;
#ifdef USE_USB_INTF
struct usb_interface *pfunction;
#else
#if((LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,18))&& \
(LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23)))
PSDDEVICE pDevice;
#elif (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,26))
struct sdio_func *pfunction;
#endif
#endif
struct onebox_os_intf_operations *os_intf_ops;
struct onebox_osd_host_intf_operations *osd_host_intf_ops;
struct onebox_osi_host_intf_operations *osi_host_intf_ops;
struct onebox_zigb_osd_operations *zigb_osd_ops;
struct onebox_osi_zigb_ops *osi_zigb_ops;
ONEBOX_STATUS (*onebox_send_pkt_to_coex)(netbuf_ctrl_block_t* netbuf_cb, uint8 hal_queue);
struct semaphore zigb_gpl_lock;
/*version related variables*/
version_st driver_ver;
version_st ta_ver;
version_st lmac_ver;
struct genl_cb *genl_cb;
} __attribute__((__aligned__(4)));
extern uint32 onebox_zigb_zone_enabled;
ONEBOX_STATUS setup_zigb_procfs(PONEBOX_ADAPTER adapter);
void destroy_zigb_procfs(void);
ONEBOX_STATUS zigb_read_pkt(PONEBOX_ADAPTER adapter,
netbuf_ctrl_block_t *netbuf_cb);
struct onebox_osi_zigb_ops *onebox_get_osi_zigb_ops(void);
struct onebox_zigb_osd_operations *onebox_get_zigb_osd_ops(void);
extern uint32 onebox_zone_enabled;
int32 zigb_register_genl(PONEBOX_ADAPTER adapter);
int32 zigb_unregister_genl(PONEBOX_ADAPTER adapter);
void onebox_common_app_send(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb);
/***************** END DRIVER DATA STRUCTURE TEMPLATES ******************/
#endif
<file_sep>/wlan/wlan_hal/osi_wlan/devdep/rsi_9113/onebox_devdep_mgmt.c
/**
* @file onebox_devdep_mgmt.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* The file contains the message information exchanged between the
* driver and underlying device/
*/
#include "onebox_common.h"
#include "onebox_per.h"
#include "onebox_bootup_params.h"
#include "onebox_qspi.h"
#if 0
void send_sta_supported_features_at_timeout(struct ieee80211vap *vap)
{
struct ieee80211com *ic = NULL;
PONEBOX_ADAPTER adapter = NULL;
if(is_vap_valid(vap) < 0) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("ERROR: VAP is Not a valid pointer In %s Line %d, So returning\n "),
__func__, __LINE__));
dump_stack();
return;
}
printk("Initial Timeout expired\n");
/*clear the timer flag*/
ic = vap->iv_ic;
adapter = (PONEBOX_ADAPTER)vap->hal_priv_vap->hal_priv_ptr;
//adapter->sta_mode.initial_timer_running = 0;
if(vap->iv_state == IEEE80211_S_RUN) {
onebox_send_sta_supported_features(vap, adapter);
}
else {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("ERROR: Vap is not run state, so Sta supported features are not being send\n")));
}
}
void initialize_sta_support_feature_timeout(struct ieee80211vap *vap, PONEBOX_ADAPTER adapter)
{
if( (!adapter->sta_support_feature_send_timeout.function))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Initializing feature support timeout \n")));
adapter->os_intf_ops->onebox_init_sw_timer(&adapter->sta_support_feature_send_timeout, (uint32)vap,
(void *)&send_sta_supported_features_at_timeout, 100);
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Modifiying Initializing feature support timeout \n")));
adapter->os_intf_ops->onebox_mod_timer(&adapter->sta_support_feature_send_timeout, msecs_to_jiffies(100));
}
adapter->sta_mode.initial_timer_running =1;
driver_ps.delay_pwr_sve_decision_flag = 1;
}
#endif
/**
* This function prepares the Baseband Programming request
* frame and sends to the PPE
*
* @param
* adapter Pointer to Driver Private Structure
* @param
* bb_prog_vals Pointer to bb programming values
* @param
* num_of_vals Number of BB Programming values
*
* @return
* Returns ONEBOX_STATUS_SUCCESS on success, or ONEBOX_STATUS_FAILURE
* on failure
*/
static ONEBOX_STATUS onebox_mgmt_send_bb_prog_frame(PONEBOX_ADAPTER adapter,
uint16 *bb_prog_vals,
uint16 num_of_vals)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status_l;
uint16 frame_len;
uint16 count;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
uint8 ii = 0;
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,
(TEXT("===> Sending Baseband Programming Packet <===\n")));
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, MAX_MGMT_PKT_SIZE);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_MGMT_DUMP, (PUCHAR)bb_prog_vals, num_of_vals);
/* Preparing BB Request Frame Body */
for (count=1; ((count < num_of_vals) && (ii< num_of_vals)); ii++, count+=2)
{
mgmt_frame->u.bb_prog_req[ii].reg_addr = ONEBOX_CPU_TO_LE16(bb_prog_vals[count]);
mgmt_frame->u.bb_prog_req[ii].bb_prog_vals = ONEBOX_CPU_TO_LE16(bb_prog_vals[count+1]);
}
if (num_of_vals % 2)
{
mgmt_frame->u.bb_prog_req[ii].reg_addr = ONEBOX_CPU_TO_LE16(bb_prog_vals[count]);
}
/* Preparing BB Request Frame Header */
frame_len = ((num_of_vals) * 2); //each 2 bytes
/*prepare the frame descriptor */
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16((frame_len) | (ONEBOX_WIFI_MGMT_Q << 12));
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(BB_PROG_VALUES_REQUEST);
if (adapter->soft_reset & BBP_REMOVE_SOFT_RST_BEFORE_PROG)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(BBP_REMOVE_SOFT_RST_BEFORE_PROG);
}
if (adapter->soft_reset & BBP_REMOVE_SOFT_RST_AFTER_PROG)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(BBP_REMOVE_SOFT_RST_AFTER_PROG);
}
if (adapter->bb_rf_rw)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(BBP_REG_READ);
adapter->bb_rf_rw = 0;
}
adapter->soft_reset = 0;
//Flags are not handled FIXME:
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(num_of_vals);
#ifdef RF_8230
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16 (PUT_BBP_RESET | BBP_REG_WRITE | (NONRSI_RF_TYPE << 4));
#else
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16 (PUT_BBP_RESET | BBP_REG_WRITE | (RSI_RF_TYPE << 4));
#endif
//FIXME: What is the radio id to fill here
// mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16 (RADIO_ID << 8 );
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_MGMT_DUMP, (PUCHAR)mgmt_frame, (frame_len + FRAME_DESC_SZ ));
status_l = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, (frame_len + FRAME_DESC_SZ));
return status_l;
}
/**
* This function prepares the RF Programming Request frame and sends to the PPE
*
* @param
* adapter Pointer to Driver Private Structure
* adapter Pointer to RF programming values Structure
* adapter number of programming values to be loaded
* adapter number of values in a row
*
* @returns
* ONEBOX_STATUS_SUCCESS on success, or corresponding negative
* error code on failure
*/
static ONEBOX_STATUS onebox_mgmt_send_rf_prog_frame(PONEBOX_ADAPTER adapter,
uint16 *rf_prog_vals,
uint16 num_of_sets,
uint16 vals_per_set,
uint8 type)
{
//FIXME: How are we taking care of band here ??
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status_l;
uint16 frame_len;
uint16 count;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
FUNCTION_ENTRY(ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("===> Sending RF Programming Packet <===\n")));
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, 256);
/* Preparing RF Request Frame Header */
frame_len = (vals_per_set * num_of_sets * 2);
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(frame_len | (ONEBOX_WIFI_MGMT_Q << 12));
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(RF_PROG_VALUES_REQUEST);
if (adapter->soft_reset & BBP_REMOVE_SOFT_RST_BEFORE_PROG)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(BBP_REMOVE_SOFT_RST_BEFORE_PROG);
}
if (adapter->soft_reset & BBP_REMOVE_SOFT_RST_AFTER_PROG)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(BBP_REMOVE_SOFT_RST_AFTER_PROG);
}
if (adapter->bb_rf_rw)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(BBP_REG_READ);
adapter->bb_rf_rw = 0;
}
adapter->soft_reset = 0;
if (adapter->Driver_Mode == RF_EVAL_MODE_ON)
{
if (adapter->bb_rf_params.value == 4 || adapter->bb_rf_params.value == 5)
{
mgmt_frame->desc_word[5] |= ONEBOX_CPU_TO_LE16(ULP_MODE); //indicating ULP
printk("ULP \n");
}
}
//Flags are not handled FIXME:
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(vals_per_set | (num_of_sets << 8));
#ifdef RF_8230
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16 (PUT_BBP_RESET | BBP_REG_WRITE | (NONRSI_RF_TYPE << 4));
#else
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16 (PUT_BBP_RESET | BBP_REG_WRITE | (RSI_RF_TYPE << 4));
#endif
if(adapter->rf_reset)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16 (RF_RESET_ENABLE);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("===> RF RESET REQUEST SENT <===\n")));
adapter->rf_reset = 0;
}
//FIXME: What is the radio id to fill here
// mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16 (RADIO_ID << 8 );
/* Preparing RF Request Frame Body */
for (count = 0; count < (vals_per_set * num_of_sets); count++)
{
mgmt_frame->u.rf_prog_req.rf_prog_vals[count] = ONEBOX_CPU_TO_LE16(rf_prog_vals[count]);
}
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_MGMT_DUMP,(PUCHAR)mgmt_frame, (frame_len + FRAME_DESC_SZ ));
status_l = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, (frame_len + FRAME_DESC_SZ));
return status_l;
} /* onebox_mgmt_send_rf_prog_frame */
/**
* This function prepares the Baseband buffer Programming request
* frame
*
* @param
* adapter Pointer to Driver Private Structure
* @param
* bb_buf_vals Pointer to bb_buf programming values
* @param
* num_of_vals Number of BB Programming values
*
* @return
* Returns ONEBOX_STATUS_SUCCESS on success, or ONEBOX_STATUS_FAILURE
* on failure
*/
static ONEBOX_STATUS onebox_bb_buffer_request(PONEBOX_ADAPTER adapter,
uint16 *bb_buf_vals,
uint16 num_of_vals)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status_l;
uint16 frame_len;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,
(TEXT("===> Sending Buffer Programming Packet <===\n")));
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, MAX_MGMT_PKT_SIZE);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)bb_buf_vals, ((num_of_vals*2 *3) + 6));
/* Preparing BB BUFFER Request Frame Body */
frame_len = ((num_of_vals * 2 *3) + 6); //for 1 value there are 3 regs and each 2 bytes
adapter->os_intf_ops->onebox_memcpy(&mgmt_frame->u.bb_buf_req.bb_buf_vals[0], &bb_buf_vals[1], (frame_len));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)&mgmt_frame->u.bb_buf_req.bb_buf_vals[0], (frame_len));
/* Preparing BB Request Frame Header */
/*prepare the frame descriptor */
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16((frame_len) | (ONEBOX_WIFI_MGMT_Q << 12));
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(BB_BUF_PROG_VALUES_REQ);
if (adapter->soft_reset & BBP_REMOVE_SOFT_RST_BEFORE_PROG)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(BBP_REMOVE_SOFT_RST_BEFORE_PROG);
}
if (adapter->soft_reset & BBP_REMOVE_SOFT_RST_AFTER_PROG)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(BBP_REMOVE_SOFT_RST_AFTER_PROG);
}
if (adapter->bb_rf_rw)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(BBP_REG_READ);
adapter->bb_rf_rw = 0;
}
adapter->soft_reset = 0;
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(num_of_vals);
#ifdef RF_8230
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16 (PUT_BBP_RESET | BBP_REG_WRITE | (NONRSI_RF_TYPE << 4));
#else
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16 (PUT_BBP_RESET | BBP_REG_WRITE | (RSI_RF_TYPE << 4));
#endif
//Flags are not handled FIXME:
//FIXME: What is the radio id to fill here
// mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16 (RADIO_ID << 8 );
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, (frame_len + FRAME_DESC_SZ ));
status_l = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, (frame_len + FRAME_DESC_SZ));
return status_l;
}
static ONEBOX_STATUS onebox_mgmt_send_rf_reset_req(PONEBOX_ADAPTER adapter,
uint16 *bb_prog_vals)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status_l;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,("ONEBOX_IOCTL: RF_RESET REQUEST\n"));
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("===> Frame request to reset RF<===\n")));
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, FRAME_DESC_SZ);
if (bb_prog_vals == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,("ONEBOX_IOCTL: RF_RESET REQUEST NULL PTR\n"));
return ONEBOX_STATUS_FAILURE;
}
/* FrameType*/
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(RF_RESET_FRAME);
mgmt_frame->desc_word[3] = ONEBOX_CPU_TO_LE16(bb_prog_vals[1] & 0x00ff);
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16((bb_prog_vals[2]) >> 8);
mgmt_frame->desc_word[0] = (ONEBOX_WIFI_MGMT_Q << 12);
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT( " RF_RESET: value is 0x%x, RF_DELAY: %d\n"),mgmt_frame->desc_word[3],mgmt_frame->desc_word[4]));
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, FRAME_DESC_SZ);
status_l = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, ( FRAME_DESC_SZ));
return status_l;
}
ONEBOX_STATUS bb_reset_req(PONEBOX_ADAPTER adapter)
{
uint16 bb_prog_vals[3];
bb_prog_vals[1] = 0x3;
bb_prog_vals[2] = 0xABAB;
if(onebox_mgmt_send_rf_reset_req(adapter, bb_prog_vals) != ONEBOX_STATUS_SUCCESS) {
return ONEBOX_STATUS_FAILURE;
}
return ONEBOX_STATUS_SUCCESS;
}
ONEBOX_STATUS onebox_ant_sel(PONEBOX_ADAPTER adapter,
uint8 value)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status_l;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,("ONEBOX_IOCTL: ANT_SEL REQUEST\n"));
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("===> Frame request to ANT_SEL <===\n")));
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, FRAME_DESC_SZ);
/* FrameType*/
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(ANT_SEL_FRAME);
mgmt_frame->desc_word[3] = ONEBOX_CPU_TO_LE16(value & 0x00ff);
mgmt_frame->desc_word[0] = (ONEBOX_WIFI_MGMT_Q << 12);
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT( " ANT_SEL: value is 0x%x, \n"),mgmt_frame->desc_word[3]));
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, FRAME_DESC_SZ);
status_l = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, ( FRAME_DESC_SZ));
return status_l;
}
static ONEBOX_STATUS onebox_mgmt_lmac_reg_ops_req(PONEBOX_ADAPTER adapter,
uint16 *prog_vals,
uint8 type)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status_l;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,("ONEBOX_IOCTL: LMAC_REG_OPS REQUEST\n"));
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("===> Frame request FOR LMAC_REG_OPS<===\n")));
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, FRAME_DESC_SZ);
if (prog_vals == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,("ONEBOX_IOCTL: LMAC_REG_OPS REQUEST NULL PTR\n"));
return ONEBOX_STATUS_FAILURE;
}
/* FrameType*/
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(LMAC_REG_OPS);
mgmt_frame->desc_word[3] = ONEBOX_CPU_TO_LE16(prog_vals[1]);
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(prog_vals[2]);
if (type == LMAC_REG_WRITE)
{
mgmt_frame->desc_word[5] = ONEBOX_CPU_TO_LE16(prog_vals[3]);
mgmt_frame->desc_word[6] = ONEBOX_CPU_TO_LE16(prog_vals[4]);
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16(0);// write Indication
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT( " LMAC_REG_OPS: type %d : addr is 0x%x, addr1 is 0x%x,\n \t \t Data: 0x%x\nData1: 0x%x\n"),
mgmt_frame->desc_word[7], mgmt_frame->desc_word[3],mgmt_frame->desc_word[4], mgmt_frame->desc_word[5],mgmt_frame->desc_word[6]));
}
else
{
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16(1); //Read Indication
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT( " LMAC_REG_OPS: type %d : addr is 0x%x, addr1 is 0x%x"),
mgmt_frame->desc_word[7], mgmt_frame->desc_word[3],mgmt_frame->desc_word[4]));
}
mgmt_frame->desc_word[0] = (ONEBOX_WIFI_MGMT_Q << 12);
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, FRAME_DESC_SZ);
status_l = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, ( FRAME_DESC_SZ));
return status_l;
}
#if 0
void load_calc_timer_values(PONEBOX_ADAPTER adapter)
{
uint16 short_slot_time=0;
uint16 long_slot_time=0 ;
uint16 ack_time=0;
uint16 in_sta_dist = 0;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO ,(TEXT("Loading Calculated values\n")));
ack_time = ( (2 * in_sta_dist) / 300) + 192;/*In micro sec*/
short_slot_time = ( in_sta_dist / 300) + 9;/*In micro sec*/
long_slot_time = ( in_sta_dist / 300) + 20;
adapter->short_slot_time = short_slot_time * 40;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO ,
(TEXT("short_slot_time:%d\n"),adapter->short_slot_time));
adapter->long_slot_time = long_slot_time * 40;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("long_slot_time:%d\n"),adapter->long_slot_time));
//adapter->short_difs_rx = 0x2F8;
adapter->short_difs_rx = (SIFS_DURATION +(1*short_slot_time)-6-11)*40;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("short_difs_rx:%d\n"), adapter->short_difs_rx));
/* DIFS = (2 * Slot_time + SIFS ) 1 slot will be added in the PPE */
//adapter->short_difs_tx = 0x3E8;
adapter->short_difs_tx = ((SIFS_DURATION +(1*short_slot_time)-6-2)*40);
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("short_difs_tx:%d\n"),adapter->short_difs_tx));
adapter->long_difs_rx = (SIFS_DURATION +(2*long_slot_time)-6-11)*40;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("long_difs_rx:%d\n"),adapter->long_difs_rx));
adapter->long_difs_tx = (SIFS_DURATION +(2*long_slot_time)-6-2)*40;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("long_difs_tx:%d\n"),adapter->long_difs_tx));
adapter->difs_g_delay = 240;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("difs_g_delay:%d\n"),adapter->difs_g_delay));
adapter->ack_timeout = (ack_time * 40 );
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("ACK timeout:%d\n"),adapter->ack_timeout));
return;
}
#endif
/**
* This function sends the start_autorate frame to the TA firmware.
* @param
* adapter Pointer to the driver private structure
*
* @returns
* ONEBOX_STATUS_SUCCESS on success, or corresponding negative
* error code on failure
*/
ONEBOX_STATUS start_autorate_stats(PONEBOX_ADAPTER adapter)
{
onebox_mac_frame_t *mgmt_frame;
uint8 pkt_buffer[FRAME_DESC_SZ];
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("%s: Starting autorate algo\n"), __func__));
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, MAX_MGMT_PKT_SIZE);
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(FRAME_DESC_SZ);
//mgmt.desc_word[0] |= ONEBOX_TA_MGMT_Q << 12;
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(MGMT_DESC_START_AUTORATE);
return onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, FRAME_DESC_SZ);
}
/**
* This function sends the radio capabilities to firmware
* @param
* adapter Pointer to the driver private structure
*
* @returns
* ONEBOX_STATUS_SUCCESS on success, or corresponding negative
* error code on failure
*/
ONEBOX_STATUS onebox_load_radio_caps(PONEBOX_ADAPTER adapter)
{
struct ieee80211com *ic = NULL;
struct chanAccParams wme;
struct chanAccParams wme_sta;
onebox_mac_frame_t *mgmt_frame;
uint16 inx = 0;
int32 status = 0;
uint16 pkt[256];
uint8 ii;
uint8 radio_id;
uint16 gc[20] = {0xf0, 0xf0, 0xf0, 0xf0,
0xf0, 0xf0, 0xf0, 0xf0,
0xf0, 0xf0, 0xf0, 0xf0,
0xf0, 0xf0, 0xf0, 0xf0,
0xf0, 0xf0, 0xf0, 0xf0};
FUNCTION_ENTRY(ONEBOX_ZONE_INIT);
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("%s: Sending rate symbol req frame\n"), __func__));
printk("Sending rate symbol req frame in %s:%d \n", __func__, __LINE__);
ic = &adapter->vap_com;
wme = ic->ic_wme.wme_wmeChanParams;
wme_sta = ic->ic_wme.wme_wmeChanParams;
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, 256);
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(RADIO_CAPABILITIES);
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(ic->ic_curchan->ic_ieee);
mgmt_frame->desc_word[4] |= ONEBOX_CPU_TO_LE16(RSI_RF_TYPE<<8);
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(ONEBOX_LMAC_CLOCK_FREQ_80MHZ); //FIXME Radio config info
if(adapter->operating_chwidth == BW_40Mhz)
{
printk("===> chwidth is 40Mhz <===\n");
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(ONEBOX_ENABLE_40MHZ);
if (adapter->endpoint_params.per_ch_bw)
{
mgmt_frame->desc_word[5] |= ONEBOX_CPU_TO_LE16(adapter->endpoint_params.per_ch_bw << 12); //FIXME PPE ACK rate info 2-upper is primary
mgmt_frame->desc_word[5] |= ONEBOX_CPU_TO_LE16(FULL_40M_ENABLE); //FIXME PPE ACK rate info 2-upper is primary
}
if(ic->band_flags & IEEE80211_CHAN_HT40)
{
//FIXME PPE ACK rate info 2-upper is primary
mgmt_frame->desc_word[5] = ONEBOX_CPU_TO_LE16(0);
printk("40Mhz: Programming the radio caps for 40Mhz mode\n");
if(ic->band_flags & IEEE80211_CHAN_HT40U)
{
printk("Lower 20 Enable\n");
mgmt_frame->desc_word[5] |= ONEBOX_CPU_TO_LE16(LOWER_20_ENABLE); //PPE ACK MASK FOR 11B
mgmt_frame->desc_word[5] |= ONEBOX_CPU_TO_LE16(LOWER_20_ENABLE >> 12); //FIXME PPE ACK rate info 2-upper is primary
}
else
{
printk("Upper 20 Enable\n");
mgmt_frame->desc_word[5] |= ONEBOX_CPU_TO_LE16(UPPER_20_ENABLE); //Indicates The primary channel is above the secondary channel
mgmt_frame->desc_word[5] |= ONEBOX_CPU_TO_LE16(UPPER_20_ENABLE >> 12); //FIXME PPE ACK rate info 2-upper is primary
}
}
}
radio_id = 0;
mgmt_frame->u.radio_caps.sifs_tx_11n = adapter->sifs_tx_11n;
mgmt_frame->u.radio_caps.sifs_tx_11b = adapter->sifs_tx_11b;
mgmt_frame->u.radio_caps.slot_rx_11n = adapter->slot_rx_11n;
mgmt_frame->u.radio_caps.ofdm_ack_tout = adapter->ofdm_ack_tout;
mgmt_frame->u.radio_caps.cck_ack_tout = adapter->cck_ack_tout;
mgmt_frame->u.radio_caps.preamble_type = adapter->preamble_type;
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(radio_id << 8); //radio_id
mgmt_frame->u.radio_caps.qos_params[0].cont_win_min_q = (1 << (wme_sta.cap_wmeParams[1].wmep_logcwmin)) - 1;
mgmt_frame->u.radio_caps.qos_params[0].cont_win_max_q = (1 << wme_sta.cap_wmeParams[1].wmep_logcwmax) - 1;
mgmt_frame->u.radio_caps.qos_params[0].aifsn_val_q = (wme_sta.cap_wmeParams[1].wmep_aifsn);
mgmt_frame->u.radio_caps.qos_params[0].txop_q = (wme_sta.cap_wmeParams[1].wmep_txopLimit << 5);
mgmt_frame->u.radio_caps.qos_params[1].cont_win_min_q = (1 << wme_sta.cap_wmeParams[0].wmep_logcwmin) - 1;
mgmt_frame->u.radio_caps.qos_params[1].cont_win_max_q = (1 << wme_sta.cap_wmeParams[0].wmep_logcwmax) - 1;
mgmt_frame->u.radio_caps.qos_params[1].aifsn_val_q = (wme_sta.cap_wmeParams[0].wmep_aifsn-2);
//mgmt_frame->u.radio_caps.qos_params[1].aifsn_val_q = (wme_sta.cap_wmeParams[0].wmep_aifsn);
mgmt_frame->u.radio_caps.qos_params[1].txop_q = (wme_sta.cap_wmeParams[0].wmep_txopLimit << 5);
mgmt_frame->u.radio_caps.qos_params[4].cont_win_min_q = (1 << wme.cap_wmeParams[1].wmep_logcwmin) - 1;
mgmt_frame->u.radio_caps.qos_params[4].cont_win_max_q = (1 << wme.cap_wmeParams[1].wmep_logcwmax) - 1;
mgmt_frame->u.radio_caps.qos_params[4].aifsn_val_q = (wme.cap_wmeParams[1].wmep_aifsn );
mgmt_frame->u.radio_caps.qos_params[4].txop_q = (wme.cap_wmeParams[1].wmep_txopLimit << 5);
mgmt_frame->u.radio_caps.qos_params[5].cont_win_min_q = (1 << wme.cap_wmeParams[0].wmep_logcwmin) - 1;
mgmt_frame->u.radio_caps.qos_params[5].cont_win_max_q = (1 << wme.cap_wmeParams[0].wmep_logcwmax) - 1;
mgmt_frame->u.radio_caps.qos_params[5].aifsn_val_q = (wme.cap_wmeParams[0].wmep_aifsn);
mgmt_frame->u.radio_caps.qos_params[5].txop_q = (wme.cap_wmeParams[0].wmep_txopLimit << 5);
for(ii = 2; ii < MAX_HW_QUEUES - 8; ii++)
{
/* FIXME: Num of AC's are mapped to 4 How to fill in for Q4-Q7 */
mgmt_frame->u.radio_caps.qos_params[ii].cont_win_min_q = (1 << wme_sta.cap_wmeParams[ii].wmep_logcwmin) - 1;
mgmt_frame->u.radio_caps.qos_params[ii].cont_win_max_q = (1 << wme_sta.cap_wmeParams[ii].wmep_logcwmax) - 1;
if(ii != 5)
mgmt_frame->u.radio_caps.qos_params[ii].aifsn_val_q = (wme_sta.cap_wmeParams[ii].wmep_aifsn -1);
else
mgmt_frame->u.radio_caps.qos_params[ii].aifsn_val_q = (wme_sta.cap_wmeParams[ii].wmep_aifsn );
mgmt_frame->u.radio_caps.qos_params[ii].txop_q = (wme_sta.cap_wmeParams[ii].wmep_txopLimit << 5);
mgmt_frame->u.radio_caps.qos_params[ii + 4].cont_win_min_q = (1 << wme.cap_wmeParams[ii].wmep_logcwmin);
mgmt_frame->u.radio_caps.qos_params[ii + 4].cont_win_max_q = (1 << wme.cap_wmeParams[ii].wmep_logcwmax);
mgmt_frame->u.radio_caps.qos_params[ii + 4].aifsn_val_q = (wme.cap_wmeParams[ii].wmep_aifsn -1);
mgmt_frame->u.radio_caps.qos_params[ii + 4].txop_q = (wme.cap_wmeParams[ii].wmep_txopLimit << 5);
}
for(ii = 0; ii < MAX_HW_QUEUES ; ii++)
{
/* FIXME: Num of AC's are mapped to 4 How to fill in for Q4-Q7 */
if(!(mgmt_frame->u.radio_caps.qos_params[ii].cont_win_min_q))
{
/* Contention window Min is zero indicates that parameters for this queue are not assigned
* Hence Assigning them to defaults */
mgmt_frame->u.radio_caps.qos_params[ii].cont_win_min_q = 7;
mgmt_frame->u.radio_caps.qos_params[ii].cont_win_max_q = 0x3f;
mgmt_frame->u.radio_caps.qos_params[ii].aifsn_val_q = 2;
mgmt_frame->u.radio_caps.qos_params[ii].txop_q = 0;
}
}
/*Need to write MACROS for Queue_Nos*/
mgmt_frame->u.radio_caps.qos_params[BROADCAST_HW_Q].txop_q = 0xffff;
mgmt_frame->u.radio_caps.qos_params[MGMT_HW_Q].txop_q = 0;
mgmt_frame->u.radio_caps.qos_params[BEACON_HW_Q].txop_q = 0xffff;
adapter->os_intf_ops->onebox_memcpy(&adapter->rps_rate_mcs7_pwr, &gc[0], 40);
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_01_pwr & 0x00FF)); /*1*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_02_pwr & 0x00FF)); /*2*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_5_5_pwr & 0x00FF)); /*5.5*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_11_pwr & 0x00FF)); /*11*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_48_pwr & 0x00FF)); /*48*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_24_pwr & 0x00FF)); /*24*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_12_pwr & 0x00FF)); /*12*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_06_pwr & 0x00FF)); /*6*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_54_pwr & 0x00FF)); /*54*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_36_pwr & 0x00FF)); /*36*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_18_pwr & 0x00FF)); /*18*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_09_pwr & 0x00FF)); /*9*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_mcs0_pwr & 0x00FF)); /*MCS0*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_mcs1_pwr & 0x00FF)); /*MCS1*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_mcs2_pwr & 0x00FF)); /*MCS2*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_mcs3_pwr & 0x00FF)); /*MCS3*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_mcs4_pwr & 0x00FF)); /*MCS4*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_mcs5_pwr & 0x00FF)); /*MCS5*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx++] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_mcs6_pwr & 0x00FF)); /*MCS6*/
mgmt_frame->u.radio_caps.gcpd_per_rate[inx] = ONEBOX_CPU_TO_LE16((adapter->rps_rate_mcs7_pwr & 0x00FF)); /*MCS7*/
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(sizeof(mgmt_frame->u.radio_caps) | (ONEBOX_WIFI_MGMT_Q << 12));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_MGMT_DUMP, (PUCHAR)mgmt_frame, sizeof(mgmt_frame->u.radio_caps) + FRAME_DESC_SZ);
ONEBOX_DEBUG(ONEBOX_ZONE_MGMT_DUMP, (TEXT("===> RADIO CAPS FRAME SENT <===\n")));
status = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, (sizeof(mgmt_frame->u.radio_caps)+ FRAME_DESC_SZ));
if (status == ONEBOX_STATUS_FAILURE)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Unable to send radio caps frame\n")));
return ONEBOX_STATUS_FAILURE;
}
FUNCTION_EXIT(ONEBOX_ZONE_INIT);
return ONEBOX_STATUS_SUCCESS;
}
/**
* This function sends the configuration values to firmware
* @param
* adapter Pointer to the driver private structure
*
* @returns
* ONEBOX_STATUS_SUCCESS on success, or corresponding negative
* error code on failure
*/
static ONEBOX_STATUS onebox_load_config_vals(PONEBOX_ADAPTER adapter)
{
uint16 onebox_config_vals[] =
{ 19, /* num params */
0x1, /* internalPmuEnabled */
0x0, /* ldoControlRequired */
0x9, /* crystalFrequency values */
/* 9 --> 40MHz, 8 --> 20MHz 7 --> 44MHz 6 --> 52MHz */
/* 5 --> 26MHz, 4 --> 13MHz 2 --> 38.4MHz 1 --> 19.2MHz */
/* 0 --> 9.6MHz */
0x2D, /* crystalGoodTime */
0x0, /* TAPLLEnabled */
#ifndef USE_KTV_INTF
0, /* TAPLLFrequency */
#else
40, /* TAPLLFrequency */
#endif
0x2, /* sleepClockSource */
0x0, /* voltageControlEnabled */
#ifndef USE_KTV_INTF
5200, /* wakeupThresholdTime */
#else
6500, /* wakeupThresholdTime */
#endif
0x0, /* reserved */
0x0, /* reserved */
0x0, /* reserved */
0x0, /* host based wkup enable */
0x0, /* FR4 enable */
0x0, /* BT Coexistence */
0x0, /* host based interrupt enable */
0x0, /* host wakeup_active_high */
0x0, /* xtal_ip_enable */
0x0 /* external PA*/
};
/* Driver Expecting Only 19 paramaeters */
if (onebox_config_vals[0] == 19)
{
adapter->os_intf_ops->onebox_memcpy(&adapter->config_params, &onebox_config_vals[1], 38);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_INIT, (PUCHAR)&adapter->config_params, 38);
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Wrong Number of Config params found\n"), __func__));
return ONEBOX_STATUS_FAILURE;
} /* End if <condition> */
return ONEBOX_STATUS_SUCCESS;
}
static void onebox_eeprom_read_band(PONEBOX_ADAPTER adapter)
{
printk("Reading EEPROM RF TYPE\n" );
adapter->eeprom.length = ((WLAN_MAC_MAGIC_WORD_LEN + 3) & (~3)); /* 4 bytes are read to extract RF TYPE , always read dword aligned */
adapter->eeprom.offset = WLAN_EEPROM_RFTYPE_ADDR; /* Offset val to read RF type is zero */
if(eeprom_read(adapter) == ONEBOX_STATUS_SUCCESS)
{
adapter->fsm_state = FSM_EEPROM_READ_RF_TYPE;
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Unable to Read RF type %d, len %d\n"), __func__, adapter->eeprom.offset, adapter->eeprom.length));
adapter->operating_band = BAND_2_4GHZ;
}
return;
}
/**
* This function receives the management packets from the hardware and process them
*
* @param
* adapter Pointer to driver private structure
* @param
* msg Received packet
* @param
* len Length of the received packet
*
* @returns
* ONEBOX_STATUS_SUCCESS on success, or corresponding negative
* error code on failure
*/
int32 onebox_mgmt_pkt_recv(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb)
{
uint16 msg_type;
int32 msg_len;
uint8 sub_type;
uint8 status;
uint8 associd;
uint8 *msg;
uint8 sta_id ;
uint32 path = 0;
struct ieee80211com *ic = &adapter->vap_com;
struct ieee80211vap *vap =NULL;
const struct ieee80211_node_table *nt = &ic->ic_sta;
struct ieee80211_node *ni =NULL;
#ifdef PWR_SAVE_SUPPORT
uint16 confirm_type;
#ifdef ENABLE_DEEP_SLEEP
//pwr_save_params ps_params;
#endif
#endif
//EEPROM_READ read_buf;
FUNCTION_ENTRY(ONEBOX_ZONE_MGMT_RCV);
msg = netbuf_cb->data;
msg_len = (*(uint16 *)&msg[0] & 0x0fff);
/*Type is upper 5bits of descriptor */
msg_type = (msg[2] );
sub_type = (msg[15] & 0xff);
ONEBOX_DEBUG(ONEBOX_ZONE_MGMT_RCV,(TEXT("Rcvd Mgmt Pkt Len = %d type =%04x subtype= %02x\n"), msg_len, msg_type, sub_type));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_MGMT_RCV, msg, msg_len);
ONEBOX_DEBUG(ONEBOX_ZONE_MGMT_RCV,
(TEXT("WLAN Msg Len: %d, Msg Type: %4x\n"), msg_len, msg_type));
switch (adapter->fsm_state)
{
#if 0 /* coex */
case FSM_CARD_NOT_READY:
{
if (msg_type == CARD_READY_IND)
{
ONEBOX_DEBUG(ONEBOX_ZONE_FSM, (TEXT("CARD READY RECVD\n")));
/* initializing tx soft queues */
for (count = 0; count < NUM_SOFT_QUEUES; count++)
{
adapter->os_intf_ops->onebox_netbuf_queue_init(&adapter->host_tx_queue[count]);
}
if (onebox_umac_init_done(adapter)!= ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
read_reg_parameters(adapter);
if(onebox_load_bootup_params(adapter) == ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_FSM,
(TEXT("%s: BOOTUP Parameters loaded successfully\n"),__func__));
adapter->fsm_state = FSM_LOAD_BOOTUP_PARAMS ;
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT ("%s: Failed to load bootup parameters\n"),
__func__));
}
}
}
#ifndef FPGA_VALIDATION
break;
#endif
#endif /* 0 coex */
case FSM_LOAD_BOOTUP_PARAMS:
{
#ifndef FPGA_VALIDATION
if (msg_type == TA_CONFIRM_TYPE && sub_type == BOOTUP_PARAMS_REQUEST)
{
ONEBOX_DEBUG(ONEBOX_ZONE_FSM,
(TEXT("%s: Received bootup parameters confirm sucessfully\n"),__FUNCTION__));
#endif
if (adapter->Driver_Mode == QSPI_FLASHING)
{
adapter->fsm_state = FSM_MAC_INIT_DONE;
break;
}
adapter->eeprom.length = (IEEE80211_ADDR_LEN + WLAN_MAC_MAGIC_WORD_LEN
+ WLAN_HOST_MODE_LEN);
adapter->eeprom.offset = WLAN_MAC_EEPROM_ADDR;
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Read MAC Addr %d, len %d\n"), __func__, adapter->eeprom.offset, adapter->eeprom.length));
if(eeprom_read(adapter) == ONEBOX_STATUS_SUCCESS)
{
adapter->fsm_state = FSM_EEPROM_READ_MAC_ADDR;
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s %d:Unable to read from EEPROM \n"), __func__, __LINE__));
adapter->fsm_state = FSM_CARD_NOT_READY;
}
#ifndef FPGA_VALIDATION
}
#endif
}
break;
case FSM_EEPROM_READ_MAC_ADDR:
{
if (msg_type == TA_CONFIRM_TYPE && sub_type == EEPROM_READ_TYPE)
{
ONEBOX_DEBUG(ONEBOX_ZONE_FSM,
(TEXT("%s: Received MAC Addr read confirmed \n"),__FUNCTION__));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, (16 +msg_len));
if (msg_len > 0)
{
if (msg[16] == MAGIC_WORD)
{
adapter->os_intf_ops->onebox_memcpy((PVOID)(adapter->mac_addr),
&msg[FRAME_DESC_SZ + WLAN_HOST_MODE_LEN + WLAN_MAC_MAGIC_WORD_LEN], IEEE80211_ADDR_LEN);
//adapter->os_intf_ops->onebox_fill_mac_address(adapter);
adapter->os_intf_ops->onebox_memcpy(adapter->dev->dev_addr,
adapter->mac_addr, ETH_ALEN);
}
else
{
if (!adapter->calib_mode)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: UNABLE TO READ MAC_ADDR \n"),__FUNCTION__));
#ifndef CHIP_9116
adapter->fsm_state = FSM_CARD_NOT_READY;
break;
#endif
}
}
}
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, adapter->mac_addr, (IEEE80211_ADDR_LEN));
onebox_eeprom_read_band(adapter);
break;
case FSM_EEPROM_READ_RF_TYPE:
printk("CONFIRM FOR RF TYPE READ CAME\n");
if (msg_type == TA_CONFIRM_TYPE && sub_type == EEPROM_READ_TYPE)
{
ONEBOX_DEBUG(ONEBOX_ZONE_FSM,
(TEXT("%s: Received EEPROM RF type read confirmed \n"),__func__));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, (16 +msg_len));
#ifdef CHIP_9116
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("!!!! Dual band supported!!!!!\n")));
printk("!!!! Dual band supported!!!!!\n");
adapter->operating_band = BAND_5GHZ;
adapter->band_supported = 1;
#else
if (msg[16] == MAGIC_WORD)
{
if((msg[17] & 0x3) == 0x3)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("!!!! Dual band supported!!!!!\n")));
printk("!!!! Dual band supported!!!!!\n");
adapter->operating_band = BAND_5GHZ;
adapter->band_supported = 1;
}
else if((msg[17] & 0x3) == 0x1)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("!!!! 2.4Ghz band supported!!!!!\n")));
printk("!!!! 2.4Ghz band supported!!!!!\n");
adapter->operating_band = BAND_2_4GHZ;
adapter->band_supported = 0;
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Magic word present, But valid band is not present\n")));
adapter->fsm_state=FSM_CARD_NOT_READY;
break;
}
}
else
{
if (!adapter->calib_mode)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("No Magic word present, Defaulting to 2.4Ghz\n")));
adapter->fsm_state=FSM_CARD_NOT_READY;
break;
}
}
#endif
adapter->core_ops->onebox_net80211_attach(adapter);
}
if(onebox_send_reset_mac(adapter) == 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_FSM,
(TEXT("%s: Reset MAC frame sent sucessfully\n"),__FUNCTION__));
adapter->fsm_state = FSM_RESET_MAC_CFM;
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT ("%s: Failed to load reset mac frame \n"), __FUNCTION__));
//FIXME: return from here ???
}
}
}
break;
case FSM_RESET_MAC_CFM:
{
if(msg_type == TA_CONFIRM_TYPE && sub_type == RESET_MAC_REQ)
{
ONEBOX_DEBUG(ONEBOX_ZONE_FSM, (TEXT("Reset mac confirm is received\n")));
//if (onebox_umac_init_done(adapter)!= ONEBOX_STATUS_SUCCESS)
{
// return ONEBOX_STATUS_FAILURE;
}
ONEBOX_DEBUG(ONEBOX_ZONE_FSM, (TEXT("sending radio caps \n")));
adapter->rx_filter_word = 0x0000;
adapter->sifs_tx_11n = SIFS_TX_11N_VALUE;
adapter->sifs_tx_11b = SIFS_TX_11B_VALUE;
adapter->slot_rx_11n = SHORT_SLOT_VALUE;
adapter->ofdm_ack_tout = OFDM_ACK_TOUT_VALUE;
adapter->cck_ack_tout = CCK_ACK_TOUT_VALUE;
adapter->preamble_type = LONG_PREAMBLE;
if(!onebox_load_radio_caps(adapter))
{
/*FIXME: Freeing the netbuf_cb as returning from here may not handle the netbuf free */
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
return ONEBOX_STATUS_FAILURE;
}
ONEBOX_DEBUG(ONEBOX_ZONE_FSM, (TEXT("Program BB/RF frames \n")));
}
if(msg_type == TA_CONFIRM_TYPE && sub_type == RADIO_CAPABILITIES)
{
adapter->rf_reset = 1;
printk(" RF_RESET AFTER at RESET REQ = :\n");
if(!program_bb_rf(adapter))
{
ONEBOX_DEBUG(ONEBOX_ZONE_FSM,
(TEXT("%s: BB_RF values loaded successfully\n"),__FUNCTION__));
adapter->fsm_state = FSM_BB_RF_START;
adapter->fsm_state = FSM_MAC_INIT_DONE;
}
}
}
break;
case FSM_BB_RF_START:
ONEBOX_DEBUG(ONEBOX_ZONE_FSM, (TEXT("In %s Line %d bb_rf_count %d\n"), __func__, __LINE__,adapter->bb_rf_prog_count));
if(((msg_type == TA_CONFIRM_TYPE) && ((sub_type == BB_PROG_VALUES_REQUEST)
|| (sub_type == RF_PROG_VALUES_REQUEST) || (sub_type == BBP_PROG_IN_TA) )))
{
adapter->bb_rf_prog_count--;
ONEBOX_DEBUG(ONEBOX_ZONE_DEBUG,
(TEXT(" FSM_STATE: BB RF count after receiving confirms for previous bb/rf frames %d\n"), adapter->bb_rf_prog_count));
if(!adapter->bb_rf_prog_count)
adapter->fsm_state = FSM_MAC_INIT_DONE;
}
break;
#if 0
case FSM_DEEP_SLEEP_ENABLE:
{
if(msg_type == TA_CONFIRM_TYPE && sub_type == DEEP_SLEEP_ENABLE)
{
ONEBOX_DEBUG(ONEBOX_ZONE_FSM,
(TEXT("%s: Received confirm for Deep sleep enable frame\n"), __func__));
}
}
break;
#endif
case FSM_AMPDU_IND_SENT:
{
if(msg_type == TA_CONFIRM_TYPE && sub_type == AMPDU_IND)
{
ONEBOX_DEBUG(ONEBOX_ZONE_FSM,
(TEXT("%s: Received confirm for ampdu indication frame\n"), __func__));
ONEBOX_DEBUG(ONEBOX_ZONE_OID, (TEXT("onebox_set_per_tx_mode: Enabling the PER burst mode\n")));
if (adapter->wlan_osd_ops->onebox_init_wlan_thread(&(adapter->sdio_scheduler_thread_handle_per),
"PER THREAD",
0,
adapter->wlan_osd_ops->onebox_per_thread,
adapter) != 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("onebox_set_per_tx_mode: Unable to initialize thread\n")));
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
return -EFAULT;
}
adapter->os_intf_ops->onebox_start_thread(&(adapter->sdio_scheduler_thread_handle_per));
adapter->tx_running = BURST_RUNNING;//indicating PER_BURST_MODE
}
adapter->fsm_state = FSM_MAC_INIT_DONE;
}
break;
case FSM_SCAN_CFM:
{
if((msg_type == TA_CONFIRM_TYPE) && (sub_type == SCAN_REQUEST))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT( "FSM_SCAN_CFM Received: \n")));
adapter->os_intf_ops->onebox_set_event(&(adapter->bb_rf_event));
}
}
break;
case FSM_MAC_INIT_DONE:
{
//printk("Msg type %d\n", msg_type);
if(msg_type == TA_CONFIRM_TYPE)
{
switch (sub_type)
{
case STATS_REQUEST_FRAME:
{
uint16 *framebody;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("\nPER STATS PACKET :\n")));
framebody = (uint16 *)&msg[16];
adapter->os_intf_ops->onebox_memset(&adapter->sta_info, 0, sizeof(per_stats));
adapter->os_intf_ops->onebox_memcpy((&adapter->sta_info), &msg[16], sizeof(per_stats));
#if 0
printk("tx_pkts = 0x%04x\n",adapter->sta_info.tx_pkts );
printk("tx_retries = 0x%04x\n", adapter->sta_info.tx_retries);
printk("xretries = 0x%04x\n", adapter->sta_info.xretries);
printk("rssi = 0x%x\n", adapter->sta_info.rssi);
printk("max_cons_pkts_dropped = 0x%04x\n", adapter->sta_info.max_cons_pkts_dropped);
#endif
ONEBOX_DEBUG(ONEBOX_ZONE_FSM,
(TEXT("%s: Sending Stats response frame\n"), __func__));
adapter->os_intf_ops->onebox_set_event(&(adapter->stats_event));
}
break;
case BB_PROG_VALUES_REQUEST:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"BBP PROG STATS: Utils BB confirm Received: msg_len: %d \n"),msg_len));
if ((msg_len) > 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"BBP PROG STATS: Utils BB confirm Received: msg_len -16 : %d \n"),msg_len));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, &msg[16], (msg_len));
adapter->os_intf_ops->onebox_memcpy((PVOID)(&adapter->bb_rf_read.Data[0]), &msg[16], (msg_len));
adapter->bb_rf_read.no_of_values = (msg_len)/2 ;
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"BBP PROG STATS: msg_len is : %d no of vls is %d \n"),msg_len,adapter->bb_rf_read.no_of_values));
adapter->os_intf_ops->onebox_set_event(&(adapter->bb_rf_event));
}
}
break;
case RF_PROG_VALUES_REQUEST:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"RF_PROG_STATS: Utils RF confirm Received: msg_len : %d \n"),msg_len));
if ((msg_len) > 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"RF_PROG_STATS: Utils RF confirm Received: msg_len -16 : %d \n"),msg_len));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, msg_len);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, &msg[16], (msg_len));
adapter->os_intf_ops->onebox_memcpy((PVOID)(&adapter->bb_rf_read.Data[0]), &msg[16], (msg_len));
adapter->bb_rf_read.no_of_values = (msg_len)/2 ;
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"RF_PROG_STATS: msg_len is : %d no of vls is %d \n"),msg_len,adapter->bb_rf_read.no_of_values));
adapter->os_intf_ops->onebox_set_event(&(adapter->bb_rf_event));
}
}
break;
case BB_BUF_PROG_VALUES_REQ:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"BBP_USING_BUFFER: Utils BUF confirm Received: msg_len : %d \n"),msg_len));
if ((msg_len) > 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"BBP_USING_BUFFER: Utils BUF confirm Received: msg_len -16 : %d \n"),msg_len));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, msg_len);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, &msg[16], (msg_len));
adapter->os_intf_ops->onebox_memcpy((PVOID)(&adapter->bb_rf_read.Data[0]), &msg[16], (msg_len));
adapter->bb_rf_read.no_of_values = (msg_len)/2 ;
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"BBP_USING_BUFFER: msg_len is : %d no of vls is %d \n"),msg_len,adapter->bb_rf_read.no_of_values));
adapter->os_intf_ops->onebox_set_event(&(adapter->bb_rf_event));
}
else if(adapter->bb_rf_params.value == 7) //BUFFER_WRITE
{
adapter->os_intf_ops->onebox_set_event(&(adapter->bb_rf_event));
}
break;
}
case LMAC_REG_OPS:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"LMAC_REG_OPS : Utils LMAC_REG_READ confirm Received: msg_len: %d \n"),msg_len));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, &msg[0], (16));
if ((msg_len) > 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"LMAC_REG_OPS : Utils LMAC_REG_OPS confirm Received: msg_len -16 : %d \n"),msg_len));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, &msg[16], (msg_len));
adapter->os_intf_ops->onebox_memcpy((PVOID)(&adapter->bb_rf_read.Data[0]), &msg[16], (msg_len));
adapter->bb_rf_read.no_of_values = (msg_len)/2 ;
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"LMAC_REG_OPS : msg_len is : %d no of vls is %d \n"),msg_len,adapter->bb_rf_read.no_of_values));
adapter->os_intf_ops->onebox_set_event(&(adapter->bb_rf_event));
}
}
break;
case CW_MODE_REQ:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"CW_MODE_REQ:: Utils CW_MODE_REQ: confirm Received: msg_len : %d \n"),msg_len));
adapter->os_intf_ops->onebox_set_event(&(adapter->bb_rf_event));
break;
}
case RF_LOOPBACK_REQ:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"BBP_USING_BUFFER: Utils RF_LOOPBACK_REQ confirm Received: msg_len : %d \n"),msg_len));
if ((msg_len) > 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"BBP_USING_BUFFER: Utils RF_LOOPBACK_REQ confirm Received: msg_len -16 : %d \n"),msg_len));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, msg_len);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"BBP_USING_BUFFER: msg_len is : %d no of vls is %d rf_lpbk: %d \n"),msg_len,adapter->bb_rf_read.no_of_values,adapter->rf_lpbk_len));
{
adapter->os_intf_ops->onebox_memcpy((PVOID)(&adapter->rf_lpbk_data[adapter->rf_lpbk_len]), &msg[16], (msg_len));
adapter->rf_lpbk_len += msg_len;
printk("rf_lpbk_len : %d,\n",adapter->rf_lpbk_len);
if (adapter->rf_lpbk_len >= (4096))
{
printk("SET EVENT rf_lpbk_len : %d,\n",adapter->rf_lpbk_len);
adapter->os_intf_ops->onebox_set_event(&(adapter->bb_rf_event));
}
else
{
printk("BREAK EVENT rf_lpbk_len : %d,\n",adapter->rf_lpbk_len);
break;
}
}
}
}
break;
case RF_LPBK_M3:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"BBP_USING_BUFFER: Utils RF_LPBK_REQ confirm Received: msg_len : %d \n"),msg_len));
if ((msg_len) > 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"BBP_USING_BUFFER: Utils RF_LPBK_M3_REQ confirm Received: msg_len -16 : %d \n"),msg_len));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, msg_len);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"BBP_USING_BUFFER: msg_len is : %d no of vls is %d rf_lpbk_m3: %d \n"),msg_len,adapter->bb_rf_read.no_of_values,adapter->rf_lpbk_len));
adapter->os_intf_ops->onebox_memcpy((PVOID)(&adapter->rf_lpbk_data[adapter->rf_lpbk_len]), &msg[16], (msg_len));
adapter->rf_lpbk_len += msg_len;
printk("rf_lpbk_len : %d,\n",adapter->rf_lpbk_len);
if (adapter->rf_lpbk_len >= (512))
{
printk("SET EVENT rf_lpbk_len : %d,\n",adapter->rf_lpbk_len);
adapter->os_intf_ops->onebox_set_event(&(adapter->bb_rf_event));
}
else
{
printk("BREAK EVENT rf_lpbk_len : %d,\n",adapter->rf_lpbk_len);
break;
}
}
}
break;
case BG_SCAN_PROBE_REQ:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("<==== Recv Bg scan complete event ======>\n")));
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap == NULL)
break;
else if (vap->iv_opmode == IEEE80211_M_STA)
{
adapter->net80211_ops->onebox_send_scan_done(vap);
}
}
}
break;
#ifdef PWR_SAVE_SUPPORT
case WAKEUP_SLEEP_REQUEST:
{
if(adapter->Driver_Mode != RF_EVAL_MODE_ON)
{
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap == NULL)
break;
else if (vap->iv_opmode == IEEE80211_M_STA)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("pwr save state PS_STATE %d \n"), PS_STATE));
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("PWR save token is %d \n"), *(uint16 *)&msg[12]));
confirm_type = *(uint16 *)&msg[12];
if((confirm_type == SLEEP_REQUEST)) {
path = PS_EN_REQ_CNFM_PATH;
}else if(confirm_type == WAKEUP_REQUEST){
path = PS_DIS_REQ_CNFM_PATH;
}
else {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("In %s Line %d Invalid confirm type %d\n"), __func__, __LINE__, confirm_type));
return ONEBOX_STATUS_FAILURE;
}
update_pwr_save_status(vap, PS_DISABLE, path);
break;
//adapter->net80211_ops->onebox_send_scan_done(vap);
}
}
}
}
break;
case DEV_SLEEP_REQUEST:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("<==== Recv device sleep request======>\n")));
}
break;
case DEV_WAKEUP_CNF:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("<==== Recv device wakeup confirm======>\n")));
#if 0
adapter->sleep_request_received = 0;
if(adapter->queues_have_pkts == 1){
schedule_pkt_for_tx(adapter);
}
#endif
}
break;
#endif
case SCAN_REQUEST:
{
// ONEBOX_DEBUG(ONEBOX_ZONE_DEBUG, (TEXT("SCAN confirm received\n")));
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap == NULL)
break;
else if (vap->iv_opmode == IEEE80211_M_STA)
{
if(vap->hal_priv_vap->passive)
{
printk("SCAN REQUEST CONFIRM RECIVED\n");
adapter->net80211_ops->onebox_send_probereq_confirm(vap);
vap->hal_priv_vap->passive = 0;
}
}
}
}
break;
case EEPROM_READ_TYPE:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"EEPROM_READ: confirm Received: \n")));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, 16);
if (msg_len > 0)
{
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, &msg[16], msg_len);
adapter->os_intf_ops->onebox_memcpy((PVOID)(&adapter->eeprom.data[0]), &msg[16], (msg_len));
printk(" eeprom length: %d, eeprom msg_len %d\n",adapter->eeprom.length, msg_len);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, &adapter->eeprom.data[0], adapter->eeprom.length);
}
adapter->os_intf_ops->onebox_set_event(&(adapter->bb_rf_event));
}
break;
case EEPROM_WRITE:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"EEPROM_WRITE: confirm Received: \n")));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, 16);
if (msg_len > 0)
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, &msg[16], msg_len);
adapter->os_intf_ops->onebox_set_event(&(adapter->bb_rf_event));
}
break;
default:
ONEBOX_DEBUG(ONEBOX_ZONE_MGMT_SEND,(TEXT("\nInvalid type in FSM_MAC_INIT_DONE :\n")));
break;
}
}
else if (msg_type == TX_STATUS_IND)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("\n STATUS IND subtype %02x:\n"), sub_type));
switch(sub_type)
{
case NULLDATA_CONFIRM:
{
status = msg[12];
associd = msg[13];
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if (vap->iv_opmode == IEEE80211_M_HOSTAP)
{
TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
{
if((ni->ni_associd & 0xff) == associd)
{
if(status)
{
ni->ni_inact = ni->ni_inact_reload;
printk("In %s line %d:inact timer reloaded %d\n", __func__, __LINE__, ni->ni_inact);
} else {
printk("In %s line %d:keepalive confirm failed\n", __func__, __LINE__);
break;
}
}
}
}
}
}
break;
case EAPOL4_CONFIRM:
{
if(msg[12])
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("<==== Received EAPOL4 CONFIRM ======>\n")));
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if (vap->iv_opmode == IEEE80211_M_STA)
{
vap->hal_priv_vap->conn_in_prog = 0;
adapter->sta_mode.eapol4_cnfrm = 1;
printk("In %s Line %d eapol %d ptk %d sta_block %d ap_block %d\n", __func__, __LINE__,
adapter->sta_mode.eapol4_cnfrm, adapter->sta_mode.ptk_key, adapter->sta_data_block, adapter->block_ap_queues);
if((adapter->sta_mode.ptk_key) &&
(adapter->sta_mode.eapol4_cnfrm) &&
(adapter->sta_data_block)) {
onebox_send_block_unblock(vap, STA_CONNECTED, 0);
}
if(adapter->sta_mode.ptk_key && adapter->sta_mode.gtk_key && adapter->sta_mode.eapol4_cnfrm) {
printk("Resting ptk ket variable in %s Line %d \n", __func__, __LINE__);
adapter->sta_mode.ptk_key = 0;
printk("calling update_pwr_save_status In %s Line %d\n", __func__, __LINE__);
update_pwr_save_status(vap, PS_ENABLE, CONNECTED_PATH);
}
break;
}
}
}
else
{
printk("EAPOL4 failed Doesn't had sta_id vap_id\n");
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if (vap->iv_opmode == IEEE80211_M_STA)
{
ni = vap->iv_bss;
if(ni)
adapter->net80211_ops->onebox_ieee80211_sta_leave(ni);
}
}
// FIXME:vap_id should be handled here
//adapter->sta_mode.ptk_key = 0;
//hal_load_key(adapter, NULL, 0, adapter->sta_mode.sta_id, ONEBOX_PAIRWISE_KEY, 0,
// adapter->sec_mode[0], adapter->hal_vap[adapter->sta_mode.vap_id].vap);
//hal_load_key(adapter, NULL, 0, 0, ONEBOX_PAIRWISE_KEY, 0, adapter->sec_mode[vap_id]);
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
return 0;
}
}
break;
case PROBEREQ_CONFIRM :
{
if((uint16)msg[12])
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("<==== Recv PROBEREQ CONFIRM ======>\n")));
}
else
{
printk("Probe Request Failed \n");
}
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if (vap->iv_opmode == IEEE80211_M_STA)
{
adapter->net80211_ops->onebox_send_probereq_confirm(vap);
}
}
}
break;
default:
ONEBOX_DEBUG(ONEBOX_ZONE_MGMT_DUMP,(TEXT("\nInvalid type in FSM_MAC_INIT_DONE %02x :\n"), sub_type));
break;
}
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, msg_len);
}
else if(msg_type == DEBUG_IND)
{
printk("Received debug frame of len %d\n", msg_len);
dump_debug_frame(msg, msg_len);
}
else if (msg_type == HW_BMISS_EVENT)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Beacon miss occured..! Indicate the same to Net80211 state machine\n")));
adapter->net80211_ops->ieee80211_beacon_miss(&adapter->vap_com);
}
else if (msg_type == TSF_SYNC_CONFIRM)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Recvd TSF SYNC CONFIRM\n")));
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR ,(TEXT("\n STA_ID %02x TSF_LSB is %02x \n"), msg[13], *(uint32 *)&msg[16]) );
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR ,(TEXT("\n STA_ID %02x TSF_MSB is %02x \n"), msg[13], *(uint32 *)&msg[20]) );
sta_id = msg[13];
if(sta_id > MAX_STATIONS_SUPPORTED) {
printk("Invalid Station ID %s line %d\n", __func__, __LINE__);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, msg_len);
return -1;
}
ni = adapter->sta[sta_id].ni;
if(ni != NULL) {
if(ni->ni_vap->iv_opmode != IEEE80211_M_HOSTAP) {
printk("Invalid ni \n");
printk("Invalid Station ID %s line %d sta_id %d vap_opmode %d\n", __func__, __LINE__, sta_id, vap->iv_opmode);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, msg_len);
return ONEBOX_STATUS_FAILURE;
}
}else{
printk(" %s %d: Ni is NULL \n", __func__, __LINE__);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, msg_len);
return ONEBOX_STATUS_FAILURE;
}
ni->uapsd.eosp_tsf = *(uint32 *)&msg[16];
ni->uapsd.eosp_triggered = 0;
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, msg_len);
//adapter->net80211_ops->ieee80211_beacon_miss(&adapter->vap_com);
}
else if (msg_type == RATE_GC_TABLE_UPDATE) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR ,(TEXT(" <===== RATE GC TABLE UPDATE RECVD =====>\n")) );
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, msg_len);
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("Reached FSM state %d :Not an internal management frame\n"), adapter->fsm_state));
// adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, msg_len);
onebox_mgmt_pkt_to_core(adapter, netbuf_cb, msg_len, msg_type);
/* Freeing of the netbuf will be taken care in the above func itself. So, just return from here */
return ONEBOX_STATUS_SUCCESS;
}
}
break;
default:
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("Reached FSM state %d :Not an internal management frame\n"), adapter->fsm_state));
break;
}
} /* End switch (adapter->fsm_state) */
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
FUNCTION_EXIT(ONEBOX_ZONE_MGMT_RCV);
return ONEBOX_STATUS_SUCCESS;
}
/**
* Entry point of Management module
*
* @param
* adapter Pointer to driver private data
* @param
* msg Buffer recieved from the device
* @param
* msg_len Length of the buffer
* @return
* Status
*/
int onebox_mgmt_pkt_to_core(PONEBOX_ADAPTER adapter,
netbuf_ctrl_block_t *netbuf_cb,
int32 msg_len,
uint8 type)
{
int8 rssi;
struct ieee80211com *ic = &adapter->vap_com;
struct ieee80211vap *vap =NULL;
uint16 sta_flags;
uint8 conn_ni_mac[IEEE80211_ADDR_LEN];
struct ieee80211_node *ni;
uint32 vap_id;
uint8 *msg;
uint8 pad_bytes;
int8 chno;
uint32 sta_index=0;
FUNCTION_ENTRY(ONEBOX_ZONE_MGMT_RCV);
vap = TAILQ_FIRST(&ic->ic_vaps);
msg = netbuf_cb->data;
pad_bytes = msg[4];
rssi = *(uint16 *)(msg + 16);
chno = msg[15];
if (type == RX_DOT11_MGMT)
{
msg_len -= pad_bytes;
if ((msg_len <= 0) || (!msg))
{
ONEBOX_DEBUG(ONEBOX_ZONE_MGMT_SEND,
(TEXT("Invalid incoming message of message length = %d\n"), msg_len));
/*FIXME: Freeing the netbuf_cb as returning from here may not handle the netbuf free */
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
return ONEBOX_STATUS_FAILURE;
}
if(adapter->Driver_Mode == SNIFFER_MODE)
{
vap->hal_priv_vap->extended_desc_size = pad_bytes;
adapter->os_intf_ops->onebox_netbuf_adj(netbuf_cb, (FRAME_DESC_SZ));
}
else
{
adapter->os_intf_ops->onebox_netbuf_adj(netbuf_cb, (FRAME_DESC_SZ + pad_bytes));
}
#if 0
if( msg[FRAME_DESC_SZ + pad_bytes] == 0x80)
//if(buffer[0] == 0x50 || buffer[0] == 0x80)
{
if(vap->iv_state == IEEE80211_S_RUN)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("===> Beacon rcvd <===\n")));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, buffer, 30);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("===> vap->iv_myaddr = %02x:%02x:%02x <===\n"), vap->iv_myaddr[0], vap->iv_myaddr[1], vap->iv_myaddr[2]));
}
}
#endif
if(!(adapter->Driver_Mode == SNIFFER_MODE))
{
recv_onair_dump(adapter, netbuf_cb->data, netbuf_cb->len);
}
#ifdef PWR_SAVE_SUPPORT
//support_mimic_uapsd(adapter, buffer);
#endif
adapter->core_ops->onebox_indicate_pkt_to_net80211(adapter, netbuf_cb, rssi, chno);
return 0;
}
else if(type == PS_NOTIFY_IND)
{
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, 16);
adapter->os_intf_ops->onebox_memcpy(conn_ni_mac, (msg + 6), IEEE80211_ADDR_LEN);
// printk(" PS NOTIFY: connected station %02x:%02x:%02x:%02x:%02x:%02x\n", conn_ni_mac[0], conn_ni_mac[1],
// conn_ni_mac[2], conn_ni_mac[3], conn_ni_mac[4], conn_ni_mac[5]);
sta_flags = *(uint16 *) &msg[12]; /* station flags are defined in descriptor word6 */
vap_id = ((sta_flags & 0xC) >> 2);
for (sta_index = 0; sta_index < adapter->max_stations_supported; sta_index++)
{
if(!adapter->os_intf_ops->onebox_memcmp(adapter->sta[sta_index].mac_addr, &conn_ni_mac, ETH_ALEN))
{
ni = adapter->sta[sta_index].ni;
if(sta_index != ni->hal_priv_node.sta_id) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("ERROR: In %s Line %d The sta_id in Hal_station data structure and ni doesn't matches ni_sta_id %d hal_sta id %d\n"),
__func__, __LINE__, ni->hal_priv_node.sta_id, sta_index));
dump_stack();
return ONEBOX_STATUS_FAILURE;
}
break;
}
}
if(sta_index == adapter->max_stations_supported) /* In case if not already connected*/
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("ERROR: In %s Line %d The sta_id in Hal_station data structure and ni doesn't matches hal_sta id %d\n"),
__func__, __LINE__, sta_index));
dump_stack();
return ONEBOX_STATUS_FAILURE;
}
if(vap_id > 3)
{
printk("Vap_id is wrong in %s Line %d vap_id %d\n", __func__, __LINE__, vap_id );
/*Freeing the netbuf coming as input to this function as the upper layers don't take care of the freeing*/
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
return ONEBOX_STATUS_FAILURE;
}
IEEE80211_LOCK(ic);
if(!adapter->hal_vap[vap_id].vap_in_use) {
printk("ERROR: In %s Line %d vap_id %d is not installed\n", __func__, __LINE__, vap_id );
/*Freeing the netbuf coming as input to this function as the upper layers don't take care of the freeing*/
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
IEEE80211_UNLOCK(ic);
return ONEBOX_STATUS_FAILURE;
}
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap->hal_priv_vap->vap_id == vap_id)
{
break;
}
}
/* Find the node of the station */
if(!vap){
printk("Unable to find the vap##########vap_id %d \n", vap_id);
IEEE80211_UNLOCK(ic);
dump_stack();
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
return ONEBOX_STATUS_FAILURE;
}
if((&vap->iv_ic->ic_sta) == NULL)
{
printk("ERROR: In %s Line %d\n", __func__, __LINE__);
return ONEBOX_STATUS_FAILURE;
}
ni = adapter->net80211_ops->onebox_find_node(&vap->iv_ic->ic_sta, conn_ni_mac);
if(ni && (ni->ni_vap == vap))
{
//printk("Found the exact node\n");
}
else
{
printk("Unable to find the node so discarding\n");
/*Freeing the netbuf coming as input to this function as the upper layers don't take care of the freeing*/
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
IEEE80211_UNLOCK(ic);
return ONEBOX_STATUS_FAILURE;
}
if(sta_flags & STA_ENTERED_PS)
{
adapter->net80211_ops->onebox_node_pwrsave(ni, 1);
//printk("powersave: STA Entered into pwrsave\n");
/* Set the power management bit to indicate station entered into pwr save */
//ni->ni_flags |= IEEE80211_NODE_PWR_MGT;
}
else if(sta_flags & STA_EXITED_PS)
{
/* Reset the power management bit to indicate station came out of pwr save */
// printk("powersave: STA Exited from pwrsave\n");
//ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
adapter->net80211_ops->onebox_node_pwrsave(ni, 0);
}
IEEE80211_UNLOCK(ic);
}
else if(type == BEACON_EVENT_IND) {
vap_id = msg[15];
IEEE80211_LOCK(ic);
if(!adapter->hal_vap[vap_id].vap_in_use) {
printk("ERROR: In %s Line %d vap_id %d is not installed\n", __func__, __LINE__, vap_id );
/*Freeing the netbuf coming as input to this function as the upper layers don't take care of the freeing*/
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
IEEE80211_UNLOCK(ic);
return ONEBOX_STATUS_FAILURE;
}
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap->hal_priv_vap->vap_id == vap_id)
{
/* We set beacon interrupt only when VAP reaches RUN state, as firmware
* gives interrupt after sending vap_caps frame, so due to this there is
* a probabilty of sending beacon before programming channel as we give highest
* priority to beacon event in core_qos_processor.
*/
if((vap->iv_state == IEEE80211_S_RUN) && (!adapter->block_ap_queues))
{
adapter->beacon_event = 1;
adapter->beacon_event_vap_id = vap_id;
adapter->beacon_interrupt++;
//ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("Beacon Interrupt Received for vap_id %d \n"), vap_id));
adapter->os_intf_ops->onebox_set_event(&(adapter->sdio_scheduler_event));
}
}
}
IEEE80211_UNLOCK(ic);
}
else if(type == DECRYPT_ERROR_IND)
{
adapter->core_ops->onebox_mic_failure(adapter, msg);
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_MGMT_SEND,(TEXT ("Internal Packet\n")));
}
/*Freeing the netbuf coming as input to this function as the upper layers don't take care of the freeing*/
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
FUNCTION_EXIT(ONEBOX_ZONE_MGMT_RCV);
return 0;
}
/**
* Assigns the MAC address to the adapter
*
*/
ONEBOX_STATUS onebox_read_cardinfo(PONEBOX_ADAPTER adapter)
{
ONEBOX_STATUS status = 0;
EEPROM_READ mac_info_read;
mac_info_read.off_set = EEPROM_READ_MAC_ADDR;
mac_info_read.length = 6; /* Length in words i.e 3*2 = 6 bytes */
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("%s: Reading MAC address\n"), __func__));
// status = onebox_eeprom_read(adapter,(PEEPROM_READ)&mac_info_read);
if (status != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: EEPROM read Failed\n"), __func__));
}
return status;
}
int hal_set_sec_wpa_key(PONEBOX_ADAPTER adapter, const struct ieee80211_node *ni_sta, uint8 key_type)
{
return 0;
}
uint32 hal_send_sta_notify_frame(PONEBOX_ADAPTER adapter, struct ieee80211_node *ni, uint8 notify_event)
{
#define P2P_GRP_GROUP_OWNER 0x0
struct ieee80211vap *vap = NULL;
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
uint16 vap_id = 0;
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,
(TEXT("===> Sending Peer Notify Packet <===\n")));
vap = ni->ni_vap;
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, MAX_MGMT_PKT_SIZE);
/* Fill frame body */
switch(vap->iv_opmode)
{
case IEEE80211_M_STA:
{
/* connected peer is AP */
mgmt_frame->u.peer_notify.command = ONEBOX_CPU_TO_LE16((IEEE80211_OP_AP) << 1); //ap
break;
}
case IEEE80211_M_HOSTAP:
{
mgmt_frame->u.peer_notify.command = ONEBOX_CPU_TO_LE16((IEEE80211_OP_STA) << 1); //sta
break;
}
case IEEE80211_M_MBSS:
{
mgmt_frame->u.peer_notify.command = ONEBOX_CPU_TO_LE16((IEEE80211_OP_IBSS) << 1); //IBSS
break;
}
default:
printk("Invalid Mode\n");
return ONEBOX_STATUS_FAILURE;
}
vap_id = vap->hal_priv_vap->vap_id;
printk(" In %s and %d notify_event = %d vap_id %d sta_id %d \n", __func__, __LINE__, notify_event, vap_id, ni->hal_priv_node.sta_id);
switch(notify_event)
{
case STA_CONNECTED:
if(vap->iv_opmode == IEEE80211_M_STA) {
printk("Starting ifp queue \n");
vap->hal_priv_vap->stop_tx_q = 0;
adapter->os_intf_ops->onebox_start_ifp_txq(vap->iv_ifp);
}
mgmt_frame->u.peer_notify.command |= ONEBOX_ADD_PEER;
break;
case STA_DISCONNECTED:
mgmt_frame->u.peer_notify.command |= ONEBOX_DELETE_PEER;
if(!(vap->hal_priv_vap->roam_ind) && (vap->iv_opmode == IEEE80211_M_STA))
{
//adapter->sec_mode[vap_id] = IEEE80211_CIPHER_NONE;
}
ni->ni_flags &= ~IEEE80211_NODE_ENCRYPT_ENBL;
#ifdef BYPASS_RX_DATA_PATH
/** This should be changed based on STA ID in AP mode **/
if(vap->iv_opmode == IEEE80211_M_STA && (!adapter->sta_data_block))
{
onebox_send_block_unblock(vap, STA_DISCONNECTED, 0);
}
if(vap->iv_opmode == IEEE80211_M_STA) {
adapter->os_intf_ops->onebox_memset(&adapter->sta_mode.ptk_key, 0, sizeof(struct sta_conn_flags));
printk("In %s Line %d eapol %d ptk %d sta_block %d ap_block %d\n", __func__, __LINE__,
adapter->sta_mode.eapol4_cnfrm, adapter->sta_mode.ptk_key, adapter->sta_data_block, adapter->block_ap_queues);
if(adapter->traffic_timer.function)
adapter->os_intf_ops->onebox_remove_timer(&adapter->traffic_timer);
update_pwr_save_status(vap, PS_ENABLE, DISCONNECTED_PATH);
}
#endif
break;
case STA_ADDBA_DONE:
case STA_DELBA:
case STA_RX_ADDBA_DONE:
case STA_RX_DELBA:
/* FIXME: handle here */
status = onebox_send_ampdu_indication_frame(adapter, ni, notify_event);
return status;
break;
default:
break;
}
/* Fill the association id */
printk(" association id =%x and command =%02x\n", ni->ni_associd, mgmt_frame->u.peer_notify.command);
mgmt_frame->u.peer_notify.command |= ONEBOX_CPU_TO_LE16((ni->ni_associd & 0xfff) << 4);
adapter->os_intf_ops->onebox_memcpy(mgmt_frame->u.peer_notify.mac_addr, ni->ni_macaddr, ETH_ALEN);
/* FIXME: Fill ampdu/amsdu size, short gi, GF if supported here */
mgmt_frame->u.peer_notify.sta_flags |= ONEBOX_CPU_TO_LE32((ni->ni_flags & IEEE80211_NODE_QOS) ? 1 : 0); //connected ap is qos supported or not
/* Bit{0:11} indicates length of the Packet
* Bit{12:16} indicates host queue number
*/
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16((sizeof(mgmt_frame->u.peer_notify)) | ONEBOX_WIFI_MGMT_Q << 12);
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(PEER_NOTIFY);
// FIXME: IN AP Mode fill like this
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16(ni->hal_priv_node.sta_id | (vap_id << 8));
//mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16((vap_id << 8)); /* Peer ID is zero in sta mode */
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, sizeof(mgmt_frame->u.peer_notify) + FRAME_DESC_SZ);
//ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Sending peer notify frame\n")));
printk("IN %s Line %d Vap_id %d Sta_id %d pkt_queued to head\n", __func__, __LINE__, vap_id, ni->hal_priv_node.sta_id);
status = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, (sizeof(mgmt_frame->u.peer_notify)+ FRAME_DESC_SZ));
if(status)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Unable to send peer notify frame\n")));
return ONEBOX_STATUS_FAILURE;
}
printk("Opmode %d secmode %d \n", vap->iv_opmode, adapter->sec_mode[vap->hal_priv_vap->vap_id]);
if(!((vap->iv_flags & IEEE80211_F_WPA2) || (vap->iv_flags & IEEE80211_F_WPA1))
&& (vap->iv_flags & IEEE80211_F_PRIVACY))
{
/** WEP Mode */
printk("Key idx %d key_len %d \n ", adapter->wep_key_idx[vap_id], adapter->wep_keylen[vap_id][adapter->wep_key_idx[vap_id]]);
status = hal_load_key( adapter, adapter->wep_key[vap_id][0][0],
adapter->wep_keylen[vap_id][adapter->wep_key_idx[vap_id]],
ni->hal_priv_node.sta_id,
ONEBOX_PAIRWISE_KEY,
adapter->wep_key_idx[vap_id],
IEEE80211_CIPHER_WEP, vap);
if(vap->iv_opmode == IEEE80211_M_STA)
{
status = hal_load_key(adapter, adapter->wep_key[vap_id][0][0],
adapter->wep_keylen[vap_id][adapter->wep_key_idx[vap_id]],
ni->hal_priv_node.sta_id,
ONEBOX_GROUP_KEY,
adapter->wep_key_idx[vap_id],
IEEE80211_CIPHER_WEP, vap);
ni->ni_vap->hal_priv_vap->conn_in_prog = 0;
}
ni->ni_flags |= IEEE80211_NODE_ENCRYPT_ENBL;
}
else if((vap->iv_opmode == IEEE80211_M_STA)
&& (vap->iv_state == IEEE80211_S_RUN)
&& !(vap->iv_flags & IEEE80211_F_PRIVACY)) {
/** OPEN Mode **/
printk("In %s Line %d resetting conn_in_prog iv_state %d \n", __func__, __LINE__, vap->iv_state);
ni->ni_vap->hal_priv_vap->conn_in_prog = 0;
}
return ONEBOX_STATUS_SUCCESS;
}
#ifdef BYPASS_TX_DATA_PATH
ONEBOX_STATUS onebox_send_block_unblock(struct ieee80211vap *vap, uint8 notify_event, uint8 quiet_enable)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
struct net_device *parent_dev = vap->iv_ic->ic_ifp;
PONEBOX_ADAPTER adapter = netdev_priv(parent_dev);
struct ieee80211com *ic = vap->iv_ic;
struct ieee80211vap *vap_temp;
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, MAX_MGMT_PKT_SIZE);
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(ONEBOX_WIFI_MGMT_Q << 12);
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(BLOCK_UNBLOCK);
mgmt_frame->desc_word[3] = ONEBOX_CPU_TO_LE16(0x1);
if(notify_event == STA_DISCONNECTED)
{
printk("In %s Line %d \n", __func__, __LINE__);
vap->hal_priv_vap->sta_data_block = 1;
adapter->sta_data_block = 1;
if (quiet_enable)
mgmt_frame->desc_word[3] |= ONEBOX_CPU_TO_LE16(0x2); /* Enable QUIET */
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(0xf);
/* We may receive disconnect event when we have programmed the timer
* so stop timer first
*/
printk("Stopping the timer in %s Line %d\n", __func__, __LINE__);
ic->ic_stop_initial_timer(ic, vap);
if(!adapter->os_intf_ops->onebox_is_ifp_txq_stopped(vap->iv_ifp))
{
printk("Stopping ifp queue \n");
vap->hal_priv_vap->stop_tx_q = 1;
#ifndef WIFI_ALLIANCE
adapter->os_intf_ops->onebox_stop_ifp_txq(vap->iv_ifp);
#endif
}
}
else if(notify_event == STA_CONNECTED)
{
printk("In %s Line %d \n", __func__, __LINE__);
vap->hal_priv_vap->sta_data_block = 0;
adapter->sta_data_block = 0;
adapter->block_ap_queues = 0;
mgmt_frame->desc_word[5] = ONEBOX_CPU_TO_LE16(0xf);
}
if(adapter->block_ap_queues) {
mgmt_frame->desc_word[4] |= ONEBOX_CPU_TO_LE16(0xf << 4);
} else {
TAILQ_FOREACH(vap_temp, &ic->ic_vaps, iv_next)
{
if(vap_temp->iv_opmode == IEEE80211_M_HOSTAP) {
printk("Starting ifp queue at %s Line %d\n", __func__, __LINE__);
vap_temp->hal_priv_vap->stop_tx_q = 0;
adapter->os_intf_ops->onebox_start_ifp_txq(vap_temp->iv_ifp);
}
}
mgmt_frame->desc_word[5] |= ONEBOX_CPU_TO_LE16(0xf << 4);
}
//printk("<<<<<< BLOCK/UNBLOCK %d >>>>>>\n", notify_event);
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, (FRAME_DESC_SZ));
printk("In %s Line %d sta_block %d ap_data %d\n", __func__, __LINE__, adapter->sta_data_block, adapter->block_ap_queues);
status = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, FRAME_DESC_SZ);
if(status)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Unable to send BLOCK/UNBLOCK indication frame\n")));
return ONEBOX_STATUS_FAILURE;
}
return ONEBOX_STATUS_SUCCESS;
}
#endif
ONEBOX_STATUS onebox_send_ampdu_indication_frame(PONEBOX_ADAPTER adapter, struct ieee80211_node *ni, uint8 event)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
uint16 tidno;
/*FIXME: For ap mode get the peerid */
/* Fill peer_id in case of AP mode. For sta mode it is zero */
//uint8 peer_id = 0;
uint8 peer_id = ni->hal_priv_node.sta_id;
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,
(TEXT("===> Sending AMPDU Indication Packet <===\n")));
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, 256);
tidno = ni->hal_priv_node.tidnum;
/* Bit{0:11} indicates length of the Packet
* Bit{12:16} indicates host queue number
*/
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16((sizeof(mgmt_frame->u.ampdu_ind)) | ONEBOX_WIFI_MGMT_Q << 12);
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(AMPDU_IND);
printk("In %s and %d event %d \n", __func__, __LINE__, event);
if(event == STA_ADDBA_DONE)
{
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(ni->hal_priv_node.tid[tidno].seq_start);
mgmt_frame->desc_word[5] = ONEBOX_CPU_TO_LE16(ni->hal_priv_node.tid[tidno].baw_size);
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16(tidno | (START_AMPDU_AGGR << 4)| ( peer_id << 8));
}
else if(event == STA_RX_ADDBA_DONE)
{
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(ni->hal_priv_node.tid[tidno].seq_start);
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16(tidno | (START_AMPDU_AGGR << 4)| (RX_BA_INDICATION << 5) | ( peer_id << 8));
}
else if(event == STA_DELBA)
{
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16(tidno | (STOP_AMPDU_AGGR << 4)| (peer_id << 8));
}
else if(event == STA_RX_DELBA)
{
if(ni->hal_priv_node.delba_ind)
{
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16(tidno | (STOP_AMPDU_AGGR << 4)| (RX_BA_INDICATION << 5) | (peer_id << 8));
}
else
{
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16(tidno | (STOP_AMPDU_AGGR << 4)| (peer_id << 8));
}
}
//ONEBOX_DEBUG(ONEBOX_ZONE_MGMT_SEND, (TEXT("Sending ampdu indication frame\n")));
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_MGMT_SEND, (PUCHAR)mgmt_frame, sizeof(mgmt_frame->u.ampdu_ind) + FRAME_DESC_SZ);
status = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, (sizeof(mgmt_frame->u.ampdu_ind)+ FRAME_DESC_SZ));
if(status)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("Unable to send ampdu indication frame\n")));
return ONEBOX_STATUS_FAILURE;
}
return ONEBOX_STATUS_SUCCESS;
}
ONEBOX_STATUS onebox_send_internal_mgmt_frame(PONEBOX_ADAPTER adapter, uint16 *addr, uint16 len)
{
netbuf_ctrl_block_t *netbuf_cb = NULL;
ONEBOX_STATUS status = ONEBOX_STATUS_SUCCESS;
FUNCTION_ENTRY(ONEBOX_ZONE_MGMT_SEND);
netbuf_cb = adapter->os_intf_ops->onebox_alloc_skb(len);
if(netbuf_cb == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: Unable to allocate skb\n"), __func__));
status = ONEBOX_STATUS_FAILURE;
return status;
}
adapter->os_intf_ops->onebox_add_data_to_skb(netbuf_cb, len);
/*copy the internal mgmt frame to netbuf and queue the pkt */
adapter->os_intf_ops->onebox_memcpy((uint8 *)netbuf_cb->data, (uint8 *)addr, len);
netbuf_cb->data[1] |= BIT(7);/* Immediate Wakeup bit*/
netbuf_cb->flags |= INTERNAL_MGMT_PKT;
netbuf_cb->tx_pkt_type = WLAN_TX_M_Q;
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (uint8 *)netbuf_cb->data, netbuf_cb->len);
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_MGMT_SEND, (uint8 *)netbuf_cb->data, netbuf_cb->len);
adapter->os_intf_ops->onebox_netbuf_queue_tail(&adapter->host_tx_queue[MGMT_SOFT_Q], netbuf_cb->pkt_addr);
adapter->devdep_ops->onebox_schedule_pkt_for_tx(adapter);
return status;
}
ONEBOX_STATUS update_device_op_params(PONEBOX_ADAPTER adapter)
{
return ONEBOX_STATUS_SUCCESS;
}
/**
* This function is called after initial configuration is done.
* It starts the base band and RF programming
*
* @param
* adapter Pointer to hal private info structure
*
* @return
* 0 on success, -1 on failure
*/
ONEBOX_STATUS program_bb_rf(PONEBOX_ADAPTER adapter)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status;
uint8 pkt_buffer[FRAME_DESC_SZ];
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("===> Send BBP_RF_INIT frame in TA<===\n")));
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, FRAME_DESC_SZ);
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16( ONEBOX_WIFI_MGMT_Q << 12);
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(BBP_PROG_IN_TA);
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(adapter->endpoint);
mgmt_frame->desc_word[3] = ONEBOX_CPU_TO_LE16(adapter->rf_pwr_mode);
printk("#### in %s rf pwr mode is %d\n", __func__, adapter->rf_pwr_mode);
if(adapter->rf_reset)
{
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16 (RF_RESET_ENABLE);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("===> RF RESET REQUEST SENT <===\n")));
adapter->rf_reset = 0;
}
adapter->bb_rf_prog_count = 1;
#if 0
if(adapter->chw_flag)
{
if(adapter->operating_chwidth == BW_40Mhz)
{
mgmt_frame->desc_word[4] |= ONEBOX_CPU_TO_LE16(0x1 << 8); /*20 to 40 Bandwidth swicth*/
}
else
{
mgmt_frame->desc_word[4] |= ONEBOX_CPU_TO_LE16(0x2 << 8);/*40 to 20 Bandwidth switch */
}
adapter->chw_flag = 0;
}
#endif
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16 (PUT_BBP_RESET | BBP_REG_WRITE | (RSI_RF_TYPE << 4));
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, FRAME_DESC_SZ );
status = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, FRAME_DESC_SZ);
return status;
}
void onebox_init_chan_pwr_table(PONEBOX_ADAPTER adapter,
uint16 *bg_power_set,
uint16 *an_power_set)
{
uint8 ii = 0, cnt = 0, band = 0;
uint16 *low_indx, *med_indx, *high_indx;
uint16 *alow_indx, *amed_indx, *ahigh_indx;
if (adapter->eeprom_type >= EEPROM_VER2)
{
if (an_power_set == NULL)
{
/* In case of 2.4 GHz band, GC/PD values are given for only 3 channels */
cnt = 3;
band = BAND_2_4GHZ;
}
else
{
/* In case of 5 GHz band, GC/PD values are given for 8 channels */
cnt = 8;
band = BAND_5GHZ;
} /* End if <condition> */
for (ii = 0; ii < cnt; ii++)
{
if (band == BAND_2_4GHZ)
{
adapter->os_intf_ops->onebox_memset(&adapter->TxPower11BG[ii], 0, sizeof(CHAN_PWR_TABLE));
low_indx = (uint16 *) ((&bg_power_set[0] + (BG_PWR_VAL_LEN * ii)));
med_indx = (uint16 *) ((&bg_power_set[0] + (BG_PWR_VAL_LEN * ii) + 1));
high_indx = (uint16 *) ((&bg_power_set[0] + (BG_PWR_VAL_LEN * ii) + 2));
adapter->TxPower11BG[ii].mid_pwr = *med_indx;
adapter->TxPower11BG[ii].low_pwr = *low_indx;
adapter->os_intf_ops->onebox_memcpy(&adapter->TxPower11BG[ii].high_pwr[0],
high_indx,
(BG_PWR_VAL_LEN - 2) * 2);
}
else
{
adapter->os_intf_ops->onebox_memset(&adapter->TxPower11A[ii], 0, sizeof(CHAN_PWR_TABLE));
if (ii < 5)
{
/* Mapping between indices and channels is as follows
* 0 - 36 channel, 1 - 60 channel, 2 - 157 channel
* 3 - 120 channel, 4 - 11j channel
*/
alow_indx = ((&an_power_set[0] + (AN_PWR_VAL_LEN * ii)));
amed_indx = ((&an_power_set[0] + (AN_PWR_VAL_LEN * ii) + 1));
ahigh_indx = ((&an_power_set[0] + (AN_PWR_VAL_LEN * ii) + 2));
adapter->TxPower11A[ii].mid_pwr = *amed_indx;
adapter->TxPower11A[ii].low_pwr = *alow_indx;
adapter->os_intf_ops->onebox_memcpy(&adapter->TxPower11A[ii].high_pwr[0],
ahigh_indx,
(AN_PWR_VAL_LEN - 2) * 2);
}
else
{
/* For index 5 onwards, a single word of info is given, which needs
* to be applied to all rates and all pwr profiles. Mapping between
* channels and indices is as follows:
* 5 - 64 channel; 6 - 100 channel; 7 - 140 channel
*/
ahigh_indx = (&an_power_set[0] + (AN_PWR_VAL_LEN * 5) + (ii - 5));
/* FIXME - Anyways PD values are ignored as of now */
adapter->os_intf_ops->onebox_memset(&adapter->TxPower11A[ii],
*ahigh_indx,
(AN_PWR_VAL_LEN * 2));
} /* End if <condition> */
} /* End if <condition> */
} /* End for loop */
}
else
{
for (ii = 0; ii < 3; ii++)
{
adapter->os_intf_ops->onebox_memset(&adapter->TxPower11BG[ii], 0, sizeof(CHAN_PWR_TABLE));
adapter->os_intf_ops->onebox_memset(&adapter->TxPower11A[ii], 0, sizeof(CHAN_PWR_TABLE));
if (adapter->eeprom_type == EEPROM_VER1)
{
/* New EEPROM Map */
low_indx = (uint16 *) ((&bg_power_set[0] + (BG_PWR_VAL_LEN * ii)));
med_indx = (uint16 *) ((&bg_power_set[0] + (BG_PWR_VAL_LEN * ii) + 1));
high_indx = (uint16 *) ((&bg_power_set[0] + (BG_PWR_VAL_LEN * ii) + 2));
adapter->TxPower11BG[ii].mid_pwr = *med_indx;
adapter->TxPower11BG[ii].low_pwr = *low_indx;
adapter->os_intf_ops->onebox_memcpy(&adapter->TxPower11BG[ii].high_pwr[0],
high_indx,
(BG_PWR_VAL_LEN - 2) * 2);
if (adapter->RFType == ONEBOX_RF_8230)
{
alow_indx = ((&an_power_set[0] + (AN_PWR_VAL_LEN * ii)));
amed_indx = ((&an_power_set[0] + (AN_PWR_VAL_LEN * ii) + 1));
ahigh_indx = ((&an_power_set[0] + (AN_PWR_VAL_LEN * ii) + 2));
adapter->TxPower11A[ii].mid_pwr = *amed_indx;
adapter->TxPower11A[ii].low_pwr = *alow_indx;
adapter->os_intf_ops->onebox_memcpy(&adapter->TxPower11A[ii].high_pwr[0],
ahigh_indx,
(AN_PWR_VAL_LEN - 2) * 2);
}
}
else
{
if (adapter->RFType == ONEBOX_RF_8230)
{
if (adapter->operating_band == BAND_5GHZ)
{
adapter->power_mode = ONEBOX_PWR_HIGH;
}
ahigh_indx = ((&an_power_set[0] + (LEGACY_AN_PWR_VAL_LEN * ii)));
adapter->os_intf_ops->onebox_memcpy(&adapter->TxPower11A[ii].high_pwr[0],
ahigh_indx,
LEGACY_AN_PWR_VAL_LEN * 2);
}
low_indx = (uint16 *) ((&bg_power_set[0] + (LEGACY_BG_PWR_VAL_LEN * ii)));
med_indx = (uint16 *) ((&bg_power_set[0] + (LEGACY_BG_PWR_VAL_LEN * ii) + 1));
high_indx = (uint16 *) ((&bg_power_set[0] + (LEGACY_BG_PWR_VAL_LEN * ii) + 2));
adapter->TxPower11BG[ii].low_pwr = *low_indx;
adapter->TxPower11BG[ii].mid_pwr = *med_indx;
adapter->os_intf_ops->onebox_memcpy(&adapter->TxPower11BG[ii].high_pwr[0],
high_indx,
(LEGACY_BG_PWR_VAL_LEN - 2) * 2);
} /* End if <condition> */
} /* End for loop */
} /* End if <condition> */
return;
}
ONEBOX_STATUS set_vap_capabilities(struct ieee80211vap *vap, uint8 vap_status)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
PONEBOX_ADAPTER adapter = NULL;
uint8 opmode ;
struct ieee80211com *ic = NULL;
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,
(TEXT("===> Sending Vap Capabilities Packet <===\n")));
if(is_vap_valid(vap) < 0) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("ERROR: VAP is Not a valid pointer In %s Line %d, So returning Recvd vap_status %d\n "),
__func__, __LINE__, vap_status));
dump_stack();
return ONEBOX_STATUS_FAILURE;
}
adapter = (PONEBOX_ADAPTER)vap->hal_priv_vap->hal_priv_ptr;
ic = &adapter->vap_com;
opmode = vap->iv_opmode;
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, 256);
switch(opmode)
{
case IEEE80211_M_STA:
opmode = IEEE80211_OP_STA;
break;
case IEEE80211_M_HOSTAP:
opmode = IEEE80211_OP_AP;
//adapter->sta_data_block = 0; //FIXME: Handle during Multiple Vaps; Kept this for P2P mode
break;
case IEEE80211_M_IBSS:
opmode = IEEE80211_OP_IBSS;
break;
default:
/* FIXME: In case of P2P after connection if the device becomes GO indicate opmode in some way to firmware */
opmode = IEEE80211_OP_P2P_GO;
break;
}
/* Fill the length & host queue num */
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(sizeof(mgmt_frame->u.vap_caps) | (ONEBOX_WIFI_MGMT_Q << 12));
/* Fill the frame type */
mgmt_frame->desc_word[1] = (ONEBOX_CPU_TO_LE16(VAP_CAPABILITIES));
mgmt_frame->desc_word[2] |= (ONEBOX_CPU_TO_LE16(vap_status) << 8);
if (vap->p2p_enable) {
if (vap->p2p_mode == IEEE80211_P2P_GO) {
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(IEEE80211_OP_P2P_GO | adapter->ch_bandwidth << 8);
} else {
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(IEEE80211_OP_P2P_CLIENT | adapter->ch_bandwidth << 8);
}
} else {
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(opmode | adapter->ch_bandwidth << 8);
}
/* FIXME: Fill antenna Info here */
mgmt_frame->desc_word[5] = 0;
printk("In func %s Line %d Vap_id %d \n", __func__, __LINE__, vap->hal_priv_vap->vap_id);
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16((vap->hal_priv_vap->vap_id << 8) | (adapter->mac_id << 4) | adapter->radio_id);
//mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16((vap_id << 8) | (adapter->mac_id << 4) | adapter->radio_id);
/*Frame Body*/
//adapter->os_intf_ops->onebox_memcpy(mgmt_frame->u.vap_caps.mac_addr, adapter->mac_addr, IEEE80211_ADDR_LEN);
adapter->os_intf_ops->onebox_memcpy(mgmt_frame->u.vap_caps.mac_addr, vap->iv_myaddr, IEEE80211_ADDR_LEN);
//Default value for keep alive period is 90secs.
mgmt_frame->u.vap_caps.keep_alive_period = 90;
//adapter->os_intf_ops->onebox_memcpy(mgmt_frame->u.vap_caps.bssid, bssid, IEEE80211_ADDR_LEN);
if(ic->ic_flags & IEEE80211_F_USEPROT)
{
/* Enable this bit if a non erp station is present or if the sizeof the pkt is greater than RTS threshold*/
if(ic->ic_nonerpsta)
{
printk("Enabling self cts bit\n");
mgmt_frame->u.vap_caps.flags |= ONEBOX_CPU_TO_LE32(ONEBOX_SELF_CTS_ENABLE);
}
}
mgmt_frame->u.vap_caps.frag_threshold = ONEBOX_CPU_TO_LE16(2346);
mgmt_frame->u.vap_caps.rts_threshold = ONEBOX_CPU_TO_LE16(vap->iv_rtsthreshold);
mgmt_frame->u.vap_caps.default_mgmt_rate_bbpinfo = ONEBOX_CPU_TO_LE32(RSI_RATE_6);
mgmt_frame->u.vap_caps.beacon_miss_threshold = ONEBOX_CPU_TO_LE16(vap->iv_bmissthreshold);
if(adapter->operating_band == BAND_5GHZ)
{
mgmt_frame->u.vap_caps.default_ctrl_rate_bbpinfo = ONEBOX_CPU_TO_LE32(RSI_RATE_6);
printk("vap->iv_flags_ht = %x IEEE80211_FHT_USEHT40 = %x\n",vap->iv_flags_ht, IEEE80211_FHT_USEHT40);
if(vap->iv_flags_ht & IEEE80211_FHT_USEHT40)
{
if(ic->band_flags & IEEE80211_CHAN_HT40U)
{
/* primary channel is below secondary channel */
mgmt_frame->u.vap_caps.default_ctrl_rate_bbpinfo |= ONEBOX_CPU_TO_LE32(LOWER_20_ENABLE << 16);
}
else
{
/* primary channel is above secondary channel */
mgmt_frame->u.vap_caps.default_ctrl_rate_bbpinfo |= ONEBOX_CPU_TO_LE32((UPPER_20_ENABLE << 16));
}
printk("full 40 rate in vap caps\n");
}
}
else
{
mgmt_frame->u.vap_caps.default_ctrl_rate_bbpinfo = ONEBOX_CPU_TO_LE32(RSI_RATE_1);
/* 2.4 Ghz band */
if(ic->band_flags & IEEE80211_CHAN_HT40U)
{
/* primary channel is below secondary channel */
mgmt_frame->u.vap_caps.default_ctrl_rate_bbpinfo |= ONEBOX_CPU_TO_LE32(LOWER_20_ENABLE << 16);
}
else
{
/* primary channel is above secondary channel */
mgmt_frame->u.vap_caps.default_ctrl_rate_bbpinfo |= ONEBOX_CPU_TO_LE32((UPPER_20_ENABLE << 16));
}
}
mgmt_frame->u.vap_caps.default_data_rate_bbpinfo = ONEBOX_CPU_TO_LE32(0);
mgmt_frame->u.vap_caps.beacon_interval = ONEBOX_CPU_TO_LE16(ic->ic_bintval);
mgmt_frame->u.vap_caps.dtim_period = ONEBOX_CPU_TO_LE16(vap->iv_dtim_period);
//printk("VAP CAPABILITIES\n");
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, sizeof(mgmt_frame->u.vap_caps) + FRAME_DESC_SZ);
status = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, (sizeof(mgmt_frame->u.vap_caps) + FRAME_DESC_SZ));
if(status)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Unable to send vap capabilities frame\n")));
return ONEBOX_STATUS_FAILURE;
}
return ONEBOX_STATUS_SUCCESS;
}
ONEBOX_STATUS onebox_send_vap_dynamic_update_indication_frame(struct ieee80211vap *vap)
{
struct dynamic_s *dynamic_frame=NULL;
struct ieee80211com * ic=NULL;
PONEBOX_ADAPTER adapter =NULL;
ONEBOX_STATUS status;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
adapter = (PONEBOX_ADAPTER)vap->hal_priv_vap->hal_priv_ptr;
ic = &adapter->vap_com;
dynamic_frame = (struct dynamic_s *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(dynamic_frame, 0, 256);
dynamic_frame->desc_word[0] = ONEBOX_CPU_TO_LE16((sizeof(dynamic_frame->frame_body)) | (ONEBOX_WIFI_MGMT_Q << 12));
dynamic_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(VAP_DYNAMIC_UPDATE);
dynamic_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(vap->iv_rtsthreshold);
//dynamic_frame->desc_word[5] = ONEBOX_CPU_TO_LE16(vap->iv_fragthreshold );
dynamic_frame->desc_word[6] = ONEBOX_CPU_TO_LE16(vap->iv_bmissthreshold);
dynamic_frame->frame_body.keep_alive_period = ONEBOX_CPU_TO_LE16(vap->iv_keep_alive_period);
if(ic->ic_flags & IEEE80211_F_USEPROT) {
if((ic->ic_nonerpsta && (vap->iv_opmode == IEEE80211_M_HOSTAP))
|| (vap->iv_opmode == IEEE80211_M_STA)) {
printk("Enabling self cts bit\n");
dynamic_frame->desc_word[2] |= ONEBOX_CPU_TO_LE32(ONEBOX_SELF_CTS_ENABLE);
}
}
if(vap->hal_priv_vap->fixed_rate_enable) {
dynamic_frame->desc_word[3] |= ONEBOX_CPU_TO_LE16(ONEBOX_FIXED_RATE_EN); //Fixed rate is enabled
dynamic_frame->frame_body.data_rate = ONEBOX_CPU_TO_LE16(vap->hal_priv_vap->rate_hix);
}
dynamic_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16((vap->hal_priv_vap->vap_id << 8));
printk("IN %s Line %d VAP_ID %d\n", __func__, __LINE__, vap->hal_priv_vap->vap_id);
status = onebox_send_internal_mgmt_frame(adapter, (uint16 *)dynamic_frame, (sizeof(struct dynamic_s)));
if(status) {
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("Unable to send vap dynamic update indication frame\n")));
return ONEBOX_STATUS_FAILURE;
}
return ONEBOX_STATUS_SUCCESS;
}
/**
* This function load the station update frame to PPE
*
* @param
* hal_info Pointer to the hal information structure
* @param
* sta_offset sta_id of the station
* @param
* data Station update information buffer
* @param
* len Length of the station update frame
*
* @return
* This function returns ONEBOX_STATUS_SUCCESS if template loading
* is successful otherwise ONEBOX_STATUS_FAILURE.
*/
ONEBOX_STATUS hal_load_key(PONEBOX_ADAPTER adapter,
uint8 *data,
uint16 key_len,
uint16 sta_id,
uint8 key_type,
uint8 key_id,
uint32 cipher,
struct ieee80211vap *vap)
{
onebox_mac_frame_t *mgmt_frame;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
ONEBOX_STATUS status;
uint8 key_t1 = 0;
uint16 key_descriptor = 0;
struct ieee80211com *ic = NULL;
uint32 vap_id = vap->hal_priv_vap->vap_id;
FUNCTION_ENTRY(ONEBOX_ZONE_INFO);
ic = &adapter->vap_com;
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, 256);
switch (key_type)
{
case ONEBOX_GROUP_KEY:
/* Load the key into PPE*/
key_t1 = 1 << 1;
if(vap->iv_opmode == IEEE80211_M_HOSTAP)
{
key_descriptor = ONEBOX_BIT(7);
}
else {
printk("<==== Recvd Group Key ====>\n");
if((sta_id >= adapter->max_stations_supported) || !(adapter->sta_connected_bitmap[sta_id/32] & (BIT(sta_id%32)))) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT( " Invalid Sta_id %d in %s Line %d \n"),sta_id, __func__, __LINE__));
return -1;
}
}
break;
case ONEBOX_PAIRWISE_KEY:
/* Load the key into PPE */
printk("<==== Recvd Pairwise Key ====>\n");
if((sta_id >= adapter->max_stations_supported) || !(adapter->sta_connected_bitmap[sta_id/32] & (BIT(sta_id%32)))) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT( "ERROR: Invalid Sta_id %d in %s Line %d \n"),sta_id, __func__, __LINE__));
return -1;
}
key_t1 = 0 << 1;
if(cipher != IEEE80211_CIPHER_WEP)
{
key_id = 0;
}
break;
}
key_descriptor |= key_t1 | ONEBOX_BIT(13) | (key_id << 14);
if(cipher == IEEE80211_CIPHER_WEP)
{
key_descriptor |= ONEBOX_BIT(2);
if(key_len >= 13)
{
key_descriptor |= ONEBOX_BIT(3);
}
}
else if(cipher != IEEE80211_CIPHER_NONE)
{
key_descriptor |= ONEBOX_BIT(4);
if(cipher == IEEE80211_CIPHER_TKIP)
{
key_descriptor |= ONEBOX_BIT(5);
}
}
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(sizeof(mgmt_frame->u.set_key) | (ONEBOX_WIFI_MGMT_Q << 12));
mgmt_frame->desc_word[1] = (ONEBOX_CPU_TO_LE16(SET_KEY));
// mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16((key_t1) | (1<<13)| (key_id <<14) | (1<<4) | (1<<5));
// mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16((key_descriptor) | (1<<5) | (1<<4));
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16((key_descriptor));
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16((sta_id));
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(vap_id << 8);
printk("In %s Line %d sta_id %d vap_id %d key_type %d\n", __func__, __LINE__, sta_id, vap_id, key_type );
//ONEBOX_DEBUG(ONEBOX_ZONE_DEBUG, (TEXT("In %s %d \n"), __func__, __LINE__));
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)data, FRAME_DESC_SZ);
//adapter->os_intf_ops->onebox_memcpy(&mgmt_frame->u.set_key.key, data, 16);
//adapter->os_intf_ops->onebox_memcpy(&mgmt_frame->u.set_key.tx_mic_key, &data[16], 16);
//adapter->os_intf_ops->onebox_memcpy(&mgmt_frame->u.set_key.rx_mic_key, &data[24], 8);
//adapter->os_intf_ops->onebox_memcpy(&mgmt_frame->u.set_key.key, data, sizeof(mgmt_frame->u.set_key));
if(data) {
adapter->os_intf_ops->onebox_memcpy(&mgmt_frame->u.set_key.key, data, 4*32);
adapter->os_intf_ops->onebox_memcpy(&mgmt_frame->u.set_key.tx_mic_key, &data[16], 8);
adapter->os_intf_ops->onebox_memcpy(&mgmt_frame->u.set_key.rx_mic_key, &data[24], 8);
} else {
adapter->os_intf_ops->onebox_memset(&mgmt_frame->u.set_key, 0, sizeof(mgmt_frame->u.set_key));
}
//mgmt_frame->u.set_key.key = data;
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, sizeof(mgmt_frame->u.set_key) + FRAME_DESC_SZ);
status = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, (sizeof(mgmt_frame->u.set_key)+ FRAME_DESC_SZ));
if(status)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("Unable to load the keys frame\n")));
return ONEBOX_STATUS_FAILURE;
}
if(vap->iv_opmode == IEEE80211_M_STA) {
if((key_type == ONEBOX_PAIRWISE_KEY))
{
adapter->sta_mode.ptk_key = 1;
}
else if((key_type == ONEBOX_GROUP_KEY))
{
adapter->sta_mode.gtk_key = 1;
}
if((adapter->sta_mode.ptk_key) &&
(adapter->sta_mode.eapol4_cnfrm) &&
(adapter->sta_data_block)) {
printk("In %s Line %d eapol %d ptk %d sta_block %d ap_block %d\n", __func__, __LINE__,
adapter->sta_mode.eapol4_cnfrm, adapter->sta_mode.ptk_key, adapter->sta_data_block, adapter->block_ap_queues);
onebox_send_block_unblock(vap, STA_CONNECTED, 0);
}
if(adapter->sta_mode.ptk_key && adapter->sta_mode.gtk_key && adapter->sta_mode.eapol4_cnfrm) {
//onebox_send_sta_supported_features(vap, adapter);
printk("calling timeout initialziation In %s Line %d\n", __func__, __LINE__);
printk("Resting ptk ket variable in %s Line %d \n", __func__, __LINE__);
adapter->sta_mode.ptk_key = 0;
//initialize_sta_support_feature_timeout(vap, adapter);
update_pwr_save_status(vap, PS_ENABLE, CONNECTED_PATH);
}
}
return ONEBOX_STATUS_SUCCESS;
}
/* This function sends bootup parameters frame to TA.
* @param pointer to driver private structure
* @return 0 if success else -1.
*/
uint8 onebox_load_bootup_params(PONEBOX_ADAPTER adapter)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,
(TEXT("===> Sending Bootup parameters Packet <===\n")));
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, 256);
if (adapter->operating_chwidth == BW_40Mhz)
{
adapter->os_intf_ops->onebox_memcpy(&mgmt_frame->u.bootup_params,
&boot_params_40,
sizeof(BOOTUP_PARAMETERS));
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("===> Sending Bootup parameters Packet 40MHZ <=== %d\n"),UMAC_CLK_40BW));
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16(UMAC_CLK_40BW);
}
else
{
adapter->os_intf_ops->onebox_memcpy(&mgmt_frame->u.bootup_params,
&boot_params_20,
sizeof(BOOTUP_PARAMETERS));
if (boot_params_20.valid == VALID_20)
{
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16(UMAC_CLK_20BW);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("===> Sending Bootup parameters Packet 20MHZ <=== %d \n"),UMAC_CLK_20BW));
}
else
{
//FIXME: This should not occur need to remove
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16(UMAC_CLK_40MHZ);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("===>ERROR: Sending Bootup parameters Packet for 40MHZ In %s Line %d <=== %d \n"),__func__, __LINE__, UMAC_CLK_40MHZ));
}
}
/* Bit{0:11} indicates length of the Packet
* Bit{12:15} indicates host queue number
*/
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(sizeof(BOOTUP_PARAMETERS) | (ONEBOX_WIFI_MGMT_Q << 12));
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(BOOTUP_PARAMS_REQUEST);
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_DEBUG, (PUCHAR)mgmt_frame, (FRAME_DESC_SZ + sizeof(BOOTUP_PARAMETERS)));
status = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, (sizeof(BOOTUP_PARAMETERS)+ FRAME_DESC_SZ));
return status;
} /*end of onebox_load_bootup_params */
EXPORT_SYMBOL(onebox_load_bootup_params);
/**
* This function prepares reset MAC request frame and send it to LMAC.
*
* @param Pointer to Adapter structure.
* @return 0 if success else -1.
*/
ONEBOX_STATUS onebox_send_reset_mac(PONEBOX_ADAPTER adapter)
{
struct driver_assets *d_assets = onebox_get_driver_asset();
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status;
uint8 pkt_buffer[FRAME_DESC_SZ];
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,
(TEXT("===> Send Reset Mac frame <===\n")));
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, FRAME_DESC_SZ);
/* Bit{0:11} indicates length of the Packet
* Bit{12:16} indicates host queue number
*/
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(ONEBOX_WIFI_MGMT_Q << 12);
/* Fill frame type for reset mac request */
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(RESET_MAC_REQ);
if (adapter->Driver_Mode == RF_EVAL_MODE_ON)
{
mgmt_frame->desc_word[5] = ONEBOX_CPU_TO_LE16(1); //Value is (2 - 1)
}
else if (adapter->Driver_Mode == SNIFFER_MODE)
{
mgmt_frame->desc_word[3] = ONEBOX_CPU_TO_LE16(1);
}
if (adapter->calib_mode)
{
mgmt_frame->desc_word[5] |= ONEBOX_CPU_TO_LE16((1) << 8);
}
if (adapter->per_lpbk_mode)
{
mgmt_frame->desc_word[5] |= ONEBOX_CPU_TO_LE16((2) << 8);
}
#ifdef BYPASS_RX_DATA_PATH
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(0x0001);
#endif
mgmt_frame->desc_word[4] |= ONEBOX_CPU_TO_LE16(RETRY_COUNT << 8);
/*TA level aggregation of pkts to host */
if(adapter->Driver_Mode == SNIFFER_MODE)
{
mgmt_frame->desc_word[3] |= (1 << 8);
}
else
{
mgmt_frame->desc_word[3] |= (d_assets->ta_aggr << 8);
}
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_MGMT_SEND, (PUCHAR)mgmt_frame, (FRAME_DESC_SZ));
status = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, FRAME_DESC_SZ);
return status;
} /*end of onebox_send_reset_mac */
ONEBOX_STATUS set_channel(PONEBOX_ADAPTER adapter, uint16 chno)
{
/* Prepare the scan request using the chno information */
struct ieee80211com *ic = NULL;
onebox_mac_frame_t *mgmt_frame;
int32 status = 0;
uint16 frame[256];
uint16 ch_num;
ch_num = chno;
#ifndef PROGRAMMING_SCAN_TA
uint16 *rf_prog_vals;
uint16 vals_per_set;
uint8 count;
#endif
ic = &adapter->vap_com;
FUNCTION_ENTRY(ONEBOX_ZONE_INIT);
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("%s: Sending scan req frame\n"), __func__));
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)frame;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, 256);
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(SCAN_REQUEST);
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(chno);/*channel num is required */
//mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE32() & 0xFFFF; //FIXME SCAN_DURATION in usec
//mgmt_frame->desc_word[5] = ONEBOX_CPU_TO_LE32() & 0xFFFF0000; //FIXME SCAN_DURATION in usec
#ifdef RF_8111
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16 (PUT_BBP_RESET | BBP_REG_WRITE | (RSI_RF_TYPE << 4));
#else
/* RF type here is 8230 */
mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16 (PUT_BBP_RESET | BBP_REG_WRITE | (NONRSI_RF_TYPE << 4));
#endif
//mgmt_frame->desc_word[7] = ONEBOX_CPU_TO_LE16(radio_id << 8);
/* Do the channel no translation in case of 5Ghz band */
if (adapter->operating_band == BAND_5GHZ)
{
if(adapter->operating_chwidth == BW_20Mhz)
{
if ((chno >= 36) && (chno <= 64))
{
chno = ((chno - 32) / 4);
}
else if ((chno > 64) && (chno <= 140))
{
chno = ((chno - 100) / 4) + 9;
}
else if(chno >= 149)
{
chno = ((chno - 149) / 4) + 20;
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Invalid chno %d, operating_band = %d\n"), chno, adapter->operating_band));
return ONEBOX_STATUS_FAILURE;
} /* End if <condition> */
}
else /* For 40Mhz bandwidth */
{
if ((chno >= 36) && (chno <= 64))
{
chno = ((chno - 34) / 4);
}
else if ((chno > 64) && (chno <= 140))
{
chno = ((chno - 102) / 4) + 8;
}
else if(chno >= 149)
{
chno = ((chno - 151) / 4) + 18;
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Invalid chno %d, operating_band = %d\n"), chno, adapter->operating_band));
return ONEBOX_STATUS_FAILURE;
} /* End if <condition> */
}
}
else if(chno > 14)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Invalid chno %d, operating_band = %d\n"), chno, adapter->operating_band));
return ONEBOX_STATUS_FAILURE;
}
#ifndef PROGRAMMING_SCAN_TA
if(adapter->operating_band == BAND_5GHZ && ((adapter->RFType == ONEBOX_RF_8230) || (adapter->RFType == ONEBOX_RF_8111)))
{
if(adapter->operating_chwidth == BW_40Mhz)
{
printk("programming The 40Mhz center freq values in 5Ghz chno =%d\n", chno);
rf_prog_vals = &adapter->onebox_channel_vals_amode_40[chno].val[0];
vals_per_set = adapter->onebox_channel_vals_amode_40[chno].vals_row;
}
else
{
rf_prog_vals = &adapter->onebox_channel_vals_amode[chno].val[0];
vals_per_set = adapter->onebox_channel_vals_amode[chno].vals_row;
}
}
else
{
printk("In %s Line %d openrating chwidth = %d\n", __func__, __LINE__,adapter->operating_chwidth);
if(adapter->operating_chwidth == BW_40Mhz)
{
printk("programming The 40Mhz center freq values in 2Ghz chno =%d\n", chno);
rf_prog_vals = &adapter->onebox_channel_vals_bgmode_40[chno].val[0];
vals_per_set = adapter->onebox_channel_vals_bgmode_40[chno].vals_row;
}
else
{
rf_prog_vals = &adapter->onebox_channel_vals_bgmode[chno].val[0];
vals_per_set = adapter->onebox_channel_vals_bgmode[chno].vals_row;
}
}
mgmt_frame->u.rf_prog_req.rf_prog_vals[0] = ONEBOX_CPU_TO_LE16(vals_per_set + 1); //indicating no.of vals to fw
for (count = 1; count <= vals_per_set; count++)
{
mgmt_frame->u.rf_prog_req.rf_prog_vals[count] = ONEBOX_CPU_TO_LE16(rf_prog_vals[count - 1]);
}
if((adapter->RFType == ONEBOX_RF_8111) || (adapter->RFType == ONEBOX_RF_8230))
{
mgmt_frame->u.rf_prog_req.rf_prog_vals[count] = ONEBOX_CPU_TO_LE16(250); //padding delay
}
else
{
printk("%s: unknown rf type\n", __func__);
}
#else
printk("scan values in device ch_bandwidth = %d ch_num %d \n", adapter->operating_chwidth, ch_num);
//mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(ic->ic_curchan->ic_ieee);
if (adapter->Driver_Mode == RF_EVAL_MODE_ON)
{
adapter->ch_power = adapter->endpoint_params.power;
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(ch_num);
}
else if (adapter->Driver_Mode == SNIFFER_MODE)
{
adapter->ch_power = adapter->endpoint_params.power;
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(ch_num);
ic->ic_curchan->ic_ieee = ch_num;
if(ch_num == 14)
ic->ic_curchan->ic_freq = 2484;
else if (ch_num < 14)
ic->ic_curchan->ic_freq = 2407 + ch_num * 5;
else if (ch_num >= 36)
ic->ic_curchan->ic_freq = 5000 + ch_num * 5;
}
else
{
//adapter->ch_power = ic->ic_curchan->ic_maxregpower;
if(ic->ic_txpowlimit > ic->ic_curchan->ic_maxregpower)
{
adapter->ch_power = ic->ic_curchan->ic_maxregpower;
}else{
adapter->ch_power = ic->ic_txpowlimit;
}
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(ic->ic_curchan->ic_ieee);
}
mgmt_frame->desc_word[4] |= ONEBOX_CPU_TO_LE16(chno << 8);/*channel index */
mgmt_frame->desc_word[5] = ONEBOX_CPU_TO_LE16(0x1);/*scan values in TA */
mgmt_frame->desc_word[6] = ONEBOX_CPU_TO_LE16(adapter->ch_power);/*POWER VALUE*/
printk("IN %s Line %d TX_PWER is %d\n", __func__, __LINE__, adapter->ch_power);
if(adapter->operating_chwidth == BW_40Mhz)
{
printk("40Mhz is enabled\n");
mgmt_frame->desc_word[5] |= ONEBOX_CPU_TO_LE16(0x1 << 8);/*scan values in TA */
}
#endif
//ONEBOX_DEBUG(ONEBOX_ZONE_ERROR , (TEXT("Sending Scan Request frame \n")));
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame,sizeof(mgmt_frame->u.rf_prog_req) + FRAME_DESC_SZ );
#ifndef PROGRAMMING_SCAN_TA
status= onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, (sizeof(mgmt_frame->u.rf_prog_req) + FRAME_DESC_SZ));
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16((sizeof(mgmt_frame->u.rf_prog_req)) | (ONEBOX_WIFI_MGMT_Q << 12));
#else
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(ONEBOX_WIFI_MGMT_Q << 12);
status= onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, FRAME_DESC_SZ);
#endif
FUNCTION_EXIT(ONEBOX_ZONE_INIT);
return ONEBOX_STATUS_SUCCESS;
}
ONEBOX_STATUS onebox_umac_init_done (PONEBOX_ADAPTER adapter)
{
#ifdef USE_USB_INTF
//FIXME
//it is here as usb will disconnect and connect again. so adapter will be reset
adapter->mac_addr[0] = 0;
adapter->mac_addr[1] = 0x23;
adapter->mac_addr[2] = 0xa7;
adapter->mac_addr[3] = 0x04;
adapter->mac_addr[4] = 0x02;
adapter->mac_addr[5] = 0x48;
adapter->operating_band = BAND_2_4GHZ;
adapter->def_chwidth = BW_20Mhz;
adapter->operating_chwidth = BW_20Mhz;
#ifdef RF_8111
adapter->RFType = ONEBOX_RF_8111;
#else
adapter->RFType = ONEBOX_RF_8230;
#endif
if (onebox_load_config_vals(adapter) != 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR ,
(TEXT("%s: Initializing the Configuration vals Failed\n"), __func__));
return ONEBOX_STATUS_FAILURE;
}
#endif
adapter->core_ops->onebox_core_init(adapter);
return ONEBOX_STATUS_SUCCESS;
}
EXPORT_SYMBOL(onebox_umac_init_done); /* coex */
/**
* This function is to set channel, Band and Channel Bandwidth
* specified by user in PER mode.
*
* @param Pointer to adapter structure.
* @param Power Save Cmd.
* @return 0 if success else -1.
*/
ONEBOX_STATUS band_check (PONEBOX_ADAPTER adapter)
{
uint8 set_band = 0;
uint8 previous_chwidth = 0;
#ifdef PROGRAMMING_BBP_TA
uint8 previous_endpoint = 0;
previous_endpoint = adapter->endpoint;
#endif
if(adapter->endpoint_params.channel <= 14)
{
set_band = BAND_2_4GHZ;
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Band is 2GHz\n")));
}
else if((adapter->endpoint_params.channel >= 36) && (adapter->endpoint_params.channel <= 165))
{
set_band = BAND_5GHZ;
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Band is 5GHz\n")));
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Invalid channel issued by user\n")));
return ONEBOX_STATUS_FAILURE;
}
// per_ch_bw: 0 - 20MHz, 4 - Lower 40MHz, 2 - Upper 40MHz, 6 - Full 40MHz
previous_chwidth = adapter->operating_chwidth;
if (adapter->endpoint_params.per_ch_bw)
{
adapter->operating_chwidth = BW_40Mhz;
}
else
{
adapter->operating_chwidth = BW_20Mhz;
}
#ifndef PROGRAMMING_BBP_TA
if (adapter->operating_band != set_band)
{
adapter->operating_band = set_band;
adapter->rf_reset = 1;
printk(" RF_RESET AFTER BAND CHANGE = :\n");
adapter->devdep_ops->onebox_program_bb_rf(adapter);
if (adapter->operating_chwidth == BW_40Mhz)
{
adapter->chw_flag = 1;
adapter->devdep_ops->onebox_program_bb_rf(adapter);
}
}
else
{
if (adapter->operating_chwidth != previous_chwidth)
{
adapter->chw_flag = 1;
adapter->devdep_ops->onebox_program_bb_rf(adapter);
}
}
#else
if (adapter->operating_band != set_band)
{
adapter->rf_reset = 1;
adapter->operating_band = set_band;
}
if (!set_band)
{
if (adapter->operating_chwidth == BW_40Mhz)
{
adapter->endpoint = 1;
}
else
{
adapter->endpoint = 0;
}
}
else
{
if (adapter->operating_chwidth == BW_40Mhz)
{
adapter->endpoint = 3;
}
else
{
adapter->endpoint = 2;
}
}
if ((adapter->endpoint != previous_endpoint) || (adapter->rf_power_mode_change))
{
adapter->rf_power_mode_change = 0;
adapter->devdep_ops->onebox_program_bb_rf(adapter);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT(" ENDPOINT : %d \n"),adapter->endpoint));
}
#endif
if (adapter->operating_chwidth != previous_chwidth)
{
adapter->chw_flag = 1;
if(onebox_load_bootup_params(adapter) == ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: BOOTUP Parameters loaded successfully\n"),
__FUNCTION__));
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT ("%s: Failed to load bootup parameters\n"),
__FUNCTION__));
}
if(onebox_load_radio_caps(adapter))
{
return ONEBOX_STATUS_FAILURE;
}
}
else if ((adapter->operating_chwidth == BW_40Mhz) &&
(adapter->primary_channel != adapter->endpoint_params.per_ch_bw))
{
adapter->primary_channel = adapter->endpoint_params.per_ch_bw;
if(onebox_load_radio_caps(adapter))
{
return ONEBOX_STATUS_FAILURE;
}
}
return ONEBOX_STATUS_SUCCESS;
}
/**
* This function programs BB and RF values provided
* using MATLAB.
*
* @param Pointer to adapter structure.
* @param Power Save Cmd.
* @return 0 if success else -1.
*/
ONEBOX_STATUS set_bb_rf_values (PONEBOX_ADAPTER adapter, struct iwreq *wrq )
{
uint8 i = 0;
uint8 type = 0;
uint16 len = 0;
uint8 rf_len = 0;
ONEBOX_STATUS status = ONEBOX_STATUS_SUCCESS;
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("ONEBOX_read_bb_rf_values: Address = %x value = %d "),
adapter->bb_rf_params.Data[0],
adapter->bb_rf_params.value));
printk(" No of values = %d No of fields = %d:\n",adapter->bb_rf_params.no_of_values,adapter->bb_rf_params.no_of_fields);
adapter->bb_rf_params.Data[0] = adapter->bb_rf_params.no_of_values;
type = adapter->bb_rf_params.value;
for(i = 0; i <= adapter->bb_rf_params.no_of_values; i++)
printk(" bb_rf_params.Data[] = %x :\n",adapter->bb_rf_params.Data[i]);
if(type % 2 == 0)
{
adapter->bb_rf_rw = 1; //set_read
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT(" *** read \n")));
}
adapter->soft_reset = adapter->bb_rf_params.soft_reset;
adapter->os_intf_ops->onebox_reset_event(&(adapter->bb_rf_event));
if(type == BB_WRITE_REQ || type == BB_READ_REQ )
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("ONEBOX_read_buf_values : BB_REQ\n")));
if(onebox_mgmt_send_bb_prog_frame(adapter, adapter->bb_rf_params.Data, adapter->bb_rf_params.no_of_values) != ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
}
else if((type == RF_WRITE_REQ) || (type == RF_READ_REQ)
|| (type == ULP_READ_REQ) || (type == ULP_WRITE_REQ))
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("ONEBOX_read_buf_values : RF_REQ\n")));
if (type == RF_WRITE_REQ)
{
adapter->bb_rf_params.no_of_fields = 3;
if(onebox_mgmt_send_rf_prog_frame(adapter,&adapter->bb_rf_params.Data[2], adapter->bb_rf_params.no_of_values, adapter->bb_rf_params.no_of_fields, RSI_RF_TYPE ) != ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
}
else
{
if(onebox_mgmt_send_rf_prog_frame(adapter,&adapter->bb_rf_params.Data[1], adapter->bb_rf_params.no_of_values, adapter->bb_rf_params.no_of_fields, RSI_RF_TYPE ) != ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
}
}
else if(type == BUF_READ_REQ || type == BUF_WRITE_REQ )
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("ONEBOX_read_buf_values : BB_BUFFER\n")));
if(onebox_bb_buffer_request(adapter, adapter->bb_rf_params.Data, adapter->bb_rf_params.no_of_values) != ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
}
else if(type == RF_LOOPBACK_M2 || type == RF_LOOPBACK_M3 )
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("ONEBOX_read_buf_values : RF_LOOPBACK_REQ\n")));
// len = wrq->u.data.length;
if ( type == RF_LOOPBACK_M3 )
len = 256*2;
else
len = 2048 * 2;
adapter->rf_lpbk_len = 0;
adapter->os_intf_ops->onebox_memset(&adapter->rf_lpbk_data[0], 0, len );
if(onebox_rf_loopback(adapter, adapter->bb_rf_params.Data, adapter->bb_rf_params.no_of_values, type) != ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
}
else if(type == LMAC_REG_WRITE || type == LMAC_REG_READ )
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("ONEBOX_read_buf_values : LMAC_REG_READ/WRITE\n")));
if(onebox_mgmt_lmac_reg_ops_req(adapter, adapter->bb_rf_params.Data, type) != ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
}
else if(type == RF_RESET_REQ)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("ONEBOX_read_buf_values : RF_RESET_REQ\n")));
if(onebox_mgmt_send_rf_reset_req(adapter, adapter->bb_rf_params.Data) != ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
}
else if(type == EEPROM_RF_PROG_WRITE || type == EEPROM_RF_PROG_READ )
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("ONEBOX_read_buf_values : EEPROM_RF_PROG_READ\n")));
// if(eeprom_read(adapter, adapter->bb_rf_params.Data) != ONEBOX_STATUS_SUCCESS)
// if(eeprom_read(adapter, cw_mode_buf_write_array) != ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT(
"%s: Failed to perform operation type =%d\n"), __func__, type));
return -EFAULT;
}
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT(" Written success and trying to read \n")));
if(type % 2 == 0)
{
adapter->os_intf_ops->onebox_reset_event(&(adapter->bb_rf_event));
adapter->os_intf_ops->onebox_wait_event(&(adapter->bb_rf_event), 10000);
//adapter->os_intf_ops->onebox_acquire_spinlock(&adapter->lock_bb_rf, 0);
if (type == RF_LOOPBACK_M3 || type == RF_LOOPBACK_M2)
{
printk("Initial rf_lpbk_len : %d",adapter->rf_lpbk_len);
// while (rf_len < adapter->rf_lpbk_len)
{
printk("Initial else rf_lpbk_len : %d",adapter->rf_lpbk_len);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)&adapter->rf_lpbk_data[0], adapter->rf_lpbk_len );
if(copy_to_user((wrq->u.data.pointer), &adapter->rf_lpbk_data[0], adapter->rf_lpbk_len))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT(
"onebox_ioctl: Failed to perform operation\n")));
// adapter->os_intf_ops->onebox_release_spinlock(&adapter->lock_bb_rf, 0);
return -EFAULT;
}
printk("rf_lpbk_len : %d, rf_len: %d, len: %d",adapter->rf_lpbk_len,rf_len,len);
rf_len += adapter->rf_lpbk_len/2;
//adapter->os_intf_ops->onebox_wait_event(&(adapter->bb_rf_event), 10000);
}
adapter->os_intf_ops->onebox_memset(&adapter->rf_lpbk_data[0], 0, adapter->rf_lpbk_len );
adapter->rf_lpbk_len = 0;
}
else
{
wrq->u.data.length = sizeof(bb_rf_params_t);
if(copy_to_user(wrq->u.data.pointer, &adapter->bb_rf_read, sizeof(bb_rf_params_t)))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT(
"onebox_ioctl: Failed to perform operation\n")));
adapter->os_intf_ops->onebox_release_spinlock(&adapter->lock_bb_rf, 0);
return -EFAULT;
}
}
// adapter->os_intf_ops->onebox_release_spinlock(&adapter->lock_bb_rf, 0);
for(i=0;i<adapter->bb_rf_read.no_of_values;i++)
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("After reading bb_rf_read.Data[] = 0x%x \n"),adapter->bb_rf_read.Data[i]));
}
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT(
"%s: Success in performing operation\n"), __func__));
return status;
}
/**
* This function programs BBP registers for CW transmissions
*
* @param Pointer to adapter structure.
* @param Power Save Cmd.
* @return 0 if success else -1.
*/
ONEBOX_STATUS set_cw_mode (PONEBOX_ADAPTER adapter, uint8 mode)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status_l;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
int i = 0;
int j = 0;
uint16 *cw_mode_buf_write_array;
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,
(TEXT("===> Sending CW transmission Programming Packet <===\n")));
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, MAX_MGMT_PKT_SIZE);
/*prepare the frame descriptor */
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(ONEBOX_WIFI_MGMT_Q << 12);
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(CW_MODE_REQ);
adapter->soft_reset = 0;
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16((adapter->cw_sub_type << 8) | adapter->cw_type);
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, FRAME_DESC_SZ );
status_l = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, (FRAME_DESC_SZ));
if (status_l != ONEBOX_STATUS_SUCCESS)
{
return status_l;
}
else
{
printk("CW MODE write waiting \n");
adapter->os_intf_ops->onebox_reset_event(&(adapter->bb_rf_event));
adapter->os_intf_ops->onebox_wait_event(&(adapter->bb_rf_event), 10000);
#if 1
//mode = 2;
printk("CW_mode %d\n",mode);
switch (mode)
{
case 0:
case 1:
cw_mode_buf_write_array = cw_mode_buf_write_array_1;
break;
case 2:
cw_mode_buf_write_array = cw_mode_buf_write_array_2;
break;
case 3:
cw_mode_buf_write_array = cw_mode_buf_write_array_3;
break;
case 4:
cw_mode_buf_write_array = cw_mode_buf_write_array_4;
break;
case 5:
cw_mode_buf_write_array = cw_mode_buf_write_array_5;
break;
case 6:
cw_mode_buf_write_array = cw_mode_buf_write_array_6;
break;
case 7:
//cw_mode_buf_write_array = cw_mode_buf_write_array_7;
cw_mode_buf_write_array = cw_mode_buf_write_array_1;
break;
default:
{
cw_mode_buf_write_array = cw_mode_buf_write_array_1;
break;
}
} /* End switch */
i = 6;
while (i< (258*3))
{
memset (&adapter->bb_rf_params, 0, sizeof (bb_rf_params_t));
adapter->bb_rf_params.Data[1] = 0x315;
adapter->bb_rf_params.Data[2] = 0x316;
adapter->bb_rf_params.Data[3] = 0x317;
for (j =4; j< (35*3);j+=3 )
{
if (i >= 258*3 )
break;
adapter->bb_rf_params.Data[j] = cw_mode_buf_write_array[i];
adapter->bb_rf_params.Data[j+1] = cw_mode_buf_write_array[i+1];
adapter->bb_rf_params.Data[j+2] = cw_mode_buf_write_array[i+2];
printk("***** Data[%d] = 0x%x ,cw_mode_buf_write_array[%d] = 0x%x\n",j,adapter->bb_rf_params.Data[j],i,cw_mode_buf_write_array[i]);
i+=3;
}
adapter->bb_rf_params.value = 7; //BUFFER_WRITE
adapter->bb_rf_params.no_of_values = 34;
adapter->soft_reset = BBP_REMOVE_SOFT_RST_AFTER_PROG;
if(onebox_bb_buffer_request(adapter, adapter->bb_rf_params.Data, adapter->bb_rf_params.no_of_values) != ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
printk("CW MODE BUFFER write waiting \n");
adapter->os_intf_ops->onebox_reset_event(&(adapter->bb_rf_event));
adapter->os_intf_ops->onebox_wait_event(&(adapter->bb_rf_event), 10000);
}
memset (&adapter->bb_rf_params, 0, sizeof (bb_rf_params_t));
adapter->bb_rf_params.Data[1] = 0x318;
adapter->bb_rf_params.Data[2] = 0x80;
adapter->bb_rf_params.value = 1; //BB_WRITE
adapter->bb_rf_params.no_of_values = 2;
adapter->soft_reset = 0;
if(onebox_mgmt_send_bb_prog_frame(adapter, adapter->bb_rf_params.Data, adapter->bb_rf_params.no_of_values) != ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
#endif
}
return status_l;
}
ONEBOX_STATUS onebox_rf_loopback(PONEBOX_ADAPTER adapter,
uint16 *bb_prog_vals,
uint16 num_of_vals, uint8 type)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status_l;
uint16 frame_len;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE]; //1024* 4(4 bytes data) = 512*4*2(bytes)
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("===> Sending RF_LOOPBACK Programming Packet <===\n")));
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, MAX_MGMT_PKT_SIZE);
// FIXME this commented code may be used for LOOPBACK write for bebugging
#if 0
adapter->core_ops->onebox_dump(ONEBOX_ZONE_MGMT_DUMP, (PUCHAR)bb_prog_vals, num_of_vals);
if (adapter->bb_rf_rw)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(BBP_REG_READ);
adapter->bb_rf_rw = 0;
frame_len = 0;
}
else
{
/* Preparing BB Request Frame Body */
for (count=1; ((count < num_of_vals) && (ii< num_of_vals)); ii++, count+=2)
{
mgmt_frame->u.bb_prog_req[ii].reg_addr = ONEBOX_CPU_TO_LE16(bb_prog_vals[count]);
mgmt_frame->u.bb_prog_req[ii].bb_prog_vals = ONEBOX_CPU_TO_LE16(bb_prog_vals[count+1]);
}
if (num_of_vals % 2)
{
mgmt_frame->u.bb_prog_req[ii].reg_addr = ONEBOX_CPU_TO_LE16(bb_prog_vals[count]);
}
/* Preparing BB Request Frame Header */
frame_len = ((num_of_vals) * 2); //each 2 bytes
}
#endif
frame_len = 0;
/*prepare the frame descriptor */
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16((frame_len) | (ONEBOX_WIFI_MGMT_Q << 12));
if( type == RF_LOOPBACK_M2 )
{
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(RF_LOOPBACK_REQ);
}
else
{
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(RF_LPBK_M3);
}
#if 0
if (adapter->soft_reset & BBP_REMOVE_SOFT_RST_BEFORE_PROG)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(BBP_REMOVE_SOFT_RST_BEFORE_PROG);
}
if (adapter->soft_reset & BBP_REMOVE_SOFT_RST_AFTER_PROG)
{
mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16(BBP_REMOVE_SOFT_RST_AFTER_PROG);
}
adapter->soft_reset = 0;
//Flags are not handled FIXME:
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(num_of_vals/2);
//FIXME: What is the radio id to fill here
// mgmt_frame->desc_word[7] |= ONEBOX_CPU_TO_LE16 (RADIO_ID << 8 );
mgmt_frame->desc_word[5] = ONEBOX_CPU_TO_LE16(bb_prog_vals[0]);
#endif
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, (frame_len + FRAME_DESC_SZ ));
status_l = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, (frame_len + FRAME_DESC_SZ));
return status_l;
}
ONEBOX_STATUS eeprom_read(PONEBOX_ADAPTER adapter)
{
uint16 pkt_len = 0;
uint8 *pkt_buffer;
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status;
pkt_len = FRAME_DESC_SZ;
pkt_buffer = adapter->os_intf_ops->onebox_mem_zalloc(pkt_len, GFP_ATOMIC);
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("===> Frame to PERFORM EEPROM READ <===\n")));
/* FrameType*/
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(EEPROM_READ_TYPE);
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(ONEBOX_WIFI_MGMT_Q << 12 | (pkt_len - FRAME_DESC_SZ));
/* Number of bytes to read*/
printk(" offset = 0x%x, length = %d\n",adapter->eeprom.offset,adapter->eeprom.length);
mgmt_frame->desc_word[3] = ONEBOX_CPU_TO_LE16(adapter->eeprom.length << 4);
mgmt_frame->desc_word[2] |= ONEBOX_CPU_TO_LE16(3 << 8); //hsize = 3 as 32 bit transfer
/* Address to read*/
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(adapter->eeprom.offset);
mgmt_frame->desc_word[5] = ONEBOX_CPU_TO_LE16(adapter->eeprom.offset >> 16);
mgmt_frame->desc_word[6] = ONEBOX_CPU_TO_LE16(0); //delay = 0
status = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, pkt_len);
adapter->os_intf_ops->onebox_mem_free(pkt_buffer);
return status;
}
/**
* This function prepares reset RX filter request frame and send it to LMAC.
*
* @param Pointer to Adapter structure.
* @return 0 if success else -1.
*/
ONEBOX_STATUS onebox_send_rx_filter_frame(PONEBOX_ADAPTER adapter, uint16_t rx_filter_word)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status;
uint8 pkt_buffer[FRAME_DESC_SZ];
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,
(TEXT("===> Send Rx Filter frame <===\n")));
printk("Rx filter word is %x\n", rx_filter_word);
/* Allocating Memory For Mgmt Pkt From Mgmt Free Pool */
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, FRAME_DESC_SZ);
/* Bit{0:11} indicates length of the Packet
* Bit{12:16} indicates host queue number
*/
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(ONEBOX_WIFI_MGMT_Q << 12);
/* Fill frame type set_rx_filter */
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(SET_RX_FILTER);
/* Fill data in form of flags*/
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(rx_filter_word);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_MGMT_SEND, (PUCHAR)mgmt_frame, (FRAME_DESC_SZ));
status = onebox_send_internal_mgmt_frame(adapter, (uint16 *)mgmt_frame, FRAME_DESC_SZ);
return status;
} /*end of onebox_send_rx_filter_frame */
EXPORT_SYMBOL(onebox_send_rx_filter_frame);
<file_sep>/wlan/wlan_hal/Makefile
#/**
# * @file Makefile
# * @author
# * @version 1.0
# *
# * @section LICENSE
# *
# * This software embodies materials and concepts that are confidential to Redpine
# * Signals and is made available solely pursuant to the terms of a written license
# * agreement with Redpine Signals
# *
# * @section DESCRIPTION
# *
# * This is the HAL Makefile used for generating the GPL and NON-GPL modules.
# */
DRV_DIR=$(ROOT_DIR)/wlan/wlan_hal
RELEASE_DIR=$(ROOT_DIR)/release
NET80211_DIR=$(ROOT_DIR)/wlan/net80211/linux
DEVDEP_DIR=osi_wlan/devdep/rsi_9113
CORE_DIR=osi_wlan/core
OSD_DIR=osd_wlan/linux
include $(ROOT_DIR)/.config
include $(ROOT_DIR)/config/make.config
EXTRA_CFLAGS += -DLINUX -Wimplicit -Wstrict-prototypes
EXTRA_CFLAGS += -Dnet80211_s
EXTRA_CFLAGS += -DFLASH_BURNING
EXTRA_CFLAGS += -DPWR_SAVE_SUPPORT
EXTRA_CFLAGS += -DBGSCAN_SUPPORT
#EXTRA_CFLAGS += -DTRILITHIC_RELEASE
#EXTRA_CFLAGS += -DCHIP_9116
#EXTRA_CFLAGS += -DONEBOX_DEBUG_ENABLE
#EXTRA_CFLAGS += -DAMPDU_AGGR_SUPPORT
#EXTRA_CFLAGS += -DCHIP_ENABLED
#EXTRA_CFLAGS += -DAUTO_RATE_SUPPORT
#EXTRA_CFLAGS += -DEEPROM_READ_EN
EXTRA_CFLAGS += -DRSI_SDIO_MULTI_BLOCK_SUPPORT
EXTRA_CFLAGS += -DSECURITY_SUPPORT
#EXTRA_CFLAGS += -DENABLE_P2P_SUPPORT
#EXTRA_CFLAGS += -DENABLE_PER_MODE
EXTRA_CFLAGS += -DDYNAMIC_VARIABLES
EXTRA_CFLAGS += -DRF_8111
EXTRA_CFLAGS += -DEEPROM_NOT_PRESENT
#EXTRA_CFLAGS += -DDISABLE_TALOAD
EXTRA_CFLAGS += -I$(DRV_DIR)/include/linux
EXTRA_CFLAGS += -I$(ROOT_DIR)/common_hal/include/common
#EXTRA_CFLAGS += -DFPGA_VALIDATION
EXTRA_CFLAGS += -I$(NET80211_DIR)/osi_net80211/net80211
EXTRA_CFLAGS += -I$(NET80211_DIR)/osi_net80211
EXTRA_CFLAGS += -I$(NET80211_DIR)/osd_linux/include
#EXTRA_CFLAGS += -DUSE_SUBQUEUES
EXTRA_CFLAGS += -DACM_NO_TSPEC_CNFM
EXTRA_CFLAGS += -g
ifeq ($(USE_DEVICE),"SDIO")
EXTRA_CFLAGS += -DUSE_SDIO_INTF
else
EXTRA_CFLAGS += -DUSE_USB_INTF
endif
DEVDEP_OBJ := $(DEVDEP_DIR)/onebox_wlan_osi_init.o \
$(DEVDEP_DIR)/onebox_devdep_wlan_callbacks.o \
$(DEVDEP_DIR)/onebox_dev_ops.o \
$(DEVDEP_DIR)/onebox_ps.o \
$(DEVDEP_DIR)/onebox_devdep_mgmt.o \
$(DEVDEP_DIR)/onebox_pktpro.o \
$(DEVDEP_DIR)/onebox_debug.o \
$(DEVDEP_DIR)/onebox_reorder.o
CORE_OBJ := $(CORE_DIR)/onebox_core_wlan.o \
$(CORE_DIR)/onebox_wlan_per.o \
$(CORE_DIR)/onebox_core_wlan_callbacks.o \
$(CORE_DIR)/onebox_core_hal_intf.o \
$(CORE_DIR)/onebox_core_os_intf.o \
$(CORE_DIR)/onebox_core_autorate.o \
$(CORE_DIR)/onebox_core_vap.o \
$(CORE_DIR)/onebox_core_wmm.o \
$(CORE_DIR)/onebox_net80211_callbacks.o
OSD_OBJ := $(OSD_DIR)/onebox_wlan_ioctl.o \
$(OSD_DIR)/onebox_wlan_osd_init.o \
$(OSD_DIR)/onebox_wlan_osd_ops.o \
$(OSD_DIR)/onebox_wlan_osd_callbacks.o \
$(OSD_DIR)/onebox_wlan_proc.o \
NONGPL_OBJS := $(DEVDEP_OBJ) $(CORE_OBJ)
GPL_OBJS := $(OSD_OBJ)
obj-m := onebox_wlan_gpl.o
onebox_wlan_gpl-objs := $(GPL_OBJS)
obj-m += onebox_wlan_nongpl.o
onebox_wlan_nongpl-objs := $(NONGPL_OBJS)
all:
@echo "Compiling non gpl module"
@cp $(ROOT_DIR)/wlan/net80211/linux/Module.symvers .
make -C$(KERNELDIR) SUBDIRS=$(DRV_DIR) modules
@echo "Copying wlan module..."
@cp onebox_wlan_nongpl.ko onebox_wlan_gpl.ko $(RELEASE_DIR)/.
clean:
@echo "- Cleaning All Object and Intermediate Files"
@find . -name '*.ko' | xargs rm -rf
@find . -name '.*.ko.cmd' | xargs rm -rf
@find . -name '.*.ko.unsigned.cmd' | xargs rm -rf
@find . -name '*.ko.*' | xargs rm -rf
@find . -name '*.order' | xargs rm -rf
@find . -name '*.symvers' | xargs rm -rf
@find . -name '*.markers' | xargs rm -rf
@find . -name '*.o' | xargs rm -f
@find . -name '.*.ko.cmd' | xargs rm -rf
@find . -name '.*.o.cmd' | xargs rm -rf
@find $(OSD_DIR) -name '*.o' | xargs rm -f
@find $(HOST_INTF_DIR) -name '.*.o.cmd' | xargs rm -rf
@find . -name '*.mod.c' | xargs rm -rf
@echo "- Done"
<file_sep>/zigbee/include/linux/onebox_zigb_ops.h
/**
* @file onebox_hal_ops.h
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contians the function prototypes of the callbacks used across
* differnet layers in the driver
*
*/
#include "onebox_common.h"
#ifdef USE_USB_INTF
#include <linux/usb.h>
#endif
struct onebox_osi_zigb_ops {
int32 (*onebox_core_init)(PONEBOX_ADAPTER adapter);
int32 (*onebox_core_deinit)(PONEBOX_ADAPTER adapter);
void (*onebox_dump)(int32 dbg_zone_l, PUCHAR msg_to_print_p,int32 len);
ONEBOX_STATUS (*onebox_send_pkt)(PONEBOX_ADAPTER adapter,
netbuf_ctrl_block_t *netbuf_cb);
};
struct onebox_zigb_osd_operations {
int32 (*onebox_zigb_register_genl)(PONEBOX_ADAPTER adapter);
int32 (*onebox_zigb_deregister_genl)(PONEBOX_ADAPTER adapter);
int32 (*onebox_zigb_app_send)(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb);
};
/* EOF */
<file_sep>/wlan/wlan_hal/osd_wlan/linux/onebox_wlan_ioctl.c
/**
* @file onebox_hal_ioctl.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contians the code for handling ioctls.
*/
#include "onebox_common.h"
/**
* This function will return index of a given ioctl command.
* And the output parameter private indicates whether the given
* ioctl is a standard ioctl command or a private ioctl.
* 0: Standard
* 1: Private ioctl
* -1: Illiegal ioctl
*
* @param value of the ioctl command, input to this function
* @param Indicates whether the ioctl is private or standart, output pointer
* @return returns index of the ioctl
*/
static uint32 last_total_beacon_count;
static int get_ioctl_index(int cmd, int *private)
{
int index = 0;
*private = 0;
if ( (cmd >= SIOCIWFIRSTPRIV) && (cmd <= SIOCIWLASTPRIV))
{
/* Private IOCTL */
index = cmd - SIOCIWFIRSTPRIV;
*private = 1;
}
else if ((cmd >= 0x8B00) && (cmd <= 0x8B2D))
{
/* Standard IOCTL */
index = cmd - 0x8B00;
*private = 0;
}
else
{
*private = -1;
}
return index;
}
/**
* This function handles the ioctl for deleting a VAP.
* @param Pointer to the ieee80211com structure
* @param Pointer to the ifreq structure
* @param Pointer to the netdevice structure
* @return Success or failure
*/
int
ieee80211_ioctl_delete_vap(struct ieee80211com *ic, struct ifreq *ifr, struct net_device *mdev)
{
struct ieee80211vap *vap = NULL;
struct ieee80211_clone_params cp;
char name[IFNAMSIZ];
uint8_t wait_for_lock = 0;
uint8_t vap_del_flag = 0;
//PONEBOX_ADAPTER adapter = (PONEBOX_ADAPTER)netdev_priv(mdev);
if (!capable(CAP_NET_ADMIN))
{
return -EPERM;
}
if (copy_from_user(&cp, ifr->ifr_data, sizeof(cp)))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Copy from user failed\n")));
return -EFAULT;
}
strncpy(name, cp.icp_parent, sizeof(name));
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
printk("User given vap name =%s and list of vap names=%s\n", name, vap->iv_ifp->name);
if (!strcmp(vap->iv_ifp->name, name))
{
//adapter->net80211_ops->onebox_ifdetach(ic);
printk("Deleting vap\n");
ic->ic_vap_delete(vap, wait_for_lock);
vap_del_flag =1;
break;
}
}
if(vap_del_flag)
{
return 0;
}
else
{
printk("Invalid VAP name given for deletion\n");
return -1;
}
}
/* timeout handler for channel utilization*/
void ch_util_timeout_handler(PONEBOX_ADAPTER adapter)
{
struct ieee80211com *ic = &adapter->vap_com;
/* stop time // calculate total time taken // start time again*/
ic->ch_util->stop_time = jiffies;
adapter->ch_util_tot_time = ic->ch_util->tot_time = (ic->ch_util->stop_time - ic->ch_util->start_time);
ic->ch_util->start_time = jiffies;
/*modify timer */
adapter->os_intf_ops->onebox_mod_timer(&adapter->channel_util_timeout, msecs_to_jiffies(1000));
}
/**
* This function creates a virtual ap.This is public as it must be
* implemented outside our control (e.g. in the driver).
* @param Pointer to the ieee80211com structure
* @param Pointer to the ifreq structure
* @param Pointer to the netdevice structure
* @return Success or failure
*/
int ieee80211_ioctl_create_vap(struct ieee80211com *ic, struct ifreq *ifr,
struct net_device *mdev)
{
struct ieee80211_clone_params cp;
struct ieee80211vap *vap;
char name[IFNAMSIZ];
PONEBOX_ADAPTER adapter = (PONEBOX_ADAPTER)netdev_priv(mdev);
//uint8 vap_id;
if (!capable(CAP_NET_ADMIN))
{
return -EPERM;
}
if (copy_from_user(&cp, ifr->ifr_data, sizeof(cp)))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Copy from user failed\n")));
return -EFAULT;
}
strncpy(name, cp.icp_parent, sizeof(name));
#if 0
vap_id = adapter->os_intf_ops->onebox_extract_vap_id(name);
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap && (vap->hal_priv_vap->vap_id == vap_id)) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Virtual Interface with similar name is already created\n")));
return -EFAULT;
}
}
#endif
printk("Name for vap creation is: %s rtnl %d\n", name, rtnl_is_locked());
/* FIXME */ //Check 3,6,7 param whether it should be 0 or not
vap = adapter->core_ops->onebox_create_vap(ic, name, 0, cp.icp_opmode, cp.icp_flags, NULL, adapter->mac_addr);
if (vap == NULL)
{
printk("VAP = NULL\n");
return -EIO;
}
/* return final device name */
strncpy(ifr->ifr_name, vap->iv_ifp->name, IFNAMSIZ);
return 0;
}
bool check_valid_bgchannel(uint16 *data_ptr, uint8_t supported_band)
{
uint8_t ii, jj;
uint8_t num_chan = *((uint8 *)(data_ptr) + 6) ;
uint16_t chan_5g[] = {36, 40, 44, 48, 149, 153, 157, 161, 165};
uint16_t chan_check[num_chan];
memcpy(chan_check, (uint16 *)(data_ptr + 6), 2*num_chan);
if (!supported_band) {
for (ii = 0; ii < num_chan; ii++) {
for (jj = 0; jj < num_chan; jj++) {
if (chan_check[ii] == chan_5g[jj]) {
printk("ERROR: Trying to program 5GHz channel on a card supporting only 2.4GHz\n");
return false;
}
}
}
}
return true;
}
static void send_sleep_req_in_per_mode(PONEBOX_ADAPTER adapter, uint8 *data)
{
onebox_mac_frame_t *mgmt_frame;
ONEBOX_STATUS status = 0;
uint8 pkt_buffer[MAX_MGMT_PKT_SIZE];
struct pwr_save_params ps_params_ioctl;//Parameters to store IOCTL parameters from USER
#ifndef USE_USB_INTF
uint8 request =1;
#endif
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
memcpy(&ps_params_ioctl, data, sizeof(struct pwr_save_params));
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, MAX_MGMT_PKT_SIZE);
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(sizeof(mgmt_frame->u.ps_req_params) | (ONEBOX_WIFI_MGMT_Q << 12));
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(WAKEUP_SLEEP_REQUEST);
mgmt_frame->u.ps_req_params.ps_req.sleep_type = ps_params_ioctl.sleep_type; //LP OR ULP
mgmt_frame->u.ps_req_params.listen_interval = ps_params_ioctl.listen_interval;
mgmt_frame->u.ps_req_params.ps_req.sleep_duration = ps_params_ioctl.deep_sleep_wakeup_period;
mgmt_frame->u.ps_req_params.ps_req.ps_en = ps_params_ioctl.ps_en;
mgmt_frame->u.ps_req_params.ps_req.connected_sleep = DEEP_SLEEP;
if(!ps_params_ioctl.ps_en) {
mgmt_frame->desc_word[0] |= 1 << 15; //IMMEDIATE WAKE UP
}
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (" <==== Sending Power save request =====> In %s Line %d \n", __func__, __LINE__));
status = adapter->devdep_ops->onebox_send_internal_mgmt_frame(adapter,
(uint16 *)mgmt_frame,
FRAME_DESC_SZ + sizeof(mgmt_frame->u.ps_req_params));
#ifndef USE_USB_INTF
msleep(2);
printk("Writing disable to wakeup register\n");
status = adapter->osd_host_intf_ops->onebox_write_register(adapter,
0,
SDIO_WAKEUP_REG,
&request);
#endif
return ;
}
/**
* Calls the corresponding (Private) IOCTL functions
*
* @param pointer to the net_device
* @param pointer to the ifreq
* @param value of the ioctl command, input to this function
* @return returns 0 on success otherwise returns the corresponding
* error code for failure
*/
int onebox_ioctl(struct net_device *dev,struct ifreq *ifr, int cmd)
{
PONEBOX_ADAPTER adapter = (PONEBOX_ADAPTER)netdev_priv(dev);
struct ieee80211com *ic = &adapter->vap_com;
struct iwreq *wrq = (struct iwreq *)ifr;
int index, priv, ret_val=0;
struct ieee80211_node *ni = NULL;
struct ieee80211vap *vap = NULL;
uint8_t macaddr[IEEE80211_ADDR_LEN];
int error;
struct minstrel_node *ar_stats = NULL;
unsigned int value = 0;
unsigned int channel = 1;
unsigned int set_band = BAND_2_4GHZ;
unsigned int status;
onebox_mac_frame_t *mgmt_frame;
struct test_mode test;
ONEBOX_DEBUG(ONEBOX_ZONE_OID, ("In onebox_ioctl function\n"));
/* Check device is present or not */
if (!netif_device_present(dev))
{
printk("Device not present\n");
return -ENODEV;
}
/* Get the IOCTL index */
index = get_ioctl_index(cmd, &priv);
/*vap creation command*/
switch(cmd)
{
case RSI_WATCH_IOCTL:
{
wrq->u.data.length = 4;
if (adapter->buffer_full)
{
adapter->watch_bufferfull_count++;
if (adapter->watch_bufferfull_count > 10) /* FIXME : not 10, should dependent on time */
{
/* Incase of continous buffer full, give the last beacon counter */
ret_val = copy_to_user(wrq->u.data.pointer, &last_total_beacon_count, 4);
return ret_val;
}
}
last_total_beacon_count = adapter->total_beacon_count;
ret_val = copy_to_user(wrq->u.data.pointer, &last_total_beacon_count, 4);
return ret_val;
}
break;
case ONEBOX_VAP_CREATE:
{
if ((adapter->Driver_Mode != WIFI_MODE_ON) && (adapter->Driver_Mode != SNIFFER_MODE))
{
printk("Driver Mode is not in WIFI_MODE vap creation is not Allowed\n");
return ONEBOX_STATUS_FAILURE;
}
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (" VAP Creation \n"));
ret_val = ieee80211_ioctl_create_vap(ic, ifr, dev);
if(ret_val == 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("Created VAP with dev name:%s\n"),ifr->ifr_name));
}
return ret_val;
}
break;
case ONEBOX_VAP_DELETE:
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (" VAP delete \n"));
ret_val = ieee80211_ioctl_delete_vap(ic, ifr, dev);
if(ret_val == 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("Deleted VAP with dev name:%s\n"),ifr->ifr_name));
}
return ret_val;
}
#define IS_RUNNING(ifp) \
((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
case SIOCSIFFLAGS:
{
printk("In SIOCSIFFLAGS case dev->flags =%x\n", dev->if_flags);
/* Not doing anything here */
if (IS_RUNNING(dev))
{
/* Nothing to be done here */
}
else if (dev->if_flags & IFF_UP)
{
dev->if_drv_flags |= IFF_DRV_RUNNING;
ieee80211_start_all(ic);
}
else
{
dev->if_drv_flags &= ~IFF_DRV_RUNNING;
}
return ret_val;
}
break;
case SIOCGAUTOSTATS:
{
error = copy_from_user(macaddr, wrq->u.data.pointer, IEEE80211_ADDR_LEN);
if (error != 0)
{
return error;
}
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT(" mac addr=%02x:%02x:%02x:%02x:%02x:%02x\n"), macaddr[0],
macaddr[1], macaddr[2], macaddr[3], macaddr[4], macaddr[5]));
ni = adapter->net80211_ops->onebox_find_node(&vap->iv_ic->ic_sta, macaddr);
if (ni == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_OID, (TEXT("Ni is null vap node not found\n")));
return ENOENT;
}
}
ONEBOX_DEBUG(ONEBOX_ZONE_OID, (TEXT(" Found VAP node\n")));
if((&ni->hal_priv_node) && ni->hal_priv_node.ni_mn)
{
ONEBOX_DEBUG(ONEBOX_ZONE_OID, (TEXT("Autorate Minstrel node pointer = %p\n"), ni->hal_priv_node.ni_mn));
error = copy_to_user( wrq->u.data.pointer, ni->hal_priv_node.ni_mn, sizeof(struct minstrel_node));
ar_stats = ni->hal_priv_node.ni_mn;
error = copy_to_user( wrq->u.data.pointer + sizeof(struct minstrel_node),
ni->hal_priv_node.ni_mn->r,
sizeof(struct minstrel_rate) * (ar_stats->n_rates));
}
}
break;
case ONEBOX_HOST_IOCTL:
{
if(adapter->Driver_Mode == WIFI_MODE_ON)
{
value = wrq->u.data.length;
switch((unsigned char)wrq->u.data.flags)
{
case PER_RECEIVE_STOP:
adapter->recv_stop = 1;
adapter->rx_running = 0;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,("PER_RECEIVE_STOP\n"));
case PER_RECEIVE:
adapter->os_intf_ops->onebox_reset_event(&(adapter->stats_event));
if (!adapter->rx_running)
{
if(!(adapter->core_ops->onebox_stats_frame(adapter)))
{
adapter->rx_running = 1;
if (adapter->recv_stop)
{
adapter->recv_stop = 0;
adapter->rx_running = 0;
return ONEBOX_STATUS_SUCCESS;
}
adapter->os_intf_ops->onebox_wait_event(&(adapter->stats_event), EVENT_WAIT_FOREVER);
ret_val = copy_to_user(wrq->u.data.pointer, &adapter->sta_info, sizeof(per_stats));
return ret_val;
}
}
else
{
adapter->os_intf_ops->onebox_wait_event(&(adapter->stats_event), EVENT_WAIT_FOREVER);
ret_val = copy_to_user(wrq->u.data.pointer, &adapter->sta_info, sizeof(per_stats));
return ret_val;
}
break;
case SET_BEACON_INVL:
if (IEEE80211_BINTVAL_MIN_AP <= value &&
value <= IEEE80211_BINTVAL_MAX)
{
ic->ic_bintval = ((value + 3) & ~(0x3));
}
else
{
ret_val = EINVAL;
}
adapter->beacon_interval = ONEBOX_CPU_TO_LE16(((value + 3) & ~(0x3)));
break;
case SET_ENDPOINT:
value = ((unsigned short)wrq->u.data.flags >> 8); //endpoint value
printk("ENDPOINT type is : %d \n",value);
if (!adapter->band_supported) {
if (value == 2 || value == 3) {
printk("ERROR: 5GHz endpoint not supported\n");
return -EINVAL;
}
}
adapter->endpoint = value;
adapter->devdep_ops->onebox_program_bb_rf(adapter);
break;
case ANT_SEL:
value = ((unsigned short)wrq->u.data.flags >> 8); //endpoint value
printk("ANT_SEL value is : %d \n",value);
adapter->devdep_ops->onebox_program_ant_sel(adapter, value);
break;
case SET_BGSCAN_PARAMS:
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("<<< BGSCAN >>>\n")));
// onebox_send_bgscan_params(adapter, wrq->u.data.pointer , 0);
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT(" mac addr=%02x:%02x:%02x:%02x:%02x:%02x\n"), macaddr[0],
macaddr[1], macaddr[2], macaddr[3], macaddr[4], macaddr[5]));
if(vap->iv_opmode == IEEE80211_M_STA)
{
if (!check_valid_bgchannel(wrq->u.data.pointer, adapter->band_supported)) {
printk("Invalid channel in bg param set; 5GHz not supported by card\n");
return -EINVAL;
}
memset(&vap->hal_priv_vap->bgscan_params_ioctl, 0, sizeof(mgmt_frame->u.bgscan_params));
memcpy(&vap->hal_priv_vap->bgscan_params_ioctl, wrq->u.data.pointer, sizeof(mgmt_frame->u.bgscan_params));
vap->hal_priv_vap->bgscan_params_ioctl.bg_ioctl = 1;
if(vap->iv_state == IEEE80211_S_RUN && (!adapter->sta_mode.delay_sta_support_decision_flag))
{
printk("Bgscan: In %s and %d \n", __func__, __LINE__);
if(onebox_send_bgscan_params(vap, wrq->u.data.pointer , 0))
{
return ONEBOX_STATUS_FAILURE;
}
}
else
{
printk("Bgscan: In %s and %d \n", __func__, __LINE__);
return 0;
}
ni = adapter->net80211_ops->onebox_find_node(&vap->iv_ic->ic_sta, vap->iv_myaddr);
if (ni == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_OID, (TEXT("Ni is null vap node not found\n")));
return ENOENT;
}
send_bgscan_probe_req(adapter, ni, 0);
return 0;
}
}
printk("Issue IOCTL after vap creation in %s Line %d\n", __func__, __LINE__);
return -EINVAL;
break;
case DO_BGSCAN:
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("<<< DO BGSCAN IOCTL Called >>>\n")));
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap && (vap->iv_opmode == IEEE80211_M_STA))
{
ni = adapter->net80211_ops->onebox_find_node(&vap->iv_ic->ic_sta, vap->iv_myaddr);
if (ni == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_OID, (TEXT("Ni is null vap node not found\n")));
return ENOENT;
}
if(vap && (vap->hal_priv_vap->bgscan_params_ioctl.bg_ioctl))
{
memcpy(&vap->hal_priv_vap->bgscan_params_ioctl.bg_cmd_flags, wrq->u.data.pointer, sizeof(uint16_t));
if((vap->iv_state == IEEE80211_S_RUN))
{
send_bgscan_probe_req(adapter, ni, vap->hal_priv_vap->bgscan_params_ioctl.bg_cmd_flags);
}
return 0;
}
else
{
printk("Issue this IOCTL only after issuing bgscan_params ioctl\n");
return -EINVAL;
}
}
}
printk("Issue IOCTL after vap creation in %s Line %d\n", __func__, __LINE__);
return -EINVAL;
break;
case BGSCAN_SSID:
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("<<< BGSCAN SSID >>>\n")));
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT(" mac addr=%02x:%02x:%02x:%02x:%02x:%02x\n"), macaddr[0],
macaddr[1], macaddr[2], macaddr[3], macaddr[4], macaddr[5]));
if(vap->iv_opmode == IEEE80211_M_STA)
{
memcpy(&vap->hal_priv_vap->bg_ssid, wrq->u.data.pointer, sizeof(vap->hal_priv_vap->bg_ssid));
printk("SSID len is %d ssid is %s\n", vap->hal_priv_vap->bg_ssid.ssid_len, vap->hal_priv_vap->bg_ssid.ssid);
}
}
break;
#ifdef PWR_SAVE_SUPPORT
case PS_REQUEST:
{
printk("Name for vap creation is rtnl %d\n", rtnl_is_locked());
printf("In %s Line %d issued PS_REQ ioctl\n", __func__, __LINE__);
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap->iv_opmode == IEEE80211_M_STA){
break;
}
}
if(vap)
{
memcpy(&vap->hal_priv_vap->ps_params_ioctl, wrq->u.data.pointer, sizeof(vap->hal_priv_vap->ps_params));
printk("monitor interval %d\n", vap->hal_priv_vap->ps_params_ioctl.monitor_interval);
driver_ps.update_ta = 1;
update_pwr_save_status(vap, PS_ENABLE, IOCTL_PATH);
#if 0
if(ps_params_def.ps_en)
{
driver_ps.en = 1;
}
else
{
driver_ps.en = 0;
}
#endif
#if 0
#ifndef USE_USB_INTF
if((vap->iv_state == IEEE80211_S_RUN) || (vap->iv_state == IEEE80211_S_INIT))
#else
if((vap->iv_state == IEEE80211_S_RUN))
#endif
{
// adapter->devdep_ops->onebox_send_ps_params(adapter, &vap->hal_priv_vap->ps_params);
//pwr_sve_event_handler(vap);
}
#endif
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("ERROR: Give IOCTL after station vap Creation\n")));
return -EINVAL;
}
break;
}
case UAPSD_REQ:
{
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap->iv_opmode == IEEE80211_M_STA){
break;
}
}
if(vap && (vap->iv_state == IEEE80211_S_RUN))
{
memcpy(&vap->hal_priv_vap->uapsd_params_ioctl, wrq->u.data.pointer, sizeof(vap->hal_priv_vap->uapsd_params_ioctl));
}
else if(vap)
{
memcpy(&vap->hal_priv_vap->uapsd_params_ioctl, wrq->u.data.pointer, sizeof(vap->hal_priv_vap->uapsd_params_ioctl));
printk("acs %02x wakeup %02x \n", vap->hal_priv_vap->uapsd_params_ioctl.uapsd_acs, vap->hal_priv_vap->uapsd_params_ioctl.uapsd_wakeup_period);
memcpy(&vap->hal_priv_vap->uapsd_params_updated, &vap->hal_priv_vap->uapsd_params_ioctl, sizeof(vap->hal_priv_vap->uapsd_params_ioctl));
}
else
{
printk("Give IOCTL after vap Creation\n");
return -EINVAL;
}
break;
}
#endif
case RESET_ADAPTER:
{
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap->iv_opmode == IEEE80211_M_STA){
break;
}
}
if(vap)
{
#if 0
printk("Copying ioctl values to updated \n");
if((&vap->hal_priv_vap->uapsd_params_ioctl) && (&vap->hal_priv_vap->uapsd_params_updated))
{
memcpy(&vap->hal_priv_vap->uapsd_params_updated, &vap->hal_priv_vap->uapsd_params_ioctl, sizeof(vap->hal_priv_vap->uapsd_params_ioctl));
}
#endif
printk("Resetting the Adapter settings \n");
ni = vap->iv_bss;
if(ni && (vap->iv_state == IEEE80211_S_RUN))
{
printk("Issuing sta leave cmd\n");
adapter->net80211_ops->onebox_ieee80211_sta_leave(ni);
}
}
break;
}
case RX_FILTER:
{
memcpy(&adapter->rx_filter_word,wrq->u.data.pointer,sizeof(adapter->rx_filter_word));
printk("Setting RX_FILTER %04x\n", adapter->rx_filter_word);
status = onebox_send_rx_filter_frame(adapter, adapter->rx_filter_word);
if(status < 0)
{
printk("Sending of RX filter frame failed\n");
}
break;
}
case RF_PWR_MODE:
{
memcpy(&adapter->rf_pwr_mode, wrq->u.data.pointer, sizeof(adapter->rf_pwr_mode));
printk("Setting RF PWR MODE %04x\n", adapter->rf_pwr_mode);
printk("Setting RF PWR MODE %d\n", adapter->rf_pwr_mode);
break;
}
case RESET_PER_Q_STATS:
{
int q_num;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,("Resetting WMM stats\n"));
if (copy_from_user(&q_num, ifr->ifr_data, sizeof(q_num)))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Copy from user failed\n")));
return -EFAULT;
}
if(q_num < MAX_HW_QUEUES) {
adapter->total_tx_data_dropped[q_num] = 0;
adapter->total_tx_data_sent[q_num] = 0;
}else if(q_num == 15) {
memset(adapter->total_tx_data_dropped, 0, sizeof(adapter->total_tx_data_dropped));
memset(adapter->total_tx_data_sent, 0, sizeof(adapter->total_tx_data_sent));
} else {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("INVALID Q_NUM\n")));
return -EFAULT;
}
/* FIXME: Reset all the queue stats for now. Individual queue stats for AP/STA needs to be
* modified.
*/
/* Reset Station queue stats */
#if 0
adapter->total_sta_data_vo_pkt_send = 0;
adapter->total_sta_vo_pkt_freed = 0;
adapter->total_sta_data_vi_pkt_send = 0;
adapter->total_sta_vi_pkt_freed = 0;
adapter->total_sta_data_be_pkt_send = 0;
adapter->total_sta_be_pkt_freed = 0;
adapter->total_sta_data_bk_pkt_send = 0;
adapter->total_sta_bk_pkt_freed = 0;
/* Reset AP queue stats */
adapter->total_ap_data_vo_pkt_send = 0;
adapter->total_ap_vo_pkt_freed = 0;
adapter->total_ap_data_vi_pkt_send = 0;
adapter->total_ap_vi_pkt_freed = 0;
adapter->total_ap_data_be_pkt_send = 0;
adapter->total_ap_be_pkt_freed = 0;
adapter->total_ap_data_bk_pkt_send = 0;
adapter->total_ap_bk_pkt_freed = 0;
adapter->tx_vo_dropped = 0;
adapter->tx_vi_dropped = 0;
adapter->tx_be_dropped = 0;
adapter->tx_bk_dropped = 0;
#endif
adapter->buf_semi_full_counter = 0;
adapter->buf_full_counter = 0;
adapter->no_buffer_fulls = 0;
#if 0
switch(qnum)
{
case VO_Q:
adapter->total_data_vo_pkt_send = 0;
adapter->total_vo_pkt_freed = 0;
break;
case VI_Q:
adapter->total_data_vi_pkt_send = 0;
adapter->total_vi_pkt_freed = 0;
break;
case BE_Q:
adapter->total_data_be_pkt_send = 0;
adapter->total_be_pkt_freed = 0;
break;
case BK_Q:
adapter->total_data_bk_pkt_send = 0;
adapter->total_bk_pkt_freed = 0;
break;
default:
adapter->total_data_vo_pkt_send = 0;
adapter->total_vo_pkt_freed = 0;
adapter->total_data_vi_pkt_send = 0;
adapter->total_vi_pkt_freed = 0;
adapter->total_data_be_pkt_send = 0;
adapter->total_be_pkt_freed = 0;
adapter->total_data_bk_pkt_send = 0;
adapter->total_bk_pkt_freed = 0;
break;
}
#endif
}
break;
case AGGR_LIMIT:
if(copy_from_user(&adapter->aggr_limit, wrq->u.data.pointer, wrq->u.data.length))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT(" Aggr Params Copying Failed\n")));
return -EINVAL;
}
printk("%s: Aggr params set are tx=%d rx=%d\n", __func__, adapter->aggr_limit.tx_limit, adapter->aggr_limit.rx_limit);
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap->iv_opmode == IEEE80211_M_STA){
break;
}
}
if(vap)
{
vap->hal_priv_vap->aggr_rx_limit = adapter->aggr_limit.rx_limit;
}
break;
case MASTER_READ:
{
printk("performing master read\n");
if(adapter->devdep_ops->onebox_do_master_ops(adapter, wrq->u.data.pointer, ONEBOX_MASTER_READ) != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT(" Data Read Failed\n")));
}
}
break;
case MASTER_WRITE:
{
printk("performing master write \n");
if(adapter->devdep_ops->onebox_do_master_ops(adapter, wrq->u.data.pointer, ONEBOX_MASTER_WRITE) != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT(" Data Write Failed\n")));
}
}
break;
case TEST_MODE:
{
printk("starting in test mode");
memcpy(&test, wrq->u.data.pointer, sizeof(test));
if(adapter->devdep_ops->onebox_send_debug_frame(adapter, &test) != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT(" Sending Debug frame Failed\n")));
}
}
break;
case SET_COUNTRY:
switch(value)
{
/* Countries in US Region */
case CTRY_BELGIUM:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'B';
ic->ic_regdomain.isocc[1] = 'G';
ic->ic_regdomain.pad[0] = 0; //Just an indication of the country, to refer index in regdm_table[]
break;
case CTRY_CANADA:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'C';
ic->ic_regdomain.isocc[1] = 'A';
ic->ic_regdomain.pad[0] = 0;
break;
case CTRY_MEXICO:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'M';
ic->ic_regdomain.isocc[1] = 'X';
ic->ic_regdomain.pad[0] = 0;
break;
case CTRY_UNITED_STATES:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'U';
ic->ic_regdomain.isocc[1] = 'S';
ic->ic_regdomain.pad[0] = 0;
break;
/* Countries in EU Region */
case CTRY_FRANCE:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'F';
ic->ic_regdomain.isocc[1] = 'R';
ic->ic_regdomain.pad[0] = 1;
break;
case CTRY_GERMANY:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'G';
ic->ic_regdomain.isocc[1] = 'R';
ic->ic_regdomain.pad[0] = 1;
break;
case CTRY_ITALY:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'I';
ic->ic_regdomain.isocc[1] = 'T';
ic->ic_regdomain.pad[0] = 1;
break;
/* Countries in Japan Region */
case CTRY_JAPAN:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'J';
ic->ic_regdomain.isocc[1] = 'P';
ic->ic_regdomain.pad[0] = 2;
break;
/* Countries in Rest of the World Region */
case CTRY_AUSTRALIA:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'A';
ic->ic_regdomain.isocc[1] = 'U';
ic->ic_regdomain.pad[0] = 3;
break;
case CTRY_INDIA:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'I';
ic->ic_regdomain.isocc[1] = 'N';
ic->ic_regdomain.pad[0] = 3;
break;
case CTRY_IRAN:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'I';
ic->ic_regdomain.isocc[1] = 'R';
ic->ic_regdomain.pad[0] = 3;
break;
case CTRY_MALAYSIA:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'M';
ic->ic_regdomain.isocc[1] = 'L';
ic->ic_regdomain.pad[0] = 3;
break;
case CTRY_NEW_ZEALAND:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'N';
ic->ic_regdomain.isocc[1] = 'Z';
ic->ic_regdomain.pad[0] = 3;
break;
case CTRY_RUSSIA:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'R';
ic->ic_regdomain.isocc[1] = 'S';
ic->ic_regdomain.pad[0] = 3;
break;
case CTRY_SINGAPORE:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'S';
ic->ic_regdomain.isocc[1] = 'G';
ic->ic_regdomain.pad[0] = 3;
break;
case CTRY_SOUTH_AFRICA:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = 'S';
ic->ic_regdomain.isocc[1] = 'A';
ic->ic_regdomain.pad[0] = 3;
break;
default:
ic->ic_regdomain.location = ' ';
ic->ic_regdomain.isocc[0] = '\0';
ic->ic_regdomain.isocc[1] = '\0';
ic->ic_regdomain.pad[0] = 3;
}
printk("In %s Line %d *********Recvd IOCTL code %d \n", __func__, __LINE__, value);
adapter->net80211_ops->onebox_media_init(ic);
break;
default:
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,("No match yet\n"));
return -EINVAL;
break;
}
}
else if(adapter->Driver_Mode == SNIFFER_MODE)
{
switch((unsigned char)wrq->u.data.flags)
{
case PER_RECEIVE:
adapter->endpoint_params.per_ch_bw = *(uint8 *)wrq->u.data.pointer;
adapter->recv_channel = (uint8)(wrq->u.data.flags >> 8);
adapter->endpoint_params.channel = adapter->recv_channel;
printk("In %s and %d ch_width %d recv_channel %d \n", __func__, __LINE__, adapter->endpoint_params.per_ch_bw, adapter->recv_channel);
adapter->devdep_ops->onebox_band_check(adapter);
adapter->devdep_ops->onebox_set_channel(adapter,adapter->recv_channel);
return ret_val;
break;
#ifdef TRILITHIC_RELEASE
case CH_UTIL_START:
if(adapter->ch_util_start_flag == 0){
if(copy_from_user(ic->ch_util, wrq->u.data.pointer, wrq->u.data.length))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Copying Failed\n")));
return -EINVAL;
}
++adapter->ch_util_start_flag;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,("**** Channel Utilization test Started ****\n"));
}
else
{
if(adapter->ch_util_start_flag == 1){
ic->ch_util->start_time = jiffies;
ic->ch_util->crc_pkt = 0;
adapter->os_intf_ops->onebox_init_sw_timer(&adapter->channel_util_timeout, (uint32)adapter,(void *)&ch_util_timeout_handler, msecs_to_jiffies(1000));
++adapter->ch_util_start_flag;
}
//msleep(1000);
ic->ch_util->tot_time = adapter->ch_util_tot_time;
//printk("%s: %d %lu\n",__func__,__LINE__,ic->ch_util->tot_time);
if(copy_to_user(wrq->u.data.pointer, ic->ch_util, wrq->u.data.length))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Copying Failed with error \n")));
return -EINVAL;
}
ic->ch_util->tot_on_air_occupancy = 0;
ic->ch_util->on_air_occupancy = 0;
ic->ch_util->tot_time = 0;
ic->ch_util->tot_len_of_pkt = 0;
ic->ch_util->tot_length_of_pkt = 0;
adapter->ch_util_tot_time = 0;
}
break;
case CH_UTIL_STOP:
adapter->ch_util_start_flag = 0;
adapter->os_intf_ops->onebox_memset(ic->ch_util, 0, sizeof(struct ch_utils));
adapter->os_intf_ops->onebox_remove_timer(&adapter->channel_util_timeout);
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,("**** Channel Utilization test Stopped ****\n"));
break;
#endif
default:
printk("Failed: in %d case\n",(unsigned char)wrq->u.data.flags);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,("No match yet\n"));
return -EINVAL;
break;
}
}
else
{
switch((unsigned char)wrq->u.data.flags)
{
case PER_TRANSMIT:
if(copy_from_user(&adapter->endpoint_params, wrq->u.data.pointer, wrq->u.data.length))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Copying Failed\n")));
return -EINVAL;
}
if(adapter->core_ops->onebox_start_per_tx(adapter))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Invalid arguments issued by user\n")));
return -EINVAL;
}
return 0;
break;
case PER_RECEIVE_STOP:
adapter->recv_stop = 1;
adapter->rx_running = 0;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,("PER_RECEIVE_STOP\n"));
case PER_RECEIVE:
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,("per_ch_bw :%d \n",adapter->endpoint_params.per_ch_bw));
adapter->endpoint_params.per_ch_bw = *(uint8 *)wrq->u.data.pointer;
adapter->recv_channel = (uint8)(wrq->u.data.flags >> 8);
adapter->endpoint_params.channel = adapter->recv_channel;
if (adapter->endpoint_params.channel == 0xFF)
{
if(adapter->devdep_ops->onebox_mgmt_send_bb_reset_req(adapter) != ONEBOX_STATUS_SUCCESS) {
return ONEBOX_STATUS_FAILURE;
}
}
else if (adapter->endpoint_params.channel)
{
adapter->os_intf_ops->onebox_reset_event(&(adapter->bb_rf_event));
adapter->devdep_ops->onebox_band_check(adapter);
adapter->devdep_ops->onebox_set_channel(adapter,adapter->recv_channel);
adapter->fsm_state = FSM_SCAN_CFM;
adapter->os_intf_ops->onebox_wait_event(&(adapter->bb_rf_event), EVENT_WAIT_FOREVER);
adapter->fsm_state = FSM_MAC_INIT_DONE;
}
adapter->os_intf_ops->onebox_reset_event(&(adapter->stats_event));
if (!adapter->rx_running)
{
if(!(adapter->core_ops->onebox_stats_frame(adapter)))
{
adapter->rx_running = 1;
if (adapter->recv_stop)
{
adapter->recv_stop = 0;
adapter->rx_running = 0;
return ONEBOX_STATUS_SUCCESS;
}
adapter->os_intf_ops->onebox_wait_event(&(adapter->stats_event), EVENT_WAIT_FOREVER);
ret_val = copy_to_user(wrq->u.data.pointer, &adapter->sta_info, sizeof(per_stats));
return ret_val;
}
}
else
{
adapter->os_intf_ops->onebox_wait_event(&(adapter->stats_event), EVENT_WAIT_FOREVER);
ret_val = copy_to_user(wrq->u.data.pointer, &adapter->sta_info, sizeof(per_stats));
return ret_val;
}
break;
case PER_PACKET:
if(copy_from_user(&adapter->per_packet, wrq->u.data.pointer, wrq->u.data.length))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Copying PER Packet Failed in %s\n"), __func__));
return -EINVAL;
}
ONEBOX_DEBUG(ONEBOX_ZONE_DEBUG, (TEXT("Copying PER Packet in %s\n"), __func__));
adapter->core_ops->onebox_dump(ONEBOX_ZONE_DEBUG, (PUCHAR)&adapter->per_packet.packet, adapter->per_packet.length);
return 0;
break;
case ANT_SEL:
value = ((unsigned short)wrq->u.data.flags >> 8); //endpoint value
printk("ANT_SEL value is : %d \n",value);
adapter->devdep_ops->onebox_program_ant_sel(adapter, value);
break;
case SET_ENDPOINT:
value = ((unsigned short)wrq->u.data.flags >> 8); //endpoint value
printk("ENDPOINT type is : %d \n",value);
adapter->endpoint = value;
#ifdef PROGRAMMING_BBP_TA
adapter->devdep_ops->onebox_program_bb_rf(adapter);
#else
if (value == 0)
{
adapter->endpoint_params.per_ch_bw = 0;
adapter->endpoint_params.channel = 1;
}
else if (value == 1)
{
adapter->endpoint_params.per_ch_bw = 6;
adapter->endpoint_params.channel = 1;
}
else if (value == 2)
{
adapter->endpoint_params.per_ch_bw = 0;
adapter->endpoint_params.channel = 36;
}
else if (value == 3)
{
adapter->endpoint_params.per_ch_bw = 6;
adapter->endpoint_params.channel = 36;
}
adapter->devdep_ops->onebox_band_check(adapter);
#endif
break;
case EEPROM_READ_IOCTL:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,("ONEBOX_IOCTL: EEPROM READ \n"));
adapter->os_intf_ops->onebox_memset(&adapter->eeprom, 0, sizeof(EEPROMRW));
if(copy_from_user(&adapter->eeprom, wrq->u.data.pointer,
(sizeof(EEPROMRW) - sizeof(adapter->eeprom.data))))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Copying Failed\n")));
return -EINVAL;
}
status = adapter->devdep_ops->onebox_eeprom_rd(adapter);
if (status == ONEBOX_STATUS_SUCCESS)
{
adapter->os_intf_ops->onebox_reset_event(&(adapter->bb_rf_event));
adapter->os_intf_ops->onebox_wait_event(&(adapter->bb_rf_event), 10000);
ONEBOX_DEBUG(ONEBOX_ZONE_DEBUG, (TEXT(" eeprom length: %d, \n"), adapter->eeprom.length));
ONEBOX_DEBUG(ONEBOX_ZONE_DEBUG, (TEXT(" eeprom offset: %d, \n"), adapter->eeprom.offset));
ret_val = copy_to_user(wrq->u.data.pointer, &adapter->eeprom, sizeof(EEPROMRW));
return ret_val;
}
else
{
return ONEBOX_STATUS_FAILURE;
}
}
break;
#if 0
case EEPROM_WRITE_IOCTL:
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,("ONEBOX_IOCTL: EEPROM WRITE \n"));
#if 1
if(copy_from_user(&adapter->eeprom, wrq->u.data.pointer, wrq->u.data.length))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Copying Failed\n")));
return -EINVAL;
}
#endif
adapter->eeprom.length = (wrq->u.data.length - 10);
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("===> Frame to WRITE IN TO EEPROM <===\n")));
mgmt_frame = (onebox_mac_frame_t *)pkt_buffer;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, FRAME_DESC_SZ);
/* FrameType*/
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(EEPROM_WRITE);
mgmt_frame->desc_word[0] = (ONEBOX_WIFI_MGMT_Q << 12 | adapter->eeprom.length);
if (!adapter->eeprom_erase)
{
mgmt_frame->desc_word[2] = ONEBOX_CPU_TO_LE16(BIT(10));
adapter->eeprom_erase = 1;
}
/* Number of bytes to read*/
mgmt_frame->desc_word[3] = ONEBOX_CPU_TO_LE16(adapter->eeprom.length);
/* Address to read*/
mgmt_frame->desc_word[4] = ONEBOX_CPU_TO_LE16(adapter->eeprom.offset);
mgmt_frame->desc_word[5] = ONEBOX_CPU_TO_LE16(adapter->eeprom.offset >> 16);
adapter->os_intf_ops->onebox_memcpy(mgmt_frame->u.byte.buf, adapter->eeprom.data, adapter->eeprom.length);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, FRAME_DESC_SZ + adapter->eeprom.length);
status = adapter->osi_host_intf_ops->onebox_host_intf_write_pkt(adapter,
(uint8 *)mgmt_frame,
FRAME_DESC_SZ + adapter->eeprom.length);
if (status == ONEBOX_STATUS_SUCCESS)
{
adapter->os_intf_ops->onebox_wait_event(&(adapter->bb_rf_event), 10000);
adapter->os_intf_ops->onebox_memset(adapter->eeprom.data, 0, 480);
return ONEBOX_STATUS_SUCCESS;
}
else
{
return ONEBOX_STATUS_FAILURE;
}
}
break;
#endif
case PS_REQUEST:
{
if((adapter->Driver_Mode == RF_EVAL_MODE_ON)) {
send_sleep_req_in_per_mode(adapter, wrq->u.data.pointer);
}
break;
}
case RF_PWR_MODE:
{
memcpy(&adapter->rf_pwr_mode, wrq->u.data.pointer, sizeof(adapter->rf_pwr_mode));
adapter->rf_power_mode_change = 1;
printk("Setting RF PWR MODE %04x\n", adapter->rf_pwr_mode);
break;
}
default:
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,("No match yet\n"));
return -EINVAL;
break;
}
}
return ret_val;
}
break;
case ONEBOX_SET_BB_RF:
{
// if(adapter->Driver_Mode == RF_EVAL_MODE_ON)
{
if(copy_from_user(&adapter->bb_rf_params.Data[0], wrq->u.data.pointer, (sizeof(adapter->bb_rf_params))))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Copying Failed\n")));
return -EINVAL;
}
if(adapter->devdep_ops->onebox_set_bb_rf_values(adapter, wrq))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Invalid arguments issued by user\n")));
return -EINVAL;
}
return ONEBOX_STATUS_SUCCESS;
}
}
break;
case ONEBOX_SET_CW_MODE:
{
if(adapter->Driver_Mode == RF_EVAL_MODE_ON)
{
channel = (uint8 )wrq->u.data.flags;
if (!channel)
channel = 1;
if(channel <= 14)
{
set_band = BAND_2_4GHZ;
adapter->endpoint = 0;
}
else if((channel >= 36) && (channel <= 165))
{
set_band = BAND_5GHZ;
adapter->endpoint = 2;
}
if (adapter->operating_band != set_band)
{
adapter->operating_band = set_band;
adapter->rf_reset = 1;
adapter->devdep_ops->onebox_program_bb_rf(adapter);
}
adapter->devdep_ops->onebox_set_channel(adapter,channel);
adapter->fsm_state = FSM_SCAN_CFM;
adapter->os_intf_ops->onebox_reset_event(&(adapter->bb_rf_event));
adapter->os_intf_ops->onebox_wait_event(&(adapter->bb_rf_event), EVENT_WAIT_FOREVER);
adapter->fsm_state = FSM_MAC_INIT_DONE;
channel = (unsigned int)wrq->u.data.flags; //cw_type & subtype info
adapter->cw_type = (channel & 0x0f00) >> 8 ;
adapter->cw_sub_type = (channel & 0xf000) >> 12 ;
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("ONEBOX_IOCTL: SET_CW_MODE , cw_type:%d cw_mode:%d channel : %d\n"),adapter->cw_sub_type,adapter->cw_type, channel));
if(adapter->devdep_ops->onebox_cw_mode(adapter, adapter->cw_sub_type))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Invalid arguments issued by user\n")));
return -EINVAL;
}
break;
return ONEBOX_STATUS_SUCCESS;
}
}
break;
default:
{
if (priv == 0) /* req is a standard ioctl */
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, ("Standard ioctl: %d\n", index));
}
else /* Ignore it, Bad ioctl */
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, ("Unrecognised ioctl: %d\n", cmd));
}
return -EFAULT;
}
}
return ret_val;
}
<file_sep>/wlan/wlan_hal/osd_wlan/linux/onebox_wlan_osd_init.c
/**
* @file onebox_osd_main.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contains all the Linux network device specific code.
*/
#include "onebox_common.h"
#include "onebox_linux.h"
#include "onebox_sdio_intf.h"
static uint32 tcp_csumoffld_enable =0;
static uint8 device_mac_addr[6] = {0x00, 0x23, 0xa7, 0x1b, 0x52, 0x3a};
static PONEBOX_ADAPTER adapter;
/**
* Allocate & initialize the network device.This function
* allocates memory for the network device & initializes
* it with ethernet generic values.
*
* @param size of the priv area to be allocated.
* @return Pointer to the network device structure.
*/
static struct net_device* onebox_allocdev(int32 sizeof_priv)
{
struct net_device *dev = NULL;
dev = alloc_netdev(sizeof_priv, "rpine%d", ether_setup);
return dev;
}/* End of <onebox_allocdev> */
/**
* This function register the network device.
*
* @param Pointer to our network device structure.
* @return On success 0 is returned else a negative value.
*/
static int32 onebox_registerdev(struct net_device *dev)
{
return register_netdev(dev);
}/* End of <onebox_registerdev> */
/**
* This function unregisters the network device & returns it
* back to the kernel.
*
* @param Pointer to our network device structure.
* @return VOID.
*/
VOID unregister_dev(struct net_device *dev)
{
unregister_netdev(dev);
free_netdev(dev);
return;
} /* End of <onebox_unregisterdev> */
/**
* This function gives the statistical information regarding
* the interface.
*
* @param Pointer to our network device strucure.
* @return Pointer to the net_device_stats structure .
*/
static struct net_device_stats* onebox_get_stats(struct net_device *dev)
{
PONEBOX_ADAPTER Adapter = netdev_priv(dev);
return &Adapter->stats;
} /* End of <onebox_get_stats> */
/**
* This function performs all net device related operations
* like allocating,initializing and registering the netdevice.
*
* @param VOID.
* @return On success 0 is returned else a negative value.
*/
struct net_device* wlan_netdevice_op(VOID)
{
struct net_device *dev;
#if KERNEL_VERSION_BTWN_2_6_(18, 27)
/*Allocate & initialize the network device structure*/
dev = onebox_allocdev(sizeof(ONEBOX_ADAPTER));
if (dev == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s:Failure in allocation of net-device\n"),__func__));
return dev;
}
dev->open = device_open;
dev->stop = device_close;
dev->hard_start_xmit = onebox_xmit;
dev->get_stats = onebox_get_stats;
dev->do_ioctl = onebox_ioctl;
//dev->wireless_handlers = &onebox_handler_def;
dev->hard_header_len = FRAME_DESC_SZ + RSI_DESCRIPTOR_SZ; /* 64 + 16 */
if (tcp_csumoffld_enable)
{
dev->features |= NETIF_F_IP_CSUM;
}
if (onebox_registerdev(dev) != 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Registration of net-device failed\n"), __func__));
free_netdev(dev);
return NULL;
}
#elif KERNEL_VERSION_GREATER_THAN_2_6_(27)
static const struct net_device_ops onebox_netdev_ops =
{
.ndo_open = device_open,
.ndo_stop = device_close,
.ndo_start_xmit = onebox_xmit,
.ndo_get_stats = onebox_get_stats,
.ndo_do_ioctl = onebox_ioctl,
};
/*Allocate & initialize the network device structure*/
dev = onebox_allocdev(sizeof(ONEBOX_ADAPTER));
if (dev == NULL) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Failure in allocation of net-device\n"),
__func__));
goto noalloc;
}
//dev->wireless_handlers = &onebox_handler_def;
dev->hard_header_len = FRAME_DESC_SZ + ONEBOX_DESCRIPTOR_SZ; /* 64 + 16 */
dev->netdev_ops = &onebox_netdev_ops;
if (tcp_csumoffld_enable)
{
dev->features |= NETIF_F_IP_CSUM;
}
if (onebox_registerdev(dev) != 0) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Registration of net-device failed\n"),
__func__));
goto nodev;
}
return dev;
nodev:
free_netdev(dev);
dev = NULL;
noalloc:
return dev;
#endif
}/* End of <wlan_netdevice_op> */
/**
* This function is called by OS when we UP the
* interface.
*
* @param Pointer to network device
* @return Success
*/
int device_open(struct net_device *dev)
{
//netif_start_queue(dev);
dev->flags |= IFF_RUNNING;
return 0;
}
/**
* This function is called by OS when the interface
* status changed to DOWN.
*
* @param dev Pointer to network device
*/
int device_close(struct net_device *dev)
{
if (!netif_queue_stopped(dev))
{
netif_stop_queue(dev);
}
return 0;
}
static ONEBOX_STATUS wlan_gpl_read_pkt(netbuf_ctrl_block_t *netbuf_cb)
{
struct driver_assets *d_assets = onebox_get_driver_asset();
PONEBOX_ADAPTER w_adapter = (PONEBOX_ADAPTER)d_assets->techs[WLAN_ID].priv;
w_adapter->os_intf_ops->onebox_acquire_sem(&w_adapter->wlan_gpl_lock, 0);
if (d_assets->techs[WLAN_ID].drv_state == MODULE_ACTIVE) {
wlan_read_pkt(w_adapter, netbuf_cb);
} else {
printk("WLAN is being removed.. Dropping Pkt\n");
w_adapter->os_intf_ops->onebox_free_pkt(w_adapter, netbuf_cb, 0);
netbuf_cb = NULL;
}
w_adapter->os_intf_ops->onebox_release_sem(&w_adapter->wlan_gpl_lock);
return ONEBOX_STATUS_SUCCESS;
}
static void dump_wlan_mgmt_pending_pkts(void)
{
netbuf_ctrl_block_t *netbuf_cb = NULL;
struct driver_assets *d_assets = onebox_get_driver_asset();
PONEBOX_ADAPTER adapter = (PONEBOX_ADAPTER)d_assets->techs[WLAN_ID].priv;
for(;;)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s:%d ==> PKT IN MGMT QUEUE count %d <==\n"), __func__, __LINE__, adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->host_tx_queue[MGMT_SOFT_Q])));
if (adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->host_tx_queue[MGMT_SOFT_Q]))
{
//netbuf_cb = core_dequeue_pkt(adapter, MGMT_SOFT_Q);
netbuf_cb = adapter->os_intf_ops->onebox_dequeue_pkt((void *)&adapter->host_tx_queue[MGMT_SOFT_Q]);
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s:%d ==> PKT IN MGMT QUEUE <==\n"), __func__, __LINE__));
if(netbuf_cb){
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (uint8 *)netbuf_cb->data, netbuf_cb->len);
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
}
}
else{
break;
}
}
}
static ONEBOX_STATUS wlan_update_buf_status(uint8 device_buf_status)
{
struct driver_assets *d_assets = onebox_get_driver_asset();
PONEBOX_ADAPTER w_adapter = (PONEBOX_ADAPTER)d_assets->techs[WLAN_ID].priv;
if (d_assets->techs[WLAN_ID].drv_state == MODULE_ACTIVE) {
//printk("_UBS_");
w_adapter->buf_status_updated = 1;
if(device_buf_status & (ONEBOX_BIT(SD_PKT_MGMT_BUFF_FULL)))
{
w_adapter->mgmt_buffer_full = 1;
}
else
{
w_adapter->mgmt_buffer_full = 0;
}
if(device_buf_status & (ONEBOX_BIT(SD_PKT_BUFF_FULL)))
{
w_adapter->buffer_full = 1;
}
else
{
w_adapter->buffer_full = 0;
}
if(device_buf_status & (ONEBOX_BIT(SD_PKT_BUFF_SEMI_FULL)))
{
w_adapter->semi_buffer_full = 1;
}
else
{
w_adapter->semi_buffer_full = 0;
}
w_adapter->os_intf_ops->onebox_set_event(&(w_adapter->sdio_scheduler_event));
/* This Interrupt Is Recvd When The Hardware Buffer Is Empty */
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("%s: ==> BUFFER_AVILABLE <==\n"), __func__));
w_adapter->buf_avilable_counter++;
} else {
printk("WLAN not active and hence no buffer updates\n");
}
return ONEBOX_STATUS_SUCCESS;
}
/**
* Os sends packet to driver using this function.
* @param Pointer to struct sk_buff containing the payload
* to be transmitted.
* @param Pointer to network device
*/
int onebox_xmit(struct sk_buff *skb, struct net_device *dev)
{
void * ni;
uint16 flags;
PONEBOX_ADAPTER adapter;
netbuf_ctrl_block_t *netbuf_cb;
adapter = netdev_priv(dev);
FUNCTION_ENTRY(ONEBOX_ZONE_DATA_SEND);
netbuf_cb = (netbuf_ctrl_block_t *)skb->cb;
/* Store the required skb->cb content temporarily before modifying netbuf_cb
* because both of them have the same memory */
ni =(void *)SKB_CB(skb)->ni;
flags =(uint16)SKB_CB(skb)->flags;
/* Now assign the required fields of netbuf_cb for hal operations */
netbuf_cb->ni = ni;
netbuf_cb->flags = flags;
netbuf_cb->skb_priority = skb_get_queue_mapping(skb);
netbuf_cb->pkt_addr = (void *)skb;
netbuf_cb->len = skb->len;
netbuf_cb->data = skb->data;
netbuf_cb->priority = skb->priority;
adapter->core_ops->onebox_dump(ONEBOX_ZONE_INFO, netbuf_cb->data, netbuf_cb->len);
adapter->core_ops->onebox_core_xmit(adapter, netbuf_cb);
return ONEBOX_STATUS_SUCCESS;
}
/*
* This function deregisters WLAN firmware
* @param Pointer to adapter structure.
* @return 0 if success else -1.
*/
static ONEBOX_STATUS wlan_deregister_fw(PONEBOX_ADAPTER adapter)
{
onebox_mac_frame_t *mgmt_frame;
netbuf_ctrl_block_t *netbuf_cb = NULL;
ONEBOX_STATUS status = ONEBOX_STATUS_SUCCESS;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("===> Deregister WLAN FW <===\n")));
netbuf_cb = adapter->os_intf_ops->onebox_alloc_skb(FRAME_DESC_SZ);
if(netbuf_cb == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: Unable to allocate skb\n"), __func__));
status = ONEBOX_STATUS_FAILURE;
return status;
}
adapter->os_intf_ops->onebox_add_data_to_skb(netbuf_cb, FRAME_DESC_SZ);
mgmt_frame = (onebox_mac_frame_t *)netbuf_cb->data;
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, FRAME_DESC_SZ);
/* FrameType*/
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(WLAN_DE_REGISTER);
#define IMMEDIATE_WAKEUP 1
mgmt_frame->desc_word[0] = ((ONEBOX_WIFI_MGMT_Q << 12)| (IMMEDIATE_WAKEUP << 15));
netbuf_cb->tx_pkt_type = WLAN_TX_M_Q;
printk("<==== DEREGISTER FRAME ====>\n");
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)mgmt_frame, FRAME_DESC_SZ);
status = adapter->onebox_send_pkt_to_coex(netbuf_cb, WLAN_Q);
if (status != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT
("%s: Failed To Write The Packet\n"),__func__));
}
#undef IMMEDIATE_WAKEUP
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
return status;
}
/**
* This function is triggered whenever wlan module is
* inserted. Links wlan module with hal module
* work is done here.
*
* @return
*/
static int32 wlan_insert(void)
{
struct net_device *dev = NULL;
uint8 count =0;
struct onebox_core_operations *core_ops = onebox_get_core_wlan_operations();
struct onebox_net80211_operations *net80211_ops = onebox_get_net80211_operations();
struct onebox_devdep_operations *devdep_ops = onebox_get_devdep_wlan_operations();
struct onebox_osi_host_intf_operations *osi_host_intf_ops = onebox_get_osi_host_intf_operations();
struct onebox_osd_host_intf_operations *osd_host_intf_ops = onebox_get_osd_host_intf_operations();
struct onebox_os_intf_operations *os_intf_ops = onebox_get_os_intf_operations();
struct ieee80211_rate_ops *core_rate_ops = onebox_get_ieee80211_rate_ops();
struct onebox_wlan_osd_operations *wlan_osd_ops = onebox_get_wlan_osd_operations_from_origin();
struct driver_assets *d_assets = onebox_get_driver_asset();
struct wireless_techs *wlan_d;
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("In %s Line %d: initializing WLAN Layer\n"),__func__, __LINE__));
os_intf_ops->onebox_acquire_sem(&d_assets->wlan_init_lock, 0);
if(d_assets->techs[WLAN_ID].drv_state == MODULE_ACTIVE) {
printk("In %s Line %d WLAN Module is already initialized\n", __func__, __LINE__);
os_intf_ops->onebox_release_sem(&d_assets->wlan_init_lock);
return ONEBOX_STATUS_SUCCESS;
}
dev = wlan_netdevice_op();
if (!dev) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Failed to initialize a network device\n"), __func__));
goto nodev;
}
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,
(TEXT("%s: Net device operations suceeded\n"), __func__));
adapter = os_intf_ops->onebox_get_priv(dev); /*we can also use dev->priv;*/
os_intf_ops->onebox_memset(adapter, 0, sizeof(ONEBOX_ADAPTER));
/* Initialise the Core and device dependent operations */
adapter->core_ops = core_ops;
adapter->net80211_ops = net80211_ops;
adapter->devdep_ops = devdep_ops;
adapter->osd_host_intf_ops = osd_host_intf_ops;
adapter->osi_host_intf_ops = osi_host_intf_ops;
adapter->os_intf_ops = os_intf_ops;
adapter->core_rate_ops = core_rate_ops;
adapter->wlan_osd_ops = wlan_osd_ops;
adapter->dev = dev;
os_intf_ops->onebox_init_dyn_mutex(&adapter->wlan_gpl_lock);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Mutex init successfull\n"), __func__));
os_intf_ops->onebox_init_event(&(adapter->sdio_scheduler_event));
os_intf_ops->onebox_init_event(&(adapter->stats_event));
os_intf_ops->onebox_init_event(&(adapter->bb_rf_event));
d_assets->techs[WLAN_ID].priv = (void *)adapter;
#ifdef USE_SDIO_INTF
adapter->pfunction = (struct sdio_func *)d_assets->pfunc;
adapter->buffer_status_register = ONEBOX_DEVICE_BUFFER_STATUS_REGISTER;
#else
adapter->pfunction = (struct usb_interface *)d_assets->pfunc;
adapter->buffer_status_register = d_assets->techs[WLAN_ID].buffer_status_reg_addr;
#endif
adapter->onebox_send_pkt_to_coex = send_pkt_to_coex;
if (wlan_osd_ops->onebox_init_wlan_thread(&(adapter->sdio_scheduler_thread_handle),
"WLAN-Thread",
0,
devdep_ops->onebox_sdio_scheduler_thread,
adapter) != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("%s: Unable to initialize thrd\n"), __func__));
goto fail;
}
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Initialized thread & Event\n"), __func__));
/* start the transmit thread */
os_intf_ops->onebox_start_thread( &(adapter->sdio_scheduler_thread_handle));
os_intf_ops->onebox_strcpy(adapter->name, "onebox-mobile");
os_intf_ops->onebox_start_netq(adapter->dev);
init_waitqueue_head(&d_assets->techs[WLAN_ID].deregister_event);
/*FIXME: why is read reg parameters not called from here?? */
//read_reg_parameters(adapter);
adapter->recv_channel = 1;
adapter->RFType = ONEBOX_RF_8111;
adapter->def_chwidth = BW_20Mhz;
/*The operating band will be later initialized based on the band from eeprom reads */
adapter->operating_band = BAND_2_4GHZ;
adapter->operating_chwidth = BW_20Mhz;
adapter->calib_mode = 0;
adapter->per_lpbk_mode = 0;
adapter->aggr_limit.tx_limit = 11;
adapter->aggr_limit.rx_limit = 64;
adapter->Driver_Mode = d_assets->asset_role;
printk("Driver mode in WLAN is %d\n", adapter->Driver_Mode);
if (adapter->Driver_Mode == RF_EVAL_LPBK_CALIB)
{
/*FIXME: Try to optimize these conditions */
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("onebox_read_reg_param: RF Eval LPBK CALIB mode on\n")));
adapter->Driver_Mode = RF_EVAL_MODE_ON; /* RF EVAL mode */
adapter->calib_mode = 1;
adapter->per_lpbk_mode = 1;
}
else if (adapter->Driver_Mode == RF_EVAL_LPBK)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT, (TEXT("onebox_read_reg_param: RF Eval LPBK mode on\n")));
adapter->Driver_Mode = RF_EVAL_MODE_ON; /* RF EVAL mode */
adapter->per_lpbk_mode = 1;
}
adapter->PassiveScanEnable = ONEBOX_FALSE;
adapter->config_params.BT_coexistence = 0;
adapter->isMobileDevice = ONEBOX_TRUE;
adapter->max_stations_supported = MAX_STATIONS_SUPPORTED;
adapter->os_intf_ops->onebox_memcpy(adapter->mac_addr, device_mac_addr, ETH_ALEN);
adapter->os_intf_ops->onebox_memcpy(adapter->dev->dev_addr, adapter->mac_addr, ETH_ALEN);
ONEBOX_DEBUG(ONEBOX_ZONE_FSM, (TEXT("WLAN : Card read indicated\n")));
/* initializing tx soft queues */
for (count = 0; count < NUM_SOFT_QUEUES; count++)
adapter->os_intf_ops->onebox_netbuf_queue_init(&adapter->host_tx_queue[count]);
if (onebox_umac_init_done(adapter)!= ONEBOX_STATUS_SUCCESS)
goto fail;
d_assets->techs[WLAN_ID].drv_state = MODULE_ACTIVE;
wlan_d = &d_assets->techs[WLAN_ID];
wlan_d->tx_intention = 1;
while(1) {
msleep(1);
d_assets->update_tx_status(WLAN_ID);
if(wlan_d->tx_access)
break;
count++;
if(count > 500)
break;
printk("Waiting for TX access\n");
}
if (!wlan_d->tx_access) {
d_assets->techs[WLAN_ID].deregister_flags = 1;
if (wait_event_timeout((wlan_d->deregister_event), (d_assets->techs[WLAN_ID].deregister_flags == 0), msecs_to_jiffies(6000) )) {
} else {
printk("ERR: In %s Line %d Initialization of WLAN Failed as Wlan TX access is not granted from Common Hal \n", __func__, __LINE__);
goto fail;
}
}
if (onebox_load_bootup_params(adapter) != ONEBOX_STATUS_SUCCESS) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT ("%s: Failed to load bootup parameters\n"),
__func__));
goto fail;
}
ONEBOX_DEBUG(ONEBOX_ZONE_FSM,
(TEXT("%s: BOOTUP Parameters loaded successfully\n"),__func__));
adapter->fsm_state = FSM_LOAD_BOOTUP_PARAMS ;
os_intf_ops->onebox_init_dyn_mutex(&adapter->ic_lock_vap);
printk("wlan hal: Init proc entry call\n");
if (setup_wlan_procfs(adapter))
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT ("%s: Failed to setup wlan procfs entry\n"),__func__));
os_intf_ops->onebox_release_sem(&d_assets->wlan_init_lock);
//Initializing Queue Depths
adapter->host_txq_maxlen[BK_Q_STA] = adapter->host_txq_maxlen[BK_Q_AP] = MAX_BK_QUEUE_LEVEL;
adapter->host_txq_maxlen[BE_Q_STA] = adapter->host_txq_maxlen[BE_Q_AP] = MAX_BE_QUEUE_LEVEL;
adapter->host_txq_maxlen[VI_Q_STA] = adapter->host_txq_maxlen[VI_Q_AP] = MAX_VI_QUEUE_LEVEL;
adapter->host_txq_maxlen[VO_Q_STA] = adapter->host_txq_maxlen[VO_Q_AP] = MAX_VO_QUEUE_LEVEL;
return ONEBOX_STATUS_SUCCESS;
fail:
if (dev)
unregister_dev(dev);
nodev:
os_intf_ops->onebox_release_sem(&d_assets->wlan_init_lock);
return -ENOMEM;
}/* End <wlan_insert> */
/**
* This function removes the wlan module safely..
*
* @param Pointer to sdio_func structure.
* @param Pointer to sdio_device_id structure.
* @return VOID.
*/
static int32 wlan_remove(void)
{
struct net_device *dev = adapter->dev;
struct onebox_os_intf_operations *os_intf_ops = onebox_get_os_intf_operations();
struct onebox_wlan_osd_operations *wlan_osd_ops = onebox_get_wlan_osd_operations_from_origin();
struct driver_assets *d_assets = onebox_get_driver_asset();
struct wireless_techs *wlan_d = &d_assets->techs[WLAN_ID];
adapter->os_intf_ops->onebox_acquire_sem(&adapter->wlan_gpl_lock, 0);
#if 0
if(wlan_d->fw_state == FW_INACTIVE)
{
printk("%s Line %d FW is already in INACTIVE state no need to perform any changes\n", __func__, __LINE__);
adapter->os_intf_ops->onebox_release_sem(&adapter->wlan_gpl_lock);
return ONEBOX_STATUS_SUCCESS;
}
#endif
FUNCTION_ENTRY(ONEBOX_ZONE_INFO);
#if KERNEL_VERSION_BTWN_2_6_(18, 26)
wlan_osd_ops->onebox_kill_wlan_thread(&adapter->sdio_scheduler_thread_handle);
#elif KERNEL_VERSION_GREATER_THAN_2_6_(27)
wlan_osd_ops->onebox_kill_wlan_thread(adapter);
#endif
os_intf_ops->onebox_delete_event(&(adapter->stats_event));
/* Removing channel_util_timeout timer here */
if (adapter == NULL) {
printk("In %s %d NULL ADAPTER\n", __func__, __LINE__);
}
printk("In %s Line %d \n", __func__, __LINE__);
if ((adapter->channel_util_timeout.function != NULL) &&
(adapter->os_intf_ops->onebox_sw_timer_pending(&adapter->channel_util_timeout))) {
printk("In %s Line %d channel utilization timer was pending\n", __func__, __LINE__);
adapter->os_intf_ops->onebox_remove_timer(&adapter->channel_util_timeout);
printk("In %s Line %d \n", __func__, __LINE__);
}
printk("In %s Line %d \n", __func__, __LINE__);
adapter->core_ops->onebox_core_deinit(adapter);
if (d_assets->card_state != GS_CARD_DETACH) {
wlan_d->tx_intention = 1;
d_assets->update_tx_status(WLAN_ID);
if(!wlan_d->tx_access) {
d_assets->techs[WLAN_ID].deregister_flags = 1;
if(wait_event_timeout((wlan_d->deregister_event), (d_assets->techs[WLAN_ID].deregister_flags == 0), msecs_to_jiffies(6000))) {
if(wlan_d->tx_access)
wlan_deregister_fw(adapter);
}
else
printk("Failed to get sleep exit\n");
} else {
wlan_deregister_fw(adapter);
}
WLAN_TECH.tx_intention = 0;
WLAN_TECH.tx_access = 0;
d_assets->update_tx_status(WLAN_ID);
}
d_assets->techs[WLAN_ID].fw_state = FW_INACTIVE;
/*Return the network device to the kernel*/
if(adapter->dev != NULL) {
printk("IN %s Line %d Unregistering netdev \n", __func__, __LINE__);
unregister_dev(dev);
//adapter->dev = NULL;
destroy_wlan_procfs();
}
adapter->os_intf_ops->onebox_release_sem(&adapter->wlan_gpl_lock);
FUNCTION_EXIT(ONEBOX_ZONE_INFO);
return ONEBOX_STATUS_SUCCESS;
}/* End <onebox_disconnect> */
ONEBOX_STATIC int32 onebox_wlangpl_module_init(VOID)
{
int32 rc = 0;
struct driver_assets *d_assets =
onebox_get_driver_asset();
d_assets->techs[WLAN_ID].drv_state = MODULE_INSERTED;
d_assets->techs[WLAN_ID].inaugurate = wlan_insert;
d_assets->techs[WLAN_ID].disconnect = wlan_remove;
d_assets->techs[WLAN_ID].onebox_get_pkt_from_coex = wlan_gpl_read_pkt;
d_assets->techs[WLAN_ID].onebox_get_buf_status = wlan_update_buf_status;
d_assets->techs[WLAN_ID].wlan_dump_mgmt_pending = dump_wlan_mgmt_pending_pkts;
if (d_assets->card_state == GS_CARD_ABOARD) {
if((d_assets->techs[WLAN_ID].fw_state == FW_ACTIVE) && (d_assets->techs[WLAN_ID].drv_state != MODULE_ACTIVE)) {
rc = wlan_insert();
if (rc) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT ("%s: failed to insert "
"wlan error[%d]\n"),__func__, rc));
return 0;
}
}
}
printk("WLAN : Wlan gpl installed\n ");
return 0;
}
ONEBOX_STATIC VOID onebox_wlangpl_module_exit(VOID)
{
struct driver_assets *d_assets =
onebox_get_driver_asset();
struct wireless_techs *wlan_d;
printk("In %s Line %d \n", __func__, __LINE__);
if (d_assets->techs[WLAN_ID].drv_state == MODULE_ACTIVE) {
printk("In %s Line %d waiting for even\n", __func__, __LINE__);
//d_assets->techs[WLAN_ID].deregister_flags = 1;
wlan_d = &d_assets->techs[WLAN_ID];
wlan_remove();
}
d_assets->techs[WLAN_ID].drv_state = MODULE_REMOVED;
d_assets->techs[WLAN_ID].inaugurate = NULL;
d_assets->techs[WLAN_ID].disconnect = NULL;
d_assets->techs[WLAN_ID].onebox_get_pkt_from_coex = NULL;
d_assets->techs[WLAN_ID].onebox_get_buf_status = NULL;
return;
}
module_init(onebox_wlangpl_module_init);
module_exit(onebox_wlangpl_module_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Redpine Signals Inc");
MODULE_DESCRIPTION("Coexistance Solution From Redpine Signals");
MODULE_SUPPORTED_DEVICE("Godavari RS911x WLAN Modules");
MODULE_VERSION("0.1");
<file_sep>/utils/sniffer.c
/**
* @file receive.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file prints the Per frames received from the PPE
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <linux/types.h>
#include <linux/if.h>
#include <linux/wireless.h>
#include "onebox_util.h"
#define PER_MODE
void sniffer_usage(char *argv)
{
printf("Onebox dump stats application\n");
ONEBOX_PRINT
("Usage: %s base_interface sniffer_mode channel_number channel_BW \n",argv);
ONEBOX_PRINT
("Usage: %s base_interface ch_utilization RSSI_threshold start/stop_bit(1 - start,0 - stop)\n",argv);
printf("\tChannel BW - 0: 20MHz, 2: Upper 40MHz, 4: Lower 40MHz & 6: Full 40MHz \n");
return ;
}
int sniffer_getcmdnumber (char *command)
{
if (!strcmp (command, "sniffer_mode"))
{
return SNIFFER_MODE;
}
if (!strcmp (command, "ch_utilization"))
{
return CH_UTILIZATION;
}
}
int channel_width_validation(unsigned short ch_width)
{
if((ch_width != 0) && (ch_width != 2) && (ch_width != 4) && (ch_width != 6))
{
return 1;
}
return 0;
}
int freq_validation(int freq,unsigned short ch_width)
{
unsigned int valid_channels_5_Ghz_40Mhz[] = { 38, 42, 46, 50, 54, 58, 62, 102,\
106, 110, 114, 118, 122, 126, 130, 134, 138,\
151, 155, 159, 163 };
unsigned int valid_channels_5_Ghz[] = { 36, 40, 44, 48, 52, 56, 60, 64, 100,\
104, 108, 112, 116, 120, 124, 128, 132, 136,\
140, 149, 153, 157, 161, 165 };
int i;
if (freq == 0xFF)
{
/* Pass 0xFF so as to skip channel programming */
}
else if((freq >= 36 && freq <= 165 && !ch_width))
{
for(i = 0; i < 24; i++)
{
if(freq == valid_channels_5_Ghz[i])
{
break;
}
}
if(i == 24)
{
return 1;
}
}
else if((freq >= 36 && freq <= 165 && ch_width))
{
for(i = 0; i < 21; i++)
{
if(freq == valid_channels_5_Ghz_40Mhz[i])
{
break;
}
}
if(i == 21)
{
return 1;
}
}
else if(!(freq <= 14))
{
return 1;
}
return 0;
}
int main(int argc, char **argv)
{
char ifName[32];
int cmdNo = -1;
int sockfd;
int freq;
int exit_var = 0;
int rssi_threshold;
int first_time = 0;
int count = 0, start_bit = 0;
int i;
unsigned short ch_width = 0;
double tot_time = 0;
double on_air_occupancy = 0;
double tot_on_air_occupancy = 0;
struct iwreq iwr;
if (argc < 3)
{
sniffer_usage(argv[0]);
}
else if (argc <= 50)
{
/* Get interface name */
if (strlen(argv[1]) < sizeof(ifName)) {
strcpy (ifName, argv[1]);
} else{
ONEBOX_PRINT("length of given interface name is more than the buffer size\n");
return -1;
}
cmdNo = sniffer_getcmdnumber (argv[2]);
//printf("cmd is %d \n",cmdNo);
}
/* Creating a Socket */
sockfd = socket(PF_INET, SOCK_DGRAM, 0);
if(sockfd < 0)
{
printf("Unable to create a socket\n");
return sockfd;
}
switch (cmdNo)
{
case SNIFFER_MODE: //to use in sniffer mode
{
if(argc != 5)
{
printf("Invalid number of arguments \n");
sniffer_usage(argv[0]);
return;
}
freq = atoi(argv[3]);
ch_width = atoi(argv[4]);
if(channel_width_validation(ch_width))
{
printf("Invalid Channel BW values \n");
return;
}
if(freq_validation(freq,ch_width))
{
printf("Invalid Channel issued by user\n");
return;
}
per_stats *sta_info = malloc(sizeof(per_stats));
memset(&iwr, 0, sizeof(iwr));
iwr.u.data.flags = (unsigned short)PER_RECEIVE;
/*Indicates that it is receive*/
strncpy (iwr.ifr_name, ifName, IFNAMSIZ);
iwr.u.data.pointer = sta_info;
iwr.u.data.flags |= (unsigned short)freq << 8;
*(unsigned short *)iwr.u.data.pointer = (unsigned short)ch_width;
if(ioctl(sockfd, ONEBOX_HOST_IOCTL, &iwr) < 0)
{
printf("Unable to issue ioctl\n");
return -1;
}
break;
}
case CH_UTILIZATION: //to use for channel utilization
{
if(argc != 5)
{
printf("Invalid number of arguments \n");
sniffer_usage(argv[0]);
return;
}
rssi_threshold = atoi(argv[3]);
if(rssi_threshold < 20 || rssi_threshold > 90)
{
printf("Invalid Rssi Threshold should be 20 to 90 \n");
return;
}
start_bit = atoi(argv[4]);
if(start_bit != 0 && start_bit != 1)
{
printf("Invalid (1 - start)/(0 - stop bit) \n");
return;
}
struct channel_util ch_ut;
while(1)
{
struct channel_util *ch_ut_ptr;
ch_ut_ptr=malloc(sizeof(struct channel_util));
sleep(1);
memset(&iwr, 0, sizeof(iwr));
/*Indicates that it is channel utilization start of stop*/
if(start_bit == 1)
{
if(first_time == 0)
{
ch_ut.rssi_threshold = rssi_threshold;
ch_ut.start_flag = start_bit;
ch_ut.start_time = 0;
ch_ut.stop_time = 0;
ch_ut.on_air_occupancy = 0;
ch_ut.num_of_pkt = 0;
ch_ut.tot_len_of_pkt = 0;
ch_ut.tot_time = 0;
iwr.u.data.pointer = (unsigned char *)&ch_ut;
first_time++;
iwr.u.data.flags = (unsigned short)CH_UTIL_START;
strncpy (iwr.ifr_name, ifName, IFNAMSIZ);
iwr.u.data.length = sizeof(struct channel_util);
//printf("Initail start\n");
if(ioctl(sockfd, ONEBOX_HOST_IOCTL, &iwr) < 0)
{
printf("Unable to issue ioctl\n");
free(ch_ut_ptr);
perror("ioctl:");
return -1;
}
sleep(1);
}
else
{
iwr.u.data.pointer = ch_ut_ptr;
}
iwr.u.data.flags = (unsigned short)CH_UTIL_START;
}
else
{
iwr.u.data.flags = (unsigned short)CH_UTIL_STOP;
iwr.u.data.pointer = ch_ut_ptr;
}
strncpy (iwr.ifr_name, ifName, IFNAMSIZ);
iwr.u.data.length = sizeof(struct channel_util);
if(ioctl(sockfd, ONEBOX_HOST_IOCTL, &iwr) < 0)
{
printf("Unable to issue ioctl\n");
free(ch_ut_ptr);
perror("ioctl:");
return -1;
}
if(start_bit == 1)
{
if((count % 20) == 0)
{
printf(" PKT_RCVD\t");
printf(" CRC_PKT_RCVD\t");
printf(" OCCUPANCY(usecs/sec)\t");
printf(" TOTAL_BYTES(B/S)\t");
printf(" UTILIZATION_RSSI(%/sec)\t");
printf(" TOT_UTILIZATION(%/sec)\n");
}
if(count != 0 && count != 1)
{
tot_time = (double)(ch_ut_ptr->tot_time);
on_air_occupancy = (double)((ch_ut_ptr->tot_len_of_pkt*8)/3000);
tot_on_air_occupancy = (double)((ch_ut_ptr->tot_length_of_pkt*8)/3000);
printf(" %8lu \t",ch_ut_ptr->num_of_pkt);
printf(" %8lu \t",ch_ut_ptr->crc_pkt);
printf(" %12lu \t",ch_ut_ptr->on_air_occupancy);
printf(" %17lu \t",ch_ut_ptr->tot_len_of_pkt);
printf(" %20.3f %%\t",(on_air_occupancy / tot_time ));
printf(" %25.3f %%\n",(tot_on_air_occupancy / tot_time ));
}
}
else
{
free(ch_ut_ptr);
break;
}
free(ch_ut_ptr);
count++;
}
break;
}
default:
printf("Invalid Command\n");
break;
}
close(sockfd);
return 0;
}
<file_sep>/wlan/net80211/linux/osd_linux/include/cfg80211_ioctl.h
#ifndef __CFG80211_IOCTL_H
#define __CFG80211_IOCTL_H
#define ONEBOX_STATUS_FAILURE -1
#define ONEBOX_STATUS_SUCCESS 0
#define IFM_OMASK 0x0000ff00 /* Type specific options */
#define IFM_MMASK 0x00070000 /* Mode */
struct ieee80211vap;
size_t os_nl_strlcpy(char *dest, const char *src, size_t siz);
void nl80211_mem_alloc(void **ptr, unsigned short len, unsigned short flags);
void* nl80211_memcp(void *to, const void *from, int len);
void* nl80211_memcpy(void *to, const void *from, int len);
int scan_results_sup(struct wireless_dev *wdev, unsigned char ssid[6], int val,
int cap_info, struct ieee80211_channel *channel,
int signal, uint8_t *binfo, int binfo_len, uint8_t *network_ssid);
int scan_done(void *temp_scan_req);
struct ieee80211_key_params
{
uint8_t *key;
uint8_t *seq;
int key_len;
int seq_len;
uint32_t cipher;
};
#define IEEE80211_MAX_SSID_LEN 32
struct ieee80211_ssid
{
uint8_t ssid[IEEE80211_MAX_SSID_LEN];
uint8_t ssid_len;
};
/* cipher suite selectors */
#define WLAN_CIPHER_SUITE_USE_GROUP 0x000FAC00
#define WLAN_CIPHER_SUITE_WEP40 0x000FAC01
#define WLAN_CIPHER_SUITE_TKIP 0x000FAC02
/* reserved: 0x000FAC03 */
#define WLAN_CIPHER_SUITE_CCMP 0x000FAC04
#define WLAN_CIPHER_SUITE_WEP104 0x000FAC05
#define WLAN_CIPHER_SUITE_AES_CMAC 0x000FAC06
#define WPA_PROTO_WPA BIT(0)
#define WPA_PROTO_RSN BIT(1)
#define WPA_AUTH_ALG_OPEN BIT(0)
#define WPA_AUTH_ALG_SHARED BIT(1)
#define WPA_AUTH_ALG_LEAP BIT(2)
#define WPA_AUTH_ALG_FT BIT(3)
enum wpa_alg {
WPA_ALG_NONE,
WPA_ALG_WEP,
WPA_ALG_TKIP,
WPA_ALG_CCMP,
WPA_ALG_IGTK,
WPA_ALG_PMK
};
typedef struct
{
unsigned short timestamp[4];
unsigned short beacon_intvl;
unsigned short capability;
unsigned char variable[0];
}__attribute__ ((packed)) BEACON_PROBE_FORMAT;
#if 0
struct ieee80211_ies1 {
/* the following are either NULL or point within data */
uint8_t *wpa_ie; /* captured WPA ie */
uint8_t *rsn_ie; /* captured RSN ie */
uint8_t *wme_ie; /* captured WME ie */
uint8_t *ath_ie; /* captured Atheros ie */
uint8_t *htcap_ie; /* captured HTCAP ie */
uint8_t *htinfo_ie; /* captured HTINFO ie */
uint8_t *tdma_ie; /* captured TDMA ie */
uint8_t *meshid_ie; /* captured MESH ID ie */
uint8_t *spare[4];
/* NB: these must be the last members of this structure */
uint8_t *data; /* frame data > 802.11 header */
int len; /* data size in bytes */
};
struct nl80211_ieee80211_scan_entry {
uint8_t se_macaddr[6];
uint8_t se_bssid[6];
/* XXX can point inside se_ies */
uint8_t se_ssid[2+32];
uint8_t se_rates[2+15];
uint8_t se_xrates[2+15];
union {
uint8_t data[8];
u_int64_t tsf;
} se_tstamp; /* from last rcv'd beacon */
uint16_t se_intval; /* beacon interval (host byte order) */
uint16_t se_capinfo; /* capabilities (host byte order) */
struct ieee80211_channel *se_chan;/* channel where sta found */
uint16_t se_timoff; /* byte offset to TIM ie */
uint16_t se_fhdwell; /* FH only (host byte order) */
uint8_t se_fhindex; /* FH only */
uint8_t se_dtimperiod; /* DTIM period */
uint16_t se_erp; /* ERP from beacon/probe resp */
int8_t se_rssi; /* avg'd recv ssi */
int8_t se_noise; /* noise floor */
uint8_t se_cc[2]; /* captured country code */
uint8_t se_meshid[2+32];
struct ieee80211_ies1 se_ies; /* captured ie's */
u_int se_age; /* age of entry (0 on create) */
};
#endif
uint8_t cfg80211_wrapper_attach(struct net_device *dev,void *ptr, int size);
void cfg80211_wrapper_free_wdev(struct wireless_dev *wdev);
int onebox_prepare_ioctl_cmd(struct ieee80211vap *vap, uint8_t type, const void *data, int val, int len );
uint8_t onebox_delete_key(struct net_device *ndev, const uint8_t *mac_addr, uint8_t index);
uint8_t onebox_add_key(struct net_device *ndev, uint8_t index,
const uint8_t *mac_addr,struct ieee80211_key_params *params );
uint8_t onebox_wep_key(struct net_device *ndev, int index, uint8_t *mac_addr, uint8_t key_len, const uint8_t *key);
uint8_t onebox_siwrts(struct iw_param *rts);
uint8_t onebox_siwfrag(struct iw_param *frag);
uint8_t tx_power(int dbm);
int onebox_set_if_media(struct net_device *dev, int media);
int onebox_get_if_media(struct net_device *dev);
int onebox_set_mediaopt(struct net_device *dev, uint32_t mask, uint32_t mode);
int onebox_driver_nl80211_set_wpa(struct ieee80211vap *vap, int enabled);
int onebox_driver_nl80211_set_wpa_internal(struct ieee80211vap *vap, int wpa, int privacy);
int nl80211_ctrl_iface(struct net_device *ndev, int enable);
int cfg80211_connect_res(struct net_device *ndev, int auth, const uint8_t *ie, size_t ie_len, unsigned char *ssid,
size_t ssid_len, unsigned char *bssid, int len, int privacy);
int cfg80211_inform_scan_results(void *arg, void *se_nl);
int cfg80211_disconnect(struct net_device *ndev, int reason_code);
int cfg80211_connect_result_vap(struct ieee80211vap *vap, uint8_t mac[6]);
int connection_confirm(struct wireless_dev *wdev, uint8_t mac[6]);
int cfg80211_disconnect_result_vap(struct ieee80211vap *vap);
int disconnection_confirm(struct wireless_dev *wdev);
#endif
<file_sep>/bt/osi_bt/onebox_bt_osi_callbacks.c
#include "onebox_core.h"
#include "onebox_pktpro.h"
static struct onebox_osi_bt_ops osi_bt_ops = {
.onebox_core_init = core_bt_init,
.onebox_core_deinit = core_bt_deinit,
.onebox_indicate_pkt_to_core = bt_core_pkt_recv,
.onebox_dump = onebox_print_dump,
.onebox_bt_xmit = bt_xmit,
.onebox_snd_cmd_pkt = onebox_bt_mgmt_pkt_recv,
.onebox_send_pkt = send_bt_pkt,
};
struct onebox_osi_bt_ops *onebox_get_osi_bt_ops(void)
{
return &osi_bt_ops;
}
EXPORT_SYMBOL(onebox_get_osi_bt_ops);
<file_sep>/bt/include/linux/onebox_bt_ops.h
/**
* @file onebox_hal_ops.h
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contians the function prototypes of the callbacks used across
* differnet layers in the driver
*
*/
#include "onebox_common.h"
#include "onebox_linux.h"
#ifdef USE_USB_INTF
#include <linux/usb.h>
#endif
struct onebox_osi_bt_ops {
int32 (*onebox_core_init)(PONEBOX_ADAPTER adapter);
int32 (*onebox_core_deinit)(PONEBOX_ADAPTER adapter);
int32 (*onebox_indicate_pkt_to_core)(PONEBOX_ADAPTER adapter,
netbuf_ctrl_block_t *netbuf_cb);
void (*onebox_dump)(int32 dbg_zone_l, PUCHAR msg_to_print_p,int32 len);
int32 (*onebox_bt_xmit) (PONEBOX_ADAPTER adapter,
netbuf_ctrl_block_t *netbuf_cb);
int32 (*onebox_snd_cmd_pkt)(PONEBOX_ADAPTER adapter,
netbuf_ctrl_block_t *netbuf_cb);
int32 (*onebox_send_pkt)(PONEBOX_ADAPTER adapter,
netbuf_ctrl_block_t *netbuf_cb);
};
struct onebox_bt_osd_operations
{
int32 (*onebox_btstack_init)(PONEBOX_ADAPTER adapter);
int32 (*onebox_btstack_deinit)(PONEBOX_ADAPTER adapter);
int32 (*onebox_send_pkt_to_btstack)(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb);
};
/* EOF */
<file_sep>/common_hal/osi/onebox_usb_devops.c
/**
*
* @file onebox_dev_ops.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* The file contains the initialization part of the SDBus driver and Loading of the
* TA firmware.
*/
/* include files */
#include "onebox_common.h"
#include "onebox_hal.h"
#include "onebox_linux.h"
#include "onebox_pktpro.h"
#include <linux/usb.h>
#if 0
ONEBOX_EXTERN uint8 process_usb_rcv_pkt(PONEBOX_ADAPTER adapter, uint32 pkt_len, uint8 pkt_type);
#endif
ONEBOX_EXTERN uint8 deploy_packet_to_assets(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *nb_deploy);
ONEBOX_EXTERN uint8 process_unaggregated_pkt(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *nb_deploy, int32 total_len);
ONEBOX_STATUS load_data_master_write(PONEBOX_ADAPTER adapter, uint32 base_address, uint32 instructions_sz,
uint32 block_size, uint8 *ta_firmware)
{
uint32 num_blocks;
uint16 msb_address;
uint32 cur_indx , ii;
uint8 temp_buf[256];
num_blocks = instructions_sz / block_size;
msb_address = base_address >> 16;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("num_blocks: %d\n"),num_blocks));
for (cur_indx = 0,ii = 0; ii < num_blocks; ii++,cur_indx += block_size)
{
adapter->os_intf_ops->onebox_memset(temp_buf, 0, block_size);
adapter->os_intf_ops->onebox_memcpy(temp_buf, ta_firmware + cur_indx, block_size);
if (adapter->osd_host_intf_ops->onebox_ta_write_multiple(adapter,
base_address,
(uint8 *)(temp_buf),
block_size)
!=ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("%s: loading block: %d\n"), __func__,ii));
base_address += block_size;
}
if (instructions_sz % block_size)
{
adapter->os_intf_ops->onebox_memset(temp_buf, 0, block_size);
adapter->os_intf_ops->onebox_memcpy(temp_buf,
ta_firmware + cur_indx,
instructions_sz % block_size);
if (adapter->osd_host_intf_ops->onebox_ta_write_multiple(adapter,
base_address,
(uint8 *)(temp_buf),
instructions_sz % block_size
)!=ONEBOX_STATUS_SUCCESS)
{
return ONEBOX_STATUS_FAILURE;
}
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("*Written Last Block in Address 0x%x Successfully**\n"),
cur_indx | SD_REQUEST_MASTER));
}
return ONEBOX_STATUS_SUCCESS;
}
void interrupt_handler(PONEBOX_ADAPTER adapter)
{
/*Dummy for USB*/
return;
}
int32 ta_reset_ops(PONEBOX_ADAPTER adapter)
{
/*Dummy for USB*/
return ONEBOX_STATUS_SUCCESS;
}
/**
* This is a kernel thread to receive the packets from the device
*
* @param
* data Pointer to driver's private data
* @return
* None
*/
void usb_rx_scheduler_thread(void *data)
{
PONEBOX_ADAPTER adapter = (PONEBOX_ADAPTER)data;
#if 0
uint16 polling_flag = 0;
uint32 rcv_len = 0;
uint8 pkt_type = 0;
uint8 ep_num = 0;
uint32 pipe = 0;
struct urb *urb;
struct usb_host_endpoint *hep;
#else
netbuf_ctrl_block_t *netbuf_cb = NULL;
uint8 s = ONEBOX_STATUS_SUCCESS;
#endif
FUNCTION_ENTRY(ONEBOX_ZONE_DEBUG);
do
{
adapter->os_intf_ops->onebox_wait_event(&adapter->usb_rx_scheduler_event, EVENT_WAIT_FOREVER);
adapter->os_intf_ops->onebox_reset_event(&adapter->usb_rx_scheduler_event);
if(adapter->usb_rx_thread_exit)
{
goto data_fail;
}
while (adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->deferred_rx_queue)) {
netbuf_cb = adapter->os_intf_ops->onebox_dequeue_pkt(&adapter->deferred_rx_queue);
if (!netbuf_cb) {
printk("HAL : Invalid netbuf_cb from deferred_rx_queue \n");
break;
}
s = deploy_packet_to_assets(adapter, netbuf_cb);
if (s) {
printk("FAILED TO DEPLOY packet[%p]\n", netbuf_cb);
continue;
}
}
}while(adapter->os_intf_ops->onebox_atomic_read(&adapter->rxThreadDone) == 0);//FIXME: why not thread_exit
data_fail:
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: Terminated thread"
"Data Pkt\n"), __func__));
complete_and_exit(&adapter->rxThreadComplete, 0);
return ;
}
uint8 process_usb_rcv_pkt(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_recv_pkt, uint8 pkt_type)
{
if (ZIGB_PKT == pkt_type) {
#ifndef USE_INTCONTEXT
adapter->os_intf_ops->onebox_netbuf_queue_tail(&adapter->deferred_rx_queue,
netbuf_recv_pkt->pkt_addr);
adapter->os_intf_ops->onebox_set_event(&adapter->usb_rx_scheduler_event);
#else
ONEBOX_STATUS status = ONEBOX_STATUS_SUCCESS;
status = deploy_packet_to_assets(adapter, netbuf_recv_pkt);
if (status) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("FAILED TO DEPLOY part of aggr packet[%p]\n"), netbuf_recv_pkt));
return ONEBOX_STATUS_FAILURE;
}
return ONEBOX_STATUS_SUCCESS;
#endif
}
else {
/* Handling unaggregated packets(As No aggregation in USB), in BT/WLAN protocols */
process_unaggregated_pkt(adapter, netbuf_recv_pkt, netbuf_recv_pkt->len);
}
FUNCTION_EXIT(ONEBOX_ZONE_INFO);
return ONEBOX_STATUS_SUCCESS;
}
EXPORT_SYMBOL(process_usb_rcv_pkt);
<file_sep>/common_hal/osi/onebox_common_dev_config_params.c
/**
* @file onebox_common_pwr_sve_cfg_params.c
* @author <NAME>
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* The file contains the user configurable values that are required by the power
* save module in the firmware.
*/
/* include files */
#include "onebox_common.h"
#include "onebox_linux.h"
#include "onebox_mgmt.h"
/* The following structure is used to configure values */
struct rsi_config_vals_s dev_config_vals[] = {
{.lp_sleep_handshake = 0,
.ulp_sleep_handshake = 0,
.sleep_config_params = 0,
.host_wakeup_intr_enable = 0,
.host_wakeup_intr_active_high = 0,
.ext_pa_or_bt_coex_en = 0,
//.lp_wakeup_threshold = 0,
//.ulp_wakeup_threshold = 5000
},
};
rsi_ulp_gpio_vals unused_ulp_gpio_bitmap = {
.Motion_sensor_GPIO_ULP_Wakeup = UNUSED_GPIO,
.Sleep_indication_from_device = UNUSED_GPIO,
.ULP_GPIO_2 = UNUSED_GPIO,
.Push_Button_ULP_Wakeup = UNUSED_GPIO,
};
rsi_soc_gpio unused_soc_gpio_bitmap = {
.PSPI_CSN_0 = USED_GPIO, //GPIO_0
.PSPI_CSN_1 = USED_GPIO, //GPIO_1
.host_wakeup_intr = UNUSED_GPIO, //GPIO_2 Enable this if host_intr_wakeup is enabled.
.PSPI_DATA_0 = USED_GPIO, //GPIO_3
.PSPI_DATA_1 = USED_GPIO, //GPIO_4
.PSPI_DATA_2 = USED_GPIO, //GPIO_5
.PSPI_DATA_3 = USED_GPIO, //GPIO_6
.I2C_SCL = USED_GPIO, //GPIO_7
.I2C_SDA = USED_GPIO, //GPIO_8
.UART1_RX = UNUSED_GPIO, //GPIO_9
.UART1_TX = UNUSED_GPIO, //GPIO_10
.UART1_RTS_I2S_CLK = UNUSED_GPIO, //GPIO_11
.UART1_CTS_I2S_WS = UNUSED_GPIO, //GPIO_12
.Debug_UART_RX_I2S_DIN = UNUSED_GPIO, //GPIO_13 Disable able this if uart debug is required.
.Debug_UART_TX_I2S_DOUT = UNUSED_GPIO, //GPIO_14 Disable this if uart debug is required.
.LP_Wakeup_Boot_Bypass = UNUSED_GPIO, //GPIO_15
.LED_0 = USED_GPIO, //GPIO_16 Disable this if Led glow is required during TX/RX.
.BT_Coexistance_WLAN_ACTIVE_EXT_PA_ANT_SEL_A = UNUSED_GPIO, //GPIO_17 Disable this for BT_WIFI COEX
.BT_Coexistance_BT_PRIORITY_EXT_PA_ANT_SEL_B = UNUSED_GPIO, //GPIO_18 Disable this for BT_WIFI COEX
.BT_Coexistance_BT_ACTIVE_EXT_PA_ON_OFF = UNUSED_GPIO, //GPIO_19 Disable this for EXT_PA
.RF_reset = USED_GPIO, //GPIO_20 This should be always used.
.Sleep_indication_from_device = UNUSED_GPIO, //GPIO_21 For GPIO handhsake this should be used
};
/**
* configure_common_dev_params() - This function is used to send a frame to the
* firmware to configure some device parameters.
* The params are picked from the struct above.
*
* @adapter: The common driver structure in the wlan module.
*
* Return: ONEBOX_STATUS_SUCCESS on successful writing of frame, else
* ONEBOX_STATUS_FAILURE
*/
ONEBOX_STATUS onebox_configure_common_dev_params(PONEBOX_ADAPTER adapter)
{
#if 1
onebox_mac_frame_t *mgmt_frame;
netbuf_ctrl_block_t *netbuf_cb = NULL;
ONEBOX_STATUS status = ONEBOX_STATUS_SUCCESS;
uint16 *frame_body;
uint32 *unused_soc_gpio ;
uint16 *unused_ulp_gpio ;
netbuf_cb = adapter->os_intf_ops->onebox_alloc_skb(FRAME_DESC_SZ + sizeof(rsi_config_vals));
if(netbuf_cb == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: Unable to allocate skb\n"), __func__));
return ONEBOX_STATUS_FAILURE;
}
adapter->os_intf_ops->onebox_add_data_to_skb(netbuf_cb, (FRAME_DESC_SZ + sizeof(rsi_config_vals)));
mgmt_frame = (onebox_mac_frame_t *)&netbuf_cb->data[0];
frame_body = (uint16 *)&netbuf_cb->data[16];
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, (FRAME_DESC_SZ + sizeof(rsi_config_vals)));
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(sizeof(rsi_config_vals) | COEX_TX_Q << 12);
netbuf_cb->tx_pkt_type = COEX_Q;
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(COMMON_DEV_CONFIG);
if (d_assets.lp_ps_handshake_mode == PACKET_HAND_SHAKE) {
printk("Ivalid Configuration of PACKET_HAND_SHAKE in LP_MODE\n");
return ONEBOX_STATUS_FAILURE;
}
frame_body[0] = (uint16 )d_assets.lp_ps_handshake_mode;
frame_body[0] |= (uint16 )d_assets.ulp_ps_handshake_mode << 8;
if (d_assets.rf_power_val == RF_POWER_1_9) {
frame_body[1] = BIT(1);
}
if(dev_config_vals[0].host_wakeup_intr_enable) {
unused_soc_gpio_bitmap.host_wakeup_intr = USED_GPIO;
//frame_body[1] |= (((uint16 )(dev_config_vals[0].host_wakeup_intr_enable)) << 8);
frame_body[1] |= BIT(2); //HOST_WAKEUP_INTR_EN
if(dev_config_vals[0].host_wakeup_intr_active_high)
{
frame_body[1] |= BIT(3); //HOST_WAKEUP_INTR_ACTIVE_HIGH
}
}
unused_ulp_gpio = (uint16 *)&unused_ulp_gpio_bitmap;
//frame_body[1] |= ((uint16)unused_ulp_gpio_bitmap << 8 );
frame_body[1] |= ((*unused_ulp_gpio) << 8);
if ((d_assets.lp_ps_handshake_mode == GPIO_HAND_SHAKE) ||
(d_assets.ulp_ps_handshake_mode == GPIO_HAND_SHAKE)) {
if ((d_assets.lp_ps_handshake_mode == GPIO_HAND_SHAKE)) {
unused_soc_gpio_bitmap.LP_Wakeup_Boot_Bypass = USED_GPIO;
}
if ((d_assets.ulp_ps_handshake_mode == GPIO_HAND_SHAKE)) {
unused_ulp_gpio_bitmap.Motion_sensor_GPIO_ULP_Wakeup = USED_GPIO;
}
if ((d_assets.device_gpio_type == TA_GPIO)) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s : Line %d Invalid Configuration OF ULP_PS_HANDHSAKE_MODE Enabling Sleep_Indication_from_device GPIO \n"),
__func__, __LINE__));
unused_soc_gpio_bitmap.Sleep_indication_from_device = USED_GPIO;
} else {
unused_ulp_gpio_bitmap.Sleep_indication_from_device = USED_GPIO;
frame_body[1] |= BIT(0); //ULP_GPIO for Handshake
}
}
if(dev_config_vals[0].ext_pa_or_bt_coex_en ) {
frame_body[4] = (uint16 )dev_config_vals[0].ext_pa_or_bt_coex_en;
unused_soc_gpio_bitmap.BT_Coexistance_WLAN_ACTIVE_EXT_PA_ANT_SEL_A = USED_GPIO;
unused_soc_gpio_bitmap.BT_Coexistance_BT_PRIORITY_EXT_PA_ANT_SEL_B = USED_GPIO;
unused_soc_gpio_bitmap.BT_Coexistance_BT_ACTIVE_EXT_PA_ON_OFF = USED_GPIO;
}
unused_soc_gpio = (uint32 *)&unused_soc_gpio_bitmap;
*(uint32 *)&frame_body[2] = *unused_soc_gpio;
adapter->coex_osi_ops->onebox_dump(ONEBOX_ZONE_ERROR,
(uint8 *)mgmt_frame,
FRAME_DESC_SZ + sizeof(rsi_config_vals)) ;
status = adapter->osi_host_intf_ops->onebox_host_intf_write_pkt(adapter,
&netbuf_cb->data[0],
netbuf_cb->len,
netbuf_cb->tx_pkt_type);
if (status != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT
("%s: Failed To Write The Packet\n"),__func__));
}
adapter->tot_pkts_sentout[COEX_Q]++;
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
return status;
#else
onebox_mac_frame_t *mgmt_frame;
netbuf_ctrl_block_t *netbuf_cb = NULL;
ONEBOX_STATUS status = ONEBOX_STATUS_SUCCESS;
//rsi_soc_gpio unused_soc_gpio = unused_soc_gpio_bitmap;
FUNCTION_ENTRY (ONEBOX_ZONE_MGMT_SEND);
if (d_assets.lp_ps_handshake_mode == PACKET_HAND_SHAKE) {
printk("Ivalid Configuration of PACKET_HAND_SHAKE in LP_MODE\n");
return ONEBOX_STATUS_FAILURE;
}
dev_config_vals[0].lp_sleep_handshake = d_assets.lp_ps_handshake_mode;
dev_config_vals[0].ulp_sleep_handshake = d_assets.ulp_ps_handshake_mode;
if ((d_assets.lp_ps_handshake_mode == GPIO_HAND_SHAKE) ||
(d_assets.ulp_ps_handshake_mode == GPIO_HAND_SHAKE)) {
unused_ulp_gpio_bitmap.Motion_sensor_GPIO_ULP_Wakeup = USED_GPIO;
unused_soc_gpio_bitmap.LP_Wakeup_Boot_Bypass = USED_GPIO;
if ((d_assets.device_gpio_type == TA_GPIO)) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s : Line %d Invalid Configuration OF ULP_PS_HANDHSAKE_MODE Enabling Sleep_Indication_from_device GPIO \n"),
__func__, __LINE__));
unused_soc_gpio_bitmap.Sleep_indication_from_device = USED_GPIO;
} else {
unused_ulp_gpio_bitmap.Sleep_indication_from_device = USED_GPIO;
}
}
if(dev_config_vals[0].host_wakeup_intr_enable){
unused_soc_gpio_bitmap.host_wakeup_intr = USED_GPIO;
}
if(dev_config_vals[0].ext_pa_or_bt_coex_en ) {
unused_soc_gpio_bitmap.BT_Coexistance_WLAN_ACTIVE_EXT_PA_ANT_SEL_A = USED_GPIO;
unused_soc_gpio_bitmap.BT_Coexistance_BT_PRIORITY_EXT_PA_ANT_SEL_B = USED_GPIO;
unused_soc_gpio_bitmap.BT_Coexistance_BT_ACTIVE_EXT_PA_ON_OFF = USED_GPIO;
}
if (d_assets.device_gpio_type == ULP_GPIO)
dev_config_vals[0].sleep_config_params |= BIT(0);
if (d_assets.rf_power_val == RF_POWER_1_9)
dev_config_vals[0].sleep_config_params |= BIT(1);
netbuf_cb = adapter->os_intf_ops->onebox_alloc_skb(FRAME_DESC_SZ + sizeof(rsi_config_vals));
if(netbuf_cb == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("%s: Unable to allocate skb\n"), __func__));
return ONEBOX_STATUS_FAILURE;
}
adapter->os_intf_ops->onebox_add_data_to_skb(netbuf_cb, (FRAME_DESC_SZ + sizeof(rsi_config_vals)));
mgmt_frame = (onebox_mac_frame_t *)&netbuf_cb->data[0];
adapter->os_intf_ops->onebox_memset(mgmt_frame, 0, (FRAME_DESC_SZ + sizeof(rsi_config_vals)));
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("In %s line %d \n"), __func__, __LINE__));
mgmt_frame->desc_word[0] = ONEBOX_CPU_TO_LE16(sizeof(rsi_config_vals) | COEX_TX_Q << 12);
netbuf_cb->tx_pkt_type = COEX_Q;
mgmt_frame->desc_word[1] = ONEBOX_CPU_TO_LE16(COMMON_DEV_CONFIG);
dev_config_vals[0].unused_soc_gpio_bitmap = unused_soc_gpio_bitmap;
dev_config_vals[0].unused_ulp_gpio_bitmap = unused_ulp_gpio_bitmap;
adapter->os_intf_ops->onebox_memcpy(&mgmt_frame->u.dev_config_vals, &dev_config_vals, sizeof(rsi_config_vals));
adapter->coex_osi_ops->onebox_dump(ONEBOX_ZONE_ERROR,
(uint8 *)mgmt_frame,
FRAME_DESC_SZ + sizeof(rsi_config_vals)) ;
status = adapter->osi_host_intf_ops->onebox_host_intf_write_pkt(adapter,
&netbuf_cb->data[0],
netbuf_cb->len,
netbuf_cb->tx_pkt_type);
if (status != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT
("%s: Failed To Write The Packet\n"),__func__));
}
adapter->tot_pkts_sentout[COEX_Q]++;
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
return status;
#endif
}
EXPORT_SYMBOL(onebox_configure_common_dev_params);
<file_sep>/utils/Makefile
#/**
# * @file Makefile
# * @author
# * @version 1.0
# *
# * @section LICENSE
# *
# * This software embodies materials and concepts that are confidential to Redpine
# * Signals and is made available solely pursuant to the terms of a written license
# * agreement with Redpine Signals
# *
# * @section DESCRIPTION
# *
# * This is the Utils Makefile used for generating the onebox utility. This utility is used for
# * creating the Virtual access point(VAP), deleting the VAP, setting wmm params etc
# */
#CC=$(CROSS_COMPILE)cc
cpy=cp
include $(PWD)/.config
include $(PWD)/config/make.config
#EXTRA_CFLAGS += -DENABLE_PER_MODE
EXTRA_CFLAGS += -MMD -O2 -Wall -g
OBJS =onebox_util.o
all: onebox_util copy
onebox_util: $(OBJS)
$(CC) -o onebox_util $(OBJS)
copy:
$(CC) -o receive receive.c
$(CC) -o transmit transmit.c
$(CC) -o transmit_packet transmit_packet.c
#$(CC) -o nl80211_util nl80211_util.c
$(CC) -o bbp_util matlab_utils.c
$(CC) -o sniffer_app sniffer.c
@echo 'copying to release folder'
$(cpy) onebox_util transmit transmit_packet receive bbp_util sniffer_app ../release/
clean:
rm -f onebox_util onebox_util.d onebox_util.o
rm -rf receive transmit transmit_packet
<file_sep>/release/wlan_insert.sh
sh common_insert.sh
insmod wlan.ko
insmod wlan_wep.ko
insmod wlan_tkip.ko
insmod wlan_ccmp.ko
insmod wlan_acl.ko
insmod wlan_xauth.ko
insmod wlan_scan_sta.ko
insmod onebox_wlan_nongpl.ko
insmod onebox_wlan_gpl.ko
<file_sep>/wlan/hostapd-2.3/src/drivers/ioctl.h
#ifndef __OSD_IOCTL_H__
#define __OSD_IOCTL_H__
struct ieee80211req_getset_appiebuf {
u_int32_t app_frmtype; /* management frame type for which buffer is added */
u_int32_t app_buflen; /* application-supplied buffer length */
u_int8_t app_buf[0]; /* application-supplied IE(s) */
};
#define IW_PRIV_BLOB_LENGTH_ENCODING(_SIZE) \
(((_SIZE) == ((_SIZE) & IW_PRIV_SIZE_MASK)) ? \
(_SIZE) : \
(((_SIZE) / sizeof(uint32_t)) + \
(((_SIZE) == (((_SIZE) / sizeof(uint32_t)) * sizeof(int))) ? \
0 : 1)))
#define IW_PRIV_BLOB_TYPE_ENCODING(_SIZE) \
(((_SIZE) == ((_SIZE) & IW_PRIV_SIZE_MASK)) ? \
(IW_PRIV_TYPE_BYTE | (_SIZE)) : \
(IW_PRIV_TYPE_INT | IW_PRIV_BLOB_LENGTH_ENCODING((_SIZE))))
struct ieee80211req_set_filter {
u_int32_t app_filterype; /* management frame filter type */
};
#define SIOCGDRVSPEC -122
#define SIOCSDRVSPEC -123
#define SIOCGPRIVATE_0 -124
#define IEEE80211_APPIE_MAX 1024
#define IW_PRIV_TYPE_OPTIE \
IW_PRIV_BLOB_TYPE_ENCODING(IEEE80211_MAX_OPT_IE)
#define IW_PRIV_TYPE_KEY \
IW_PRIV_BLOB_TYPE_ENCODING(sizeof(struct ieee80211req_key))
#define IW_PRIV_TYPE_DELKEY \
IW_PRIV_BLOB_TYPE_ENCODING(sizeof(struct ieee80211req_del_key))
#define IW_PRIV_TYPE_MLME \
IW_PRIV_BLOB_TYPE_ENCODING(sizeof(struct ieee80211req_mlme))
#define IW_PRIV_TYPE_CHANLIST \
IW_PRIV_BLOB_TYPE_ENCODING(sizeof(struct ieee80211req_chanlist))
#define IW_PRIV_TYPE_CHANINFO \
IW_PRIV_BLOB_TYPE_ENCODING(sizeof(struct ieee80211req_chaninfo))
#define IW_PRIV_TYPE_APPIEBUF \
IW_PRIV_BLOB_TYPE_ENCODING(sizeof(struct ieee80211req_getset_appiebuf) + IEEE80211_APPIE_MAX)
#define IW_PRIV_TYPE_FILTER \
IW_PRIV_BLOB_TYPE_ENCODING(sizeof(struct ieee80211req_set_filter))
#define IEEE80211_IOCTL_SETPARAM (SIOCIWFIRSTPRIV+0)
#define IEEE80211_IOCTL_GETPARAM (SIOCIWFIRSTPRIV+1)
#define IEEE80211_IOCTL_SETMODE (SIOCIWFIRSTPRIV+2)
#define IEEE80211_IOCTL_GETMODE (SIOCIWFIRSTPRIV+3)
#define IEEE80211_IOCTL_SETWMMPARAMS (SIOCIWFIRSTPRIV+4)
#define IEEE80211_IOCTL_GETWMMPARAMS (SIOCIWFIRSTPRIV+5)
#define IEEE80211_IOCTL_SETCHANLIST (SIOCIWFIRSTPRIV+6)
#define IEEE80211_IOCTL_GETCHANLIST (SIOCIWFIRSTPRIV+7)
#define IEEE80211_IOCTL_CHANSWITCH (SIOCIWFIRSTPRIV+8)
#define IEEE80211_IOCTL_GET_APPIEBUF (SIOCIWFIRSTPRIV+9)
#define IEEE80211_IOCTL_SET_APPIEBUF (SIOCIWFIRSTPRIV+10)
#define IEEE80211_IOCTL_FILTERFRAME (SIOCIWFIRSTPRIV+12)
#define IEEE80211_IOCTL_GETCHANINFO (SIOCIWFIRSTPRIV+13)
#define IEEE80211_IOCTL_SETOPTIE (SIOCIWFIRSTPRIV+14)
#define IEEE80211_IOCTL_GETOPTIE (SIOCIWFIRSTPRIV+15)
#define IEEE80211_IOCTL_SETMLME (SIOCIWFIRSTPRIV+16)
#define IEEE80211_IOCTL_RADAR (SIOCIWFIRSTPRIV+21)
#define IEEE80211_IOCTL_SETWMM (SIOCIWFIRSTPRIV+17)
#define IEEE80211_IOCTL_GETWMM (SIOCIWFIRSTPRIV+27)
#define IEEE80211_IOCTL_SETKEY (SIOCIWFIRSTPRIV+18)
#define IEEE80211_IOCTL_DELKEY (SIOCIWFIRSTPRIV+20)
#define IEEE80211_IOCTL_ADDMAC (SIOCIWFIRSTPRIV+22)
#define IEEE80211_IOCTL_DELMAC (SIOCIWFIRSTPRIV+24)
#define IEEE80211_IOCTL_WDSADDMAC (SIOCIWFIRSTPRIV+25)
#define IEEE80211_IOCTL_WDSSETMAC (SIOCIWFIRSTPRIV+26)
#define IEEE80211_IOCTL_KICKMAC (SIOCIWFIRSTPRIV+29)
#define IEEE80211_IOCTL_SETSCANLIST (SIOCIWFIRSTPRIV+31)
#define SIOCG80211 (SIOCIWFIRSTPRIV+11)
#define SIOCS80211 (SIOCIWFIRSTPRIV+28)
#define SIOCSIFMEDIA (SIOCIWFIRSTPRIV+12)
#define SIOCGIFMEDIA (SIOCIWFIRSTPRIV+19)
#define IEEE80211_IOCTL_ENDWMMPARAMS (SIOCIWFIRSTPRIV+30)
enum {
IEEE80211_WMMPARAMS_CWMIN = 1,
IEEE80211_WMMPARAMS_CWMAX = 2,
IEEE80211_WMMPARAMS_AIFS = 3,
IEEE80211_WMMPARAMS_TXOPLIMIT = 4,
IEEE80211_WMMPARAMS_ACM = 5,
IEEE80211_WMMPARAMS_NOACKPOLICY = 6,
};
typedef enum {
IEEE80211_PARAM_TURBO = 1,
IEEE80211_PARAM_MODE = 2,
IEEE80211_PARAM_AUTHMODE = 3,
IEEE80211_PARAM_PROTMODE = 4,
IEEE80211_PARAM_MCASTCIPHER = 5,
IEEE80211_PARAM_MCASTKEYLEN = 6,
IEEE80211_PARAM_UCASTCIPHERS = 7,
IEEE80211_PARAM_UCASTCIPHER = 8,
IEEE80211_PARAM_UCASTKEYLEN = 9,
IEEE80211_PARAM_WPA = 10,
IEEE80211_PARAM_ROAMING = 12,
IEEE80211_PARAM_PRIVACY = 13,
IEEE80211_PARAM_COUNTERMEASURES = 14,
IEEE80211_PARAM_DROPUNENCRYPTED = 15,
IEEE80211_PARAM_DRIVER_CAPS = 16,
IEEE80211_PARAM_MACCMD = 17,
IEEE80211_PARAM_WMM = 18,
IEEE80211_PARAM_HIDESSID = 19,
IEEE80211_PARAM_APBRIDGE = 20,
IEEE80211_PARAM_KEYMGTALGS = 21,
IEEE80211_PARAM_RSNCAPS = 22,
IEEE80211_PARAM_INACT = 23,
IEEE80211_PARAM_INACT_AUTH = 24,
IEEE80211_PARAM_INACT_INIT = 25,
IEEE80211_PARAM_ABOLT = 26,
IEEE80211_PARAM_DTIM_PERIOD = 28,
IEEE80211_PARAM_BEACON_INTERVAL = 29,
IEEE80211_PARAM_DOTH = 30,
IEEE80211_PARAM_PWRTARGET = 31,
IEEE80211_PARAM_GENREASSOC = 32,
IEEE80211_PARAM_COMPRESSION = 33,
IEEE80211_PARAM_FF = 34,
IEEE80211_PARAM_XR = 35,
IEEE80211_PARAM_BURST = 36,
IEEE80211_PARAM_PUREG = 37,
IEEE80211_PARAM_AR = 38,
IEEE80211_PARAM_WDS = 39,
IEEE80211_PARAM_BGSCAN = 40,
IEEE80211_PARAM_BGSCAN_IDLE = 41,
IEEE80211_PARAM_BGSCAN_INTERVAL = 42,
IEEE80211_PARAM_MCAST_RATE = 43,
IEEE80211_PARAM_COVERAGE_CLASS = 44,
IEEE80211_PARAM_COUNTRY_IE = 45,
IEEE80211_PARAM_SCANVALID = 46,
IEEE80211_PARAM_ROAM_RSSI_11A = 47,
IEEE80211_PARAM_ROAM_RSSI_11B = 48,
IEEE80211_PARAM_ROAM_RSSI_11G = 49,
IEEE80211_PARAM_ROAM_RATE_11A = 50,
IEEE80211_PARAM_ROAM_RATE_11B = 51,
IEEE80211_PARAM_ROAM_RATE_11G = 52,
IEEE80211_PARAM_UAPSDINFO = 53,
IEEE80211_PARAM_SLEEP = 54,
IEEE80211_PARAM_QOSNULL = 55,
IEEE80211_PARAM_PSPOLL = 56,
IEEE80211_PARAM_EOSPDROP = 57,
IEEE80211_PARAM_MARKDFS = 58,
IEEE80211_PARAM_REGCLASS = 59,
IEEE80211_PARAM_DROPUNENC_EAPOL = 60,
IEEE80211_PARAM_SHPREAMBLE = 61,
IEEE80211_PARAM_DUMPREGS = 62,
IEEE80211_PARAM_DOTH_ALGORITHM = 63,
IEEE80211_PARAM_DOTH_MINCOM = 64,
IEEE80211_PARAM_DOTH_SLCG = 65,
IEEE80211_PARAM_DOTH_SLDG = 66,
IEEE80211_PARAM_TXCONT = 67,
IEEE80211_PARAM_TXCONT_RATE = 68,
IEEE80211_PARAM_TXCONT_POWER = 69,
IEEE80211_PARAM_DFS_TESTMODE = 70,
IEEE80211_PARAM_DFS_CACTIME = 71,
IEEE80211_PARAM_DFS_EXCLPERIOD = 72,
IEEE80211_PARAM_BEACON_MISS_THRESH = 73,
IEEE80211_PARAM_BEACON_MISS_THRESH_MS = 74,
IEEE80211_PARAM_MAXRATE = 75,
IEEE80211_PARAM_MINRATE = 76,
IEEE80211_PARAM_PROTMODE_RSSI = 77,
IEEE80211_PARAM_PROTMODE_TIMEOUT = 78,
IEEE80211_PARAM_BGSCAN_THRESH = 79,
IEEE80211_PARAM_RSSI_DIS_THR = 80,
IEEE80211_PARAM_RSSI_DIS_COUNT = 81,
IEEE80211_PARAM_WDS_SEP = 82,
IEEE80211_PARAM_MAXASSOC = 83,
IEEE80211_PARAM_PROBEREQ = 84,
IEEE80211_PARAM_CHANGE_COUNTRY_IE = 85,
IEEE80211_PARAM_SHORT_GI = 86,
IEEE80211_PARAM_RIFS = 87,
IEEE80211_PARAM_GREEN_FIELD = 88,
IEEE80211_PARAM_AP_IOSOLATION = 89,
IEEE80211_PARAM_AMPDU = 90,
IEEE80211_PARAM_AMPDU_LIMIT = 91,
IEEE80211_PARAM_AMPDU_DENSITY = 92,
IEEE80211_PARAM_AMSDU = 93,
IEEE80211_PARAM_AMSDU_LIMIT = 94,
IEEE80211_PARAM_SMPS = 95,
IEEE80211_PARAM_HTCONF = 96,
IEEE80211_PARAM_HTPROTMODE = 97,
IEEE80211_PARAM_DOTD = 98,
IEEE80211_PARAM_DFS = 99,
IEEE80211_PARAM_TSN = 100,
IEEE80211_PARAM_WPS = 101,
IEEE80211_PARAM_HTCOMPAT = 102,
IEEE80211_PARAM_PUREN = 103,
IEEE80211_PARAM_TXPOWER = 104,
}enum_list;
#define IS_UP_AUTO(_vap) \
(IFNET_IS_UP_RUNNING((_vap)->iv_ifp) && \
(_vap)->iv_roaming == IEEE80211_ROAMING_AUTO)
#ifndef ifr_media
#define ifr_media ifr_ifru.ifru_ivalue
#endif
#define IFM_IEEE80211_OFDM1_50 10 /* OFDM 1.5Mbps */
#define IFM_IEEE80211_OFDM2_25 11 /* OFDM 2.25Mbps */
#define IFM_IEEE80211_OFDM4_50 13 /* OFDM 4.5Mbps */
#define IFM_IEEE80211_OFDM13_5 17 /* OFDM 13.5Mpbs */
#define IEEE80211_RATE_1M 2
#define IEEE80211_RATE_2M 4
#define IEEE80211_RATE_5_5M 11
#define IEEE80211_RATE_11M 22
#define IEEE80211_RATE_6M 12
#define IEEE80211_RATE_9M 18
#define IEEE80211_RATE_12M 24
#define IEEE80211_RATE_18M 36
#define IEEE80211_RATE_24M 48
#define IEEE80211_RATE_36M 72
#define IEEE80211_RATE_48M 96
#define IEEE80211_RATE_54M 108
#define IEEE80211_RATE_6_5M 13
#define IEEE80211_RATE_13M 26
#define IEEE80211_RATE_19_5M 39
#define IEEE80211_RATE_26M 52
#define IEEE80211_RATE_39M 78
#define IEEE80211_RATE_52M 104
#define IEEE80211_RATE_58_5M 117
#define IEEE80211_RATE_65M 130
#define ONEBOX_RATE_1M 0x00
#define ONEBOX_RATE_2M 0x02
#define ONEBOX_RATE_5_5M 0x04
#define ONEBOX_RATE_11M 0x06
#define ONEBOX_RATE_6M 0x4b
#define ONEBOX_RATE_9M 0x4f
#define ONEBOX_RATE_12M 0x4a
#define ONEBOX_RATE_18M 0x4e
#define ONEBOX_RATE_24M 0x49
#define ONEBOX_RATE_36M 0x4d
#define ONEBOX_RATE_48M 0x48
#define ONEBOX_RATE_54M 0x4c
#define ONEBOX_RATE_MCS0 0x80
#define ONEBOX_RATE_MCS1 0x81
#define ONEBOX_RATE_MCS2 0x82
#define ONEBOX_RATE_MCS3 0x83
#define ONEBOX_RATE_MCS4 0x84
#define ONEBOX_RATE_MCS5 0x85
#define ONEBOX_RATE_MCS6 0x86
#define ONEBOX_RATE_MCS7 0x87
#define IEEE80211_MODE_TURBO_STATIC_A IEEE80211_MODE_MAX
struct ieee80211_channel;
int
check_mode_consistency(const struct ieee80211_channel *c, int mode);
#endif
<file_sep>/wlan/wlan_hal/osi_wlan/devdep/rsi_9113/onebox_reorder.c
#include "onebox_common.h"
#ifdef BYPASS_RX_DATA_PATH
//void onebox_reorder_pkt(PONEBOX_ADAPTER adapter, uint8 *msg)
void onebox_reorder_pkt(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb)
{
uint8 tid = 0, vap_id = 0;
uint8 *msg = netbuf_cb->data;
uint8 pad_bytes = msg[4];
uint16 seqno;
uint8 status;
int32 msg_len;
struct ieee80211com *ic = &adapter->vap_com;
struct ieee80211vap *vap = NULL;
struct ieee80211_node *ni = NULL;
netbuf_ctrl_block_m_t *netbuf_cb_m = NULL;
uint8 qos_pkt = 0, pn_valid = 0;
msg_len = (*(uint16 *)&msg[0] & 0x0fff);
msg_len -= pad_bytes;
vap_id = ((msg[14] & 0xf0) >> 4);
adapter->os_intf_ops->onebox_acquire_sem(&adapter->ic_lock_vap, 0);
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap->hal_priv_vap->vap_id == vap_id)
{
break;
}
}
if(!vap)
{
printk("Vap Id %d \n", vap_id);
printk("Pkt recvd is \n");
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, 32);
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
adapter->os_intf_ops->onebox_release_sem(&adapter->ic_lock_vap);
return;
}
//printk("NETBUF DUMP IN REORDER FUNCTION\n");
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, netbuf_cb->data, netbuf_cb->len);
adapter->os_intf_ops->onebox_netbuf_adj(netbuf_cb, (FRAME_DESC_SZ + pad_bytes));
//printk("NETBUF DUMP AFTER ADJUST\n");
//adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, netbuf_cb->data, netbuf_cb->len);
netbuf_cb_m = onebox_translate_netbuf_to_mbuf(netbuf_cb);
if (netbuf_cb_m == NULL) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Unable to alloc mem %s %d\n"), __func__, __LINE__));
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
adapter->os_intf_ops->onebox_release_sem(&adapter->ic_lock_vap);
return;
}
/*
* We need to fill the packet details which we recieved
* from the descriptor in Device decap mode
*/
if(netbuf_cb->len < 12){
printk("@@Alert: Data Packet less than Ethernet HDR size received\n");
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)netbuf_cb->data, netbuf_cb->len);
}
if(vap->iv_opmode == IEEE80211_M_HOSTAP)
{
ni = adapter->net80211_ops->onebox_find_node(&vap->iv_ic->ic_sta, &netbuf_cb_m->m_data[6] );
}
else
{
ni = adapter->net80211_ops->onebox_find_node(&vap->iv_ic->ic_sta, (uint8 *)&vap->iv_bss->ni_macaddr );
}
if(!ni) {
/* what should I do AS this should not happen for data pkts?????*/
printk("Giving pkt directly to hostap In %s Line %d \n", __func__, __LINE__);
vap->iv_deliver_data(vap, vap->iv_bss, netbuf_cb_m);
adapter->os_intf_ops->onebox_release_sem(&adapter->ic_lock_vap);
return;
}
if((netbuf_cb->data[12] == 0x88) && (netbuf_cb->data[13] == 0x8e)) {
printk("<==== Recvd EAPOL from %02x:%02x:%02x:%02x:%2x:%02x ====>\n", ni->ni_macaddr[0], ni->ni_macaddr[1],
ni->ni_macaddr[2], ni->ni_macaddr[3], ni->ni_macaddr[4], ni->ni_macaddr[5]);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)netbuf_cb->data, netbuf_cb->len);
}
/* Indicates the Packet has been decapsulted*/
netbuf_cb_m->m_flags |= M_DECAP;
#ifdef PWR_SAVE_SUPPORT
if((vap->iv_opmode == IEEE80211_M_STA)
&& (TRAFFIC_PS_EN)
&& (ps_params_def.ps_en)
&& !(netbuf_cb_m->m_data[0] & 0x01)
)
{
vap->check_traffic(vap, 0, netbuf_cb->len);
}
#endif
qos_pkt = (msg[7] & BIT(0));
pn_valid = (msg[7] & BIT(1));
if(!qos_pkt)
{
//printk("Recvd non qos pkt seq no %d tid %d \n", (((*(uint16 *)&msg[5]) >> 4) & 0xfff), (msg[14] & 0x0f));
vap->iv_deliver_data(vap, vap->iv_bss, netbuf_cb_m);
adapter->os_intf_ops->onebox_release_sem(&adapter->ic_lock_vap);
return;
}
tid = (msg[14] & 0x0f);
if(tid > 8)
{
printk("Pkt with unkown tid is \n");
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, 32);
vap->iv_deliver_data(vap, vap->iv_bss, netbuf_cb_m);
adapter->os_intf_ops->onebox_release_sem(&adapter->ic_lock_vap);
return;
}
seqno = (((*(uint16 *)&msg[5]) >> 4) & 0xfff);
netbuf_cb_m->tid = tid;
netbuf_cb_m->aggr_len = seqno;
if(ni->ni_flags & IEEE80211_NODE_HT)
{
if (tid < WME_NUM_TID)
{
if (ni->ni_rx_ampdu[tid].rxa_flags & IEEE80211_AGGR_RUNNING)
{
netbuf_cb_m->m_flags |= M_AMPDU;
}
}
}
status = vap->iv_input(ni, netbuf_cb_m, 0, 0);
adapter->os_intf_ops->onebox_release_sem(&adapter->ic_lock_vap);
return;
}
#endif
<file_sep>/release/mbr_flash.sh
cat /dev/null > /var/log/messages
dmesg -c > /dev/null
#sh dump_msg.sh &
#dmesg -n 7
SKIP_FW_LOAD=0
#Master Boot Record and Software Bootloader flashing modes
#Driver Mode 8 Flashing with Calib data from EEPROM,
# 10 Flashing with Calib data from calib_data file
DRIVER_MODE=8
FW_LOAD_MODE=4
insmod onebox_nongpl.ko driver_mode=$DRIVER_MODE firmware_path=$PWD/firmware/ onebox_zone_enabled=0x1 skip_fw_load=$SKIP_FW_LOAD fw_load_mode=$FW_LOAD_MODE
insmod onebox_gpl.ko
<file_sep>/zigbee/osi_zigb/onebox_zigb_osi_callbacks.c
#include "onebox_core.h"
#include "onebox_pktpro.h"
#include "onebox_linux.h"
static struct onebox_osi_zigb_ops osi_zigb_ops = {
.onebox_core_init = core_zigb_init,
.onebox_core_deinit = core_zigb_deinit,
.onebox_dump = onebox_print_dump,
.onebox_send_pkt = send_zigb_pkt,
};
struct onebox_osi_zigb_ops *onebox_get_osi_zigb_ops(void)
{
return &osi_zigb_ops;
}
EXPORT_SYMBOL(onebox_get_osi_zigb_ops);
<file_sep>/release/sniffer.sh
cat /dev/null > /var/log/messages
#dmesg -c > /dev/null
#sh dump_msg.sh &
#dmesg -n 7
#Sniffer mode
DRIVER_MODE=7
COEX_MODE=1
TA_AGGR=4
SKIP_FW_LOAD=0
FW_LOAD_MODE=1
insmod onebox_nongpl.ko driver_mode=$DRIVER_MODE firmware_path=$PWD/firmware/ onebox_zone_enabled=0x1 coex_mode=$COEX_MODE ta_aggr=$TA_AGGR skip_fw_load=$SKIP_FW_LOAD fw_load_mode=$FW_LOAD_MODE
insmod onebox_gpl.ko
insmod wlan.ko
insmod wlan_wep.ko
insmod wlan_tkip.ko
insmod wlan_ccmp.ko
insmod wlan_acl.ko
insmod wlan_xauth.ko
insmod wlan_scan_sta.ko
insmod onebox_wlan_nongpl.ko
insmod onebox_wlan_gpl.ko
#./onebox_util rpine0 create_vap wifi0 mon
#ifconfig wifi0 up
<file_sep>/wlan/wlan_hal/osi_wlan/core/onebox_core_wmm.c
/**
* @file onebox_core_wmm.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contians the WMM queue determination logic
*/
#include "onebox_common.h"
/**
* This function gets the contention values for the backoff procedure.
*
* @param Pointer to the channel acces params sturcture
* @param Pointer to the driver's private structure.
* @return none.
*/
void onebox_set_contention_vals(struct ieee80211com *ic, PONEBOX_ADAPTER adapter)
{
struct chanAccParams *wme_params = &ic->ic_wme.wme_wmeChanParams;
adapter->wme_org_q[VO_Q_STA] = (((wme_params->cap_wmeParams[WME_AC_VO].wmep_logcwmin / 2 ) +
(wme_params->cap_wmeParams[WME_AC_VO].wmep_aifsn)) * WMM_SHORT_SLOT_TIME + SIFS_DURATION);
adapter->wme_org_q[VI_Q_STA] = (((wme_params->cap_wmeParams[WME_AC_VI].wmep_logcwmin / 2 ) +
(wme_params->cap_wmeParams[WME_AC_VI].wmep_aifsn)) * WMM_SHORT_SLOT_TIME + SIFS_DURATION);
adapter->wme_org_q[BE_Q_STA] = (((wme_params->cap_wmeParams[WME_AC_BE].wmep_logcwmin / 2 ) +
(wme_params->cap_wmeParams[WME_AC_BE].wmep_aifsn-1)) * WMM_SHORT_SLOT_TIME + SIFS_DURATION);
adapter->wme_org_q[BK_Q_STA] = (((wme_params->cap_wmeParams[WME_AC_BK].wmep_logcwmin / 2 ) +
(wme_params->cap_wmeParams[WME_AC_BK].wmep_aifsn)) * WMM_SHORT_SLOT_TIME + SIFS_DURATION);
printk("In %s Line %d QUEUE WT are \n", __func__, __LINE__);
printk("BE_Q %d \n",adapter->wme_org_q[BE_Q_STA] );
printk("BK_Q %d \n",adapter->wme_org_q[BK_Q_STA] );
printk("VI_Q %d \n",adapter->wme_org_q[VI_Q_STA] );
printk("VO_Q %d \n",adapter->wme_org_q[VO_Q_STA] );
/* For AP 4 more Queues */
adapter->wme_org_q[VO_Q_AP] = (((wme_params->cap_wmeParams[WME_AC_VO].wmep_logcwmin / 2 ) +
(wme_params->cap_wmeParams[WME_AC_VO].wmep_aifsn)) * WMM_SHORT_SLOT_TIME + SIFS_DURATION);
adapter->wme_org_q[VI_Q_AP] = (((wme_params->cap_wmeParams[WME_AC_VI].wmep_logcwmin / 2 ) +
(wme_params->cap_wmeParams[WME_AC_VI].wmep_aifsn)) * WMM_SHORT_SLOT_TIME + SIFS_DURATION);
adapter->wme_org_q[BE_Q_AP] = (((wme_params->cap_wmeParams[WME_AC_BE].wmep_logcwmin / 2 ) +
(wme_params->cap_wmeParams[WME_AC_BE].wmep_aifsn)) * WMM_SHORT_SLOT_TIME + SIFS_DURATION);
adapter->wme_org_q[BK_Q_AP] = (((wme_params->cap_wmeParams[WME_AC_BK].wmep_logcwmin / 2 ) +
(wme_params->cap_wmeParams[WME_AC_BK].wmep_aifsn)) * WMM_SHORT_SLOT_TIME + SIFS_DURATION);
adapter->os_intf_ops->onebox_memcpy(adapter->per_q_wt, adapter->wme_org_q, sizeof(adapter->per_q_wt));
adapter->os_intf_ops->onebox_memset(adapter->pkt_contended, 0, sizeof(adapter->pkt_contended));
}
/**
* This function determines the HAL queue from which packets has to be dequeued while transmission.
*
* @param Pointer to the driver's private structure .
* @return ONEBOX_STATUS_SUCCESS on success else ONEBOX_STATUS_FAILURE.
*/
uint8 core_determine_hal_queue(PONEBOX_ADAPTER adapter)
{
uint8 q_num = INVALID_QUEUE;
uint8 ii,min = 0;
uint8 fresh_contention;
struct ieee80211com *ic;
struct chanAccParams *wme_params_sta;
ic= &adapter->vap_com;
wme_params_sta = &ic->ic_wme.wme_wmeChanParams;
if (adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->host_tx_queue[MGMT_SOFT_Q]))
{
q_num = MGMT_SOFT_Q;
return q_num;
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("per q wt values in %d: %d %d %d %d \n"),
__LINE__, adapter->per_q_wt[0], adapter->per_q_wt[1],
adapter->per_q_wt[2], adapter->per_q_wt[3]));
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("selected queue num and pkt cnt are : %d %d %d \n"),
__LINE__, adapter->selected_qnum, adapter->pkt_cnt));
if (adapter->pkt_cnt != 0)
{
adapter->pkt_cnt -= 1;
return (adapter->selected_qnum);
}
GET_QUEUE_NUM:
q_num = 0;
fresh_contention = 0;
/* Selecting first valid contention value */
for(ii = 0; ii < NUM_EDCA_QUEUES ; ii++)
{
if(adapter->pkt_contended[ii] &&
((adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->host_tx_queue[ii])) != 0)) /* Check for contended value*/
{
min = adapter->per_q_wt[ii];
q_num = ii;
break;
}
}
/* Selecting the queue with least back off */
for(; ii < NUM_EDCA_QUEUES ; ii++) /* Start finding the least value from first valid value itself
* Leave the value of ii as is from previous loop */
{
if(adapter->pkt_contended[ii] && (adapter->per_q_wt[ii] < min)
&& ((adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->host_tx_queue[ii]) !=0))) /* Check only if contended */
{
min = adapter->per_q_wt[ii];
q_num = ii;
}
}
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("min =%d and qnum=%d\n"), min, q_num));
/* Adjust the back off values for all queues again */
adapter->pkt_contended[q_num] = 0; /* Reset the contention for the current queue so that it gets org value again if it has more packets */
for(ii = 0; ii< NUM_EDCA_QUEUES; ii++)
{
if(adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->host_tx_queue[ii]))/* Check for the need of contention */
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("queue %d len %d\n"),
ii, adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->host_tx_queue[ii])));
if(adapter->pkt_contended[ii])
{
if(adapter->per_q_wt[ii] > min)
{ /* Subtracting the backoff value if already contended */
adapter->per_q_wt[ii] -= min;
}
else /* This case occurs only two queues end up in having same back off value and is least */
{
adapter->per_q_wt[ii] = 0;
}
}
else /* Fresh contention */
{
adapter->pkt_contended[ii] = 1;
adapter->per_q_wt[ii] = adapter->wme_org_q[ii];
fresh_contention = 1;
}
}
else
{ /* No packets so no contention */
adapter->per_q_wt[ii] = 0;
adapter->pkt_contended[ii] = 0;
}
}
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("per q values in %d: %d %d %d %d \n"),
__LINE__, adapter->per_q_wt[0], adapter->per_q_wt[1], adapter->per_q_wt[2], adapter->per_q_wt[3]));
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("pkt contended val in %d: %d %d %d %d \n\n"),
__LINE__, adapter->pkt_contended[0], adapter->pkt_contended[1],
adapter->pkt_contended[2], adapter->pkt_contended[3]));
if((adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->host_tx_queue[q_num])) == 0)
{
/* If any queues are freshly contended and the selected queue doesn't have any packets
* then get the queue number again with fresh values */
if(fresh_contention)
{
goto GET_QUEUE_NUM;
}
q_num = INVALID_QUEUE;
return q_num;
}
adapter->selected_qnum = q_num ;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("WMM::queue num after algo= %d \n"), q_num));
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("queue %d len %d \n"), q_num,
adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->host_tx_queue[q_num])));
if ((adapter->selected_qnum == VO_Q_STA) || (adapter->selected_qnum == VI_Q_STA))
{
if(adapter->selected_qnum == VO_Q_STA) {
if(wme_params_sta->cap_wmeParams[adapter->selected_qnum].wmep_acm)
adapter->pkt_cnt = 1;
else
adapter->pkt_cnt = 6;
//adapter->pkt_cnt = ((wme_params_sta->cap_wmeParams[adapter->selected_qnum].wmep_txopLimit << 5) / 150);
} else {
if(wme_params_sta->cap_wmeParams[adapter->selected_qnum].wmep_acm) {
adapter->pkt_cnt = 1;
} else {
adapter->pkt_cnt = ((wme_params_sta->cap_wmeParams[adapter->selected_qnum].wmep_txopLimit << 5) / 800);
//adapter->pkt_cnt = 6;
}
}
if((adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->host_tx_queue[q_num])) <= adapter->pkt_cnt)
{
adapter->pkt_cnt = ((adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->host_tx_queue[q_num])));
}
if(adapter->pkt_cnt != 0)
{
adapter->pkt_cnt -= 1;
}
else
{
adapter->pkt_cnt = 0;
}
}
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("pkt_cnt and q_num are: %d %d \n"), adapter->pkt_cnt, q_num));
return (q_num);
}
return ONEBOX_STATUS_FAILURE;
}
<file_sep>/release/zigb_insert.sh
sh common_insert.sh
insmod onebox_zigb_nongpl.ko
insmod onebox_zigb_gpl.ko
<file_sep>/common_hal/intfdep/usb/osi_usb/onebox_usb_main_osi.c
/**
* @file onebox_usb_main_osi.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* The file contains Generic HAL changes for USB.
*/
#include "onebox_common.h"
#include "onebox_sdio_intf.h"
/**
* This function writes the packet to the device.
* @param Pointer to the driver's private data structure
* @param Pointer to the data to be written on to the device
* @param Length of the data to be written on to the device.
* @return 0 if success else a negative number.
*/
ONEBOX_STATUS host_intf_write_pkt(PONEBOX_ADAPTER adapter, uint8 *pkt, uint32 Len, uint8 q_no)
{
uint32 block_size = adapter->TransmitBlockSize;
uint32 num_blocks,Address,Length;
uint32 queueno = (q_no & 0x7);
#ifndef RSI_SDIO_MULTI_BLOCK_SUPPORT
uint32 ii;
#endif
ONEBOX_STATUS status = ONEBOX_STATUS_SUCCESS;
if( !Len && (queueno == ONEBOX_WIFI_DATA_Q ))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(" Wrong length \n")));
return ONEBOX_STATUS_FAILURE;
} /* End if <condition> */
num_blocks = Len/block_size;
if (Len % block_size)
{
num_blocks++;
}
#ifdef ENABLE_SDIO_CHANGE
if (num_blocks < 2)
{
num_blocks = 2;
}
#endif
Address = num_blocks * block_size | (queueno << 12);
Length = num_blocks * block_size;
#if 0
Address = (queueno == ONEBOX_WIFI_MGMT_Q) ? 1 : 2; //FIXME: This is endpoint num which should be calculated from pkt[8] & 0xff epnum = 1(Int mgmt) 2 (Data)
#else
/* Fill endpoint numbers based on queueno */
if ((queueno == COEX_TX_Q) || (queueno == WLAN_TX_M_Q) || (queueno == WLAN_TX_D_Q)) {
Address = 1;
} else if ((queueno == BT_TX_Q) || (queueno == ZIGB_TX_Q)) {
Address = 2;
}
#endif
#ifdef RSI_SDIO_MULTI_BLOCK_SUPPORT
status = adapter->osd_host_intf_ops->onebox_write_multiple(adapter,
Address,
(uint8 *)pkt,
Len);
if (status != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Unable to write onto the card: %d\n"),__func__,
status));
printk(" <======= Desc details written previously ========== >\n");
adapter->coex_osi_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)adapter->prev_desc, FRAME_DESC_SZ);
printk(" Current Pkt: Card write PKT details\n");
adapter->coex_osi_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)pkt, Length);
onebox_abort_handler(adapter);
} /* End if <condition> */
#else
/* Non multi block read */
for(ii = 0; ii < num_blocks; ii++)
{
if(ii==0)
{
status = adapter->osd_host_intf_ops->onebox_write_multiple(adapter,
(num_blocks*block_size |
(queueno<<12)),
pkt + (ii*block_size),
block_size);
}
else
{
status = adapter->osd_host_intf_ops->onebox_write_multiple(adapter,
(num_blocks*block_size),
pkt + (ii*block_size),
block_size);
} /* End if <condition> */
if(status != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_DATA_SEND,
(TEXT("Multi Block Support: Writing to CARD Failed\n")));
onebox_abort_handler(adapter);
status = ONEBOX_STATUS_FAILURE;
} /* End if <condition> */
} /* End for loop */
#endif
ONEBOX_DEBUG(ONEBOX_ZONE_DATA_SEND,
(TEXT("%s:Successfully written onto card\n"),__func__));
return status;
}/*End <host_intf_write_pkt>*/
/**
* This function reads the packet from the SD card.
* @param Pointer to the driver's private data structure
* @param Pointer to the packet data read from the the device
* @param Length of the data to be read from the device.
* @return 0 if success else a negative number.
*/
ONEBOX_STATUS host_intf_read_pkt(PONEBOX_ADAPTER adapter,uint8 *pkt,uint32 length)
{
//uint32 Blocksize = adapter->ReceiveBlockSize;
ONEBOX_STATUS Status = ONEBOX_STATUS_SUCCESS;
//uint32 num_blocks;
ONEBOX_DEBUG(ONEBOX_ZONE_DATA_RCV,(TEXT( "%s: Reading %d bytes from the card\n"),__func__, length));
if (!length)
{
//ONEBOX_DEBUG(ONEBOX_ZONE_DEBUG,
// (TEXT( "%s: Pkt size is zero\n"),__func__));
return Status;
}
//num_blocks = (length / Blocksize);
/*Reading the actual data*/
Status = adapter->osd_host_intf_ops->onebox_read_multiple(adapter,
length,
length, /*num of bytes*/
(uint8 *)pkt);
if (Status != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT(
"%s: Failed to read frame from the card: %d\n"),__func__,
Status));
printk("Card Read PKT details len =%d :\n", length);
adapter->coex_osi_ops->onebox_dump(ONEBOX_ZONE_ERROR, (PUCHAR)pkt, length);
return Status;
}
return Status;
}
/**
* This function intern calls the SDIO slave registers initialization function
* where SDIO slave registers are being initialized.
*
* @param Pointer to our adapter structure.
* @return 0 on success and -1 on failure.
*/
ONEBOX_STATUS init_host_interface(PONEBOX_ADAPTER adapter)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Initializing interface\n"),__func__));
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("%s: Sending init cmd\n"),__func__));
/* Initialise the SDIO slave registers */
return onebox_init_sdio_slave_regs(adapter);
}/* End <onebox_init_interface> */
/**
* This function does the actual initialization of SDBUS slave registers.
*
* @param Pointer to the driver adapter structure.
* @return ONEBOX_STATUS_SUCCESS on success and ONEBOX_STATUS_FAILURE on failure.
*/
ONEBOX_STATUS onebox_init_sdio_slave_regs(PONEBOX_ADAPTER adapter)
{
uint8 byte;
ONEBOX_STATUS status = ONEBOX_STATUS_SUCCESS;
uint8 reg_dmn;
FUNCTION_ENTRY(ONEBOX_ZONE_INIT);
reg_dmn = 0; //TA domain
/* initialize Next read delay */
if(adapter->next_read_delay)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Initialzing SDIO_NXT_RD_DELAY2\n"), __func__));
byte = adapter->next_read_delay;
status = adapter->osd_host_intf_ops->onebox_write_register(adapter,
reg_dmn,
SDIO_NXT_RD_DELAY2,&byte);
if(status)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: fail to write SDIO_NXT_RD_DELAY2\n"), __func__));
return ONEBOX_STATUS_FAILURE;
}
}
if(adapter->sdio_high_speed_enable)
{
#define SDIO_REG_HIGH_SPEED 0x13
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Enabling SDIO High speed\n"), __func__));
byte = 0x3;
status = adapter->osd_host_intf_ops->onebox_write_register(adapter,reg_dmn,SDIO_REG_HIGH_SPEED,&byte);
if(status)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: fail to enable SDIO high speed\n"), __func__));
return ONEBOX_STATUS_FAILURE;
}
}
/* This tells SDIO FIFO when to start read to host */
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Initialzing SDIO read start level\n"), __func__));
byte = 0x24;
status = adapter->osd_host_intf_ops->onebox_write_register(adapter,reg_dmn,SDIO_READ_START_LVL,&byte);
if(status)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: fail to write SDIO_READ_START_LVL\n"), __func__));
return ONEBOX_STATUS_FAILURE;
}
/* Change these parameters to load firmware */
/* This tells SDIO FIFO when to start read to host */
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Initialzing FIFO ctrl registers\n"), __func__));
byte = (128-32);
status = adapter->osd_host_intf_ops->onebox_write_register(adapter,reg_dmn,SDIO_READ_FIFO_CTL,&byte);
if(status)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: fail to write SDIO_READ_FIFO_CTL\n"), __func__));
return ONEBOX_STATUS_FAILURE;
}
/* This tells SDIO FIFO when to start read to host */
byte = 32;
status = adapter->osd_host_intf_ops->onebox_write_register(adapter,reg_dmn,SDIO_WRITE_FIFO_CTL,&byte);
if(status)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: fail to write SDIO_WRITE_FIFO_CTL\n"), __func__));
return ONEBOX_STATUS_FAILURE;
}
FUNCTION_EXIT(ONEBOX_ZONE_INIT);
return ONEBOX_STATUS_SUCCESS;
}/* End <onebox_init_sdio_slave_regs> */
/**
* This function reads the abort register until it is cleared.
*
* This function is invoked when ever CMD53 read or write gets
* failed.
*
* @param Pointer to the driver adapter structure.
* @return 0 on success and -1 on failure.
*/
ONEBOX_STATUS onebox_abort_handler(PONEBOX_ADAPTER adapter )
{
return ONEBOX_STATUS_SUCCESS;
}
<file_sep>/wlan/wlan_hal/osi_wlan/core/onebox_core_wlan.c
/**
* @file onebox_core.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contians
*/
#include "onebox_core.h"
ONEBOX_STATUS onebox_mgmt_send_bb_reset_req(PONEBOX_ADAPTER adapter);
/** This function is used to determine the wmm queue based on the backoff procedure.
* Data packets are dequeued from the selected hal queue and sent to the below layers.
* @param pointer to the driver private data structure
* @return void
*/
void core_qos_processor(PONEBOX_ADAPTER adapter)
{
netbuf_ctrl_block_t *netbuf_cb;
uint8 q_num;
uint8 counter = 0;
uint8 device_buf_status = 0;
uint8 status;
struct ieee80211com *ic;
struct ieee80211vap *vap = NULL;
uint32 vap_id = 0;
uint32 sta_id = 0;
struct ieee80211_node *ni = NULL;
struct driver_assets *d_assets = onebox_get_driver_asset();
ic = &adapter->vap_com;
if(!d_assets->techs[WLAN_ID].tx_access) {
//check whther we have tx_access or not
d_assets->techs[WLAN_ID].tx_intention = 1;
d_assets->update_tx_status(WLAN_ID);
if(!d_assets->techs[WLAN_ID].tx_access) {
printk("Waiting for tx_acces from common hal cmntx %d\n", d_assets->common_hal_tx_access);
d_assets->techs[WLAN_ID].deregister_flags = 1;
printk("Waiting evbent %s Line %d\n", __func__, __LINE__);
if (wait_event_timeout((d_assets->techs[WLAN_ID].deregister_event), (d_assets->techs[WLAN_ID].deregister_flags == 0), msecs_to_jiffies(6000) )) {
if(!d_assets->techs[WLAN_ID].tx_access) {
printk("In %s Line %d unable to get access \n", __func__, __LINE__);
return;
}
} else {
printk("ERR: In %s Line %d Initialization of WLAN Failed as Wlan TX access is not granted from Common Hal \n", __func__, __LINE__);
return;
}
}
}
while (1)
{
if(adapter->beacon_event) /* Check for beacon event set and break from here */
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("CORE_MSG: BEACON EVENT HAS HIGHEST PRIORITY\n")));
break;
}
if(adapter->fsm_state == FSM_MAC_INIT_DONE)
{
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap->iv_opmode == IEEE80211_M_STA){
break;
}
}
if(vap && (PS_STATE == PS_EN_REQ_SENT) && (vap->iv_state != IEEE80211_S_RUN))
{
printk("Breaking the schedule has PS is disabled vap_state %d PS_STATE %d\n", vap->iv_state, PS_STATE);
break;
}
}
q_num = core_determine_hal_queue(adapter);
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("\nCORE_MSG: qos_processor: Queue number = %d\n"), q_num));
if (q_num == INVALID_QUEUE)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("\nCORE_MSG: qos_pro: No More Pkt Due to invalid queueno\n")));
break;
}
if(adapter->sta_data_block && (q_num < NO_STA_DATA_QUEUES))
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("CORE_MSG: Data block is set, So don't dequeue pkts\n")));
break;
}
if (adapter->block_ap_queues &&
(((q_num > NO_STA_DATA_QUEUES)
&& (q_num < MGMT_SOFT_Q)) || (q_num == BEACON_HW_Q))
) {
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("CORE_MSG: AP Data block is set, So don't dequeue pkts\n")));
break;
}
if(adapter->buf_status_updated ||(!counter))
{ /* Polling buffer full status for every 4 packets */
/* Shouldn't change this place of updation */
adapter->buf_status_updated = 0;
status = adapter->osd_host_intf_ops->onebox_read_register(adapter,
adapter->buffer_status_register,
&device_buf_status); /* Buffer */
if (status != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Failed to Read Intr Status Register\n"),__func__));
break;
}
if(device_buf_status & (ONEBOX_BIT(SD_PKT_MGMT_BUFF_FULL)))
{
if(!adapter->mgmt_buffer_full)
{
adapter->mgmt_buf_full_counter++;
}
adapter->mgmt_buffer_full = 1;
ONEBOX_DEBUG(ONEBOX_ZONE_INFO, (TEXT("CORE_MSG: MGMT BUFFER FULL Queueing data packets till BUFFER_FREE COMES\n")));
break;
}
else
{
adapter->mgmt_buffer_full = 0;
}
if((!(device_buf_status & (ONEBOX_BIT(SD_PKT_BUFF_FULL)))) &&
(!(device_buf_status & (ONEBOX_BIT(SD_PKT_BUFF_SEMI_FULL))))) {
adapter->no_buffer_fulls++;
}
if(device_buf_status & (ONEBOX_BIT(SD_PKT_BUFF_FULL)))
{
if(!adapter->buffer_full)
{
adapter->buf_full_counter++;
}
adapter->buffer_full = 1;
//ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("CORE_MSG: BUFFER FULL Queueing data packets till BUFFER_FREE COMES\n")));
}
else
{
adapter->buffer_full = 0;
}
if(device_buf_status & (ONEBOX_BIT(SD_PKT_BUFF_SEMI_FULL)))
{
if(!adapter->semi_buffer_full)
{
adapter->buf_semi_full_counter++;
}
adapter->semi_buffer_full = 1;
}
else
{
adapter->semi_buffer_full = 0;
}
((adapter->semi_buffer_full == 0) ? (counter = 4) : (counter = 1));
}
#if 0
if((q_num != MGMT_SOFT_Q) && adapter->buffer_full) /* Check buffer full only for data packets */
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("CORE_MSG: BUFFER FULL Queueing data packets till BUFFER_FREE COMES\n")));
break;
}
#endif
if((q_num == MGMT_SOFT_Q) && adapter->mgmt_buffer_full) /* Check mgmtbuffer full for mgmt packets */
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("CORE_MSG: MGMT BUFFER FULL Queueing data packets till BUFFER_FREE COMES\n")));
break;
}
else if((adapter->buffer_full) && (q_num != MGMT_SOFT_Q))
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("CORE_MSG: BUFFER FULL Queueing data packets till BUFFER_FREE COMES\n")));
break;
}
if(adapter->fsm_state == FSM_MAC_INIT_DONE)
{
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if((vap->iv_opmode == IEEE80211_M_STA)
&& (((PS_STATE == DEV_IN_PWR_SVE) && (vap->iv_state != IEEE80211_S_RUN)))) {
//|| ((driver_ps.delay_pwr_sve_decision_flag) && ((vap->iv_state != IEEE80211_S_RUN)))){
printk("In %s line %d \n", __func__, __LINE__);
update_pwr_save_status(vap, PS_DISABLE, MGMT_PENDING_PATH);
break;
}
}
}
/* Removing A Packet From The netbuf Queue */
netbuf_cb = core_dequeue_pkt(adapter, q_num);
counter--;
if (netbuf_cb == NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("\nCORE_MSG:NETBUF is NULL qnum = %d\n"),q_num));
break;
}
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("CORE_MSG: qos_pro: Sending Packet To HAL\n")));
if(q_num == MGMT_SOFT_Q)
{
if(netbuf_cb->flags & INTERNAL_MGMT_PKT)
{
printk("Internal mgmt pkt dump\n");
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("CORE_MSG: Mgmt PKT calling on air mgmt\n")));
//adapter->devdep_ops->onebox_snd_mgmt_pkt(adapter,netbuf_cb);
onebox_internal_pkt_dump(adapter, netbuf_cb);
/* Observed Rx done handling happening before PS State being changed.
* Hence writing the packet after state is changed in USB case */
#ifndef USE_USB_INTF
status = adapter->onebox_send_pkt_to_coex(netbuf_cb, WLAN_Q);
#endif
if(netbuf_cb->data[2] == WAKEUP_SLEEP_REQUEST)
{
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
if(vap->iv_opmode == IEEE80211_M_STA){
break;
}
}
if( (netbuf_cb->data[16] == PS_DISABLE)&& (netbuf_cb->data[18] == DEEP_SLEEP))
{
}
else if(vap && (PS_STATE == PS_EN_REQ_QUEUED))
{
PS_STATE = PS_EN_REQ_SENT;
printk("In %s line %d mvng pwr save state to %d\n", __func__, __LINE__, PS_STATE);
}
}
#ifdef USE_USB_INTF
status = adapter->onebox_send_pkt_to_coex(netbuf_cb, WLAN_Q);
#endif
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
continue;
}
}
if(q_num < MAX_HW_QUEUES)
adapter->total_tx_data_sent[q_num]++;
if(q_num == MGMT_SOFT_Q)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("CORE_MSG: Mgmt PKT\n")));
//adapter->devdep_ops->onebox_snd_mgmt_pkt(adapter,netbuf_cb);
onair_mgmt_dump(adapter, netbuf_cb, netbuf_cb->data[4]);
status = adapter->onebox_send_pkt_to_coex(netbuf_cb, WLAN_Q);
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("CORE_MSG: Data PKT \n")));
vap_id = netbuf_cb->data[9] >> 6;
sta_id = netbuf_cb->data[15];
ni = (struct ieee80211_node *)netbuf_cb->ni;
adapter->os_intf_ops->onebox_acquire_sem(&adapter->ic_lock_vap, 0);
if(!adapter->hal_vap[vap_id].vap_in_use)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("CORE_MSG:Dropping pkts as vap is deleted vap id %d \n"), vap_id));
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
adapter->os_intf_ops->onebox_release_sem(&adapter->ic_lock_vap);
continue;
}
vap = ni->ni_vap;
/* Has to be taken care for multiple vaps case in a different way */
if(!vap){
printk("Unable to find VAP node\n");
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
adapter->os_intf_ops->onebox_release_sem(&adapter->ic_lock_vap);
continue;
}
if ((adapter->hal_vap[vap_id].vap == vap) &&
(vap->hal_priv_vap)) {
if ((adapter->os_intf_ops->onebox_netbuf_queue_len(&adapter->host_tx_queue[q_num])) < (adapter->host_txq_maxlen[q_num] - 500)) {
#ifndef USE_SUBQUEUES
if(adapter->os_intf_ops->onebox_is_ifp_txq_stopped(vap->iv_ifp))
#else
if(adapter->os_intf_ops->onebox_is_sub_txq_stopped(vap->iv_ifp, netbuf_cb->skb_priority))
#endif
{
#ifndef USE_SUBQUEUES
adapter->os_intf_ops->onebox_start_ifp_txq(vap->iv_ifp);
#else
adapter->os_intf_ops->onebox_start_sub_txq(vap->iv_ifp, netbuf_cb->skb_priority);
#endif
}
if(vap->hal_priv_vap->stop_udp_pkts[q_num]) {
vap->hal_priv_vap->stop_udp_pkts[q_num] = 0;
vap->hal_priv_vap->stop_per_q[q_num] = 0;
}
}
} else {
printk("Invalid VAP Ptr, We are seeing pkts on old vap ptr\n");
}
if(!((netbuf_cb->flags & ONEBOX_BROADCAST_PKT) && (vap->iv_opmode == IEEE80211_M_HOSTAP)))
{
if(sta_id >= adapter->max_stations_supported) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("CORE_MSG:Dropping pkts as sta_id is greater than max supported stations%d \n"), sta_id));
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
adapter->os_intf_ops->onebox_release_sem(&adapter->ic_lock_vap);
continue;
}
if(!(adapter->sta_connected_bitmap[sta_id/32] & BIT(sta_id % 32))) /* each bitmap is uint32 so diving by 32*/
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("CORE_MSG:Dropping pkts as station is deleted sta id %d \n"), sta_id));
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
adapter->os_intf_ops->onebox_release_sem(&adapter->ic_lock_vap);
continue;
}
}
adapter->os_intf_ops->onebox_release_sem(&adapter->ic_lock_vap);
status = adapter->onebox_send_pkt_to_coex(netbuf_cb, WLAN_Q);
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
}
}
if(vap && (vap->iv_opmode == IEEE80211_M_STA) && (ps_params_def.ps_en)) {
d_assets->techs[WLAN_ID].tx_intention = 0;
d_assets->techs[WLAN_ID].tx_access = 0;
d_assets->update_tx_status(WLAN_ID);
}
return;
}
/**
* This function indicates the received packet to net80211.
* @param Pointer to the adapter structure
* @param pointer to the netbuf control block structure.
* @return ONEBOX_STATUS_SUCCESS on success else negative number on failure.
*/
uint32 wlan_core_pkt_recv(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb, int8 rs_rssi, int8 chno)
{
int16 nf=0, status,rs_tstamp=0;
struct ieee80211_node *ni;
struct ieee80211com *ic = &adapter->vap_com;
struct ieee80211vap *vap =NULL;
netbuf_ctrl_block_m_t *netbuf_cb_m;
uint8_t tid;
/*
* No key index or no entry, do a lookup and
* add the node to the mapping table if possible.
*
*/
ni = adapter->net80211_ops->onebox_find_rxnode(ic,
(const struct ieee80211_frame_min *)netbuf_cb->data);
netbuf_cb_m = onebox_translate_netbuf_to_mbuf(netbuf_cb);
if (netbuf_cb_m == NULL) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Unable to alloc mem %s %d\n"), __func__, __LINE__));
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
return ONEBOX_STATUS_FAILURE;
}
if (ni != NULL)
{
vap = ni->ni_vap;
/* set the M_AMPDU FLAG if addba setup is done for receiving tid for now.
* Ideally this should be taken from PPE */
if(ni->ni_flags & IEEE80211_NODE_HT)
{
tid = ieee80211_gettid((const struct ieee80211_frame *)netbuf_cb_m->m_data);
if (tid < WME_NUM_TID)
{
if (ni->ni_rx_ampdu[tid].rxa_flags & IEEE80211_AGGR_RUNNING)
{
netbuf_cb_m->m_flags |= M_AMPDU;
}
}
}
ni->hal_priv_node.chno = chno;
//printk("SCAN: In %s Line %d chno = %02x \n", __func__, __LINE__, ni->hal_priv_node.chno);
status = vap->iv_input(ni, netbuf_cb_m, rs_rssi, nf);
/*
* If the station has a key cache slot assigned
* update the key->node mapping table.
*/
}
else
{
status = adapter->net80211_ops->onebox_input_all(ic, netbuf_cb_m, rs_rssi, rs_tstamp, chno);
}
if(!status)
{
return ONEBOX_STATUS_SUCCESS;
}
else
{
return ONEBOX_STATUS_FAILURE;
}
}
#ifdef BYPASS_RX_DATA_PATH
uint8 bypass_data_pkt(PONEBOX_ADAPTER adapter, netbuf_ctrl_block_t *netbuf_cb)
{
struct ieee80211com *ic = &adapter->vap_com;
struct ieee80211vap *vap =NULL;
TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
{
netbuf_cb->dev = vap->iv_ifp;
adapter->os_intf_ops->onebox_indicate_pkt_to_os(vap->iv_ifp, netbuf_cb);
}
return 0;
}
#endif
/**
* This function sends the beacon packet.
*
* @param Pointer to ieee80211vap structure.
* @param pointer to the netbuf control block structure.
* @return ONEBOX_STATUS_SUCCESS on success else negative number on failure.
*/
uint32 core_send_beacon(PONEBOX_ADAPTER adapter,netbuf_ctrl_block_t *netbuf_cb, struct core_vap *core_vp)
{
uint16 i;
uint8 dtim_beacon = 0;
/* Drop Zero Length Beacon */
if (!(netbuf_cb->len))
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("\nCORE_MSG: ### Zero Length Beacon ###")));
return ONEBOX_STATUS_FAILURE;
}
/* Drop if FSM state is not open */
if (adapter->fsm_state != FSM_MAC_INIT_DONE)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("\nCORE_MSG: ### FSM state is not open ###\n")));
return ONEBOX_STATUS_FAILURE;
}
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("CORE_MSG:===> Sending beacon to packet processor <===\n")));
if (1)
{
#define BEACON_PARSING_OFFSET 36
/* Parsing the beacon content to identify dtim beacons */
for( i = BEACON_PARSING_OFFSET; i < netbuf_cb->len ;) /* start beacon parsing from first element */
/*Fixed elements are of length 12 and mac header length is 24 */
{
if(netbuf_cb->data[i] == IEEE80211_ELEMID_TIM) /* Checking for TIM Element Value is 0x5*/
{
if(netbuf_cb->data[i+2] == 0) /*tim count field */
{
dtim_beacon = 1;
}
break;
}
i += (netbuf_cb->data[i+1] + 2);
}
adapter->devdep_ops->onebox_send_beacon(adapter, netbuf_cb, core_vp, dtim_beacon);
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("\nCORE_MSG: Beacon HAL queue is full\n")));
return ONEBOX_STATUS_FAILURE;
}
return ONEBOX_STATUS_SUCCESS;
}
/**
* This function gives the packet to the radiotap module.
*
* @param Pointer to ieee80211vap structure.
* @param Pointer to the netbuf control block structure.
* @return none.
*/
void core_radiotap_tx(PONEBOX_ADAPTER adapter, struct ieee80211vap *vap, netbuf_ctrl_block_t *netbuf_cb)
{
netbuf_ctrl_block_m_t *netbuf_cb_m = NULL;
netbuf_cb_m = onebox_translate_netbuf_to_mbuf(netbuf_cb);
if (netbuf_cb_m == NULL) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR, (TEXT("Unable to alloc mem %s %d\n"), __func__, __LINE__));
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_cb, 0);
return;
}
adapter->net80211_ops->onebox_radiotap_tx(vap,netbuf_cb_m);
adapter->os_intf_ops->onebox_mem_free(netbuf_cb_m);
return;
}
/**
* This routine dump the given data through the debugger..
*
* @param Debug zone.
* @param Pointer to data that has to dump.
* @param Length of the data to dump.
* @return none.
*/
VOID onebox_print_dump(int32 zone,UCHAR *vdata, int32 len )
{
uint16 ii;
if(!zone)
{
return;
}
for(ii=0; ii< len; ii++)
{
if(!(ii % 16))
{
ONEBOX_DEBUG(zone, (TEXT("\n%04d: "), ii));
}
ONEBOX_DEBUG(zone,(TEXT("%02x "),(vdata[ii])));
}
ONEBOX_DEBUG(zone, (TEXT("\n")));
}
/**
* This routine indicates mic failure to net80211..
*
* @param Pointer to the driver private structure.
* @param pointer to the packet indicating mic failure.
* @return none.
*/
void core_michael_failure(PONEBOX_ADAPTER adapter, uint8 *msg)
{
struct ieee80211_node *ni = NULL;
struct ieee80211com *ic = &adapter->vap_com;
struct ieee80211vap *vap =NULL;
struct ieee80211_frame frame;
u_int keyix;
uint8 status_word;
frame.i_fc[0] = 0;
frame.i_fc[1] = 0;
adapter->os_intf_ops->onebox_memcpy(frame.i_addr2, (msg + 6), IEEE80211_ADDR_LEN);
/**/
status_word = msg[12];
keyix = 1;
ni = adapter->net80211_ops->onebox_find_rxnode(ic, (struct ieee80211_frame_min *)&frame);
if(!(ni)){
printk("In %s line %d: Node is null \n", __func__, __LINE__);
adapter->core_ops->onebox_dump(ONEBOX_ZONE_ERROR, msg, 16);
return;
}
printk("The mac addres of the node is %02x %02x %02x %02x %02x %02x\n", ni->ni_macaddr[0], ni->ni_macaddr[1],
ni->ni_macaddr[2],ni->ni_macaddr[3],ni->ni_macaddr[4],ni->ni_macaddr[5]);
vap = ni->ni_vap;
if(status_word & CIPHER_MISMATCH) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("Received Cipher Mismatch Ind\n")));
}
if(status_word & ICV_ERROR) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("Received ICV Failure Indication\n")));
}
if(status_word & MIC_FAILURE) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("Received MIC Failur Indication\n")));
if(!(status_word & BCAST_MIC))
adapter->net80211_ops->onebox_rxmic_failure(vap, (struct ieee80211_frame *)&frame, keyix);
}
}
<file_sep>/release/flash.sh
cat /dev/null > /var/log/messages
dmesg -c > /dev/null
#sh dump_msg.sh &
#dmesg -n 7
SKIP_FW_LOAD=0
FW_LOAD_MODE=4
DRIVER_MODE=5
#COEX MODE 1 WIFI ALONE
# 2 WIFI+BT Classic
# 3 WIFI+ZIGBEE
# 4 WIFI+BT LE (Low Engergy)
COEX_MODE=1
insmod onebox_nongpl.ko driver_mode=$DRIVER_MODE firmware_path=$PWD/firmware/ onebox_zone_enabled=0xffffffff coex_mode=$COEX_MODE skip_fw_load=$SKIP_FW_LOAD fw_load_mode=$FW_LOAD_MODE
insmod onebox_gpl.ko
<file_sep>/release/bt_insert.sh
sh common_insert.sh
insmod onebox_bt_nongpl.ko
insmod onebox_bt_gpl.ko
<file_sep>/release/per_lpbk.sh
cat /dev/null > /var/log/messages
#dmesg -c > /dev/null
#sh dump_msg.sh &
#dmesg -n 7
#Driver Mode
# 3 PER + Loopback + Calib
# 4 PER + Loopback
DRIVER_MODE=3
COEX_MODE=1
TA_AGGR=4
SKIP_FW_LOAD=0
FW_LOAD_MODE=2
insmod onebox_nongpl.ko driver_mode=$DRIVER_MODE firmware_path=$PWD/firmware/ onebox_zone_enabled=0x1 coex_mode=$COEX_MODE ta_aggr=$TA_AGGR skip_fw_load=$SKIP_FW_LOAD fw_load_mode=$FW_LOAD_MODE
insmod onebox_gpl.ko
insmod wlan.ko
insmod wlan_wep.ko
insmod wlan_tkip.ko
insmod wlan_ccmp.ko
insmod wlan_acl.ko
insmod wlan_xauth.ko
insmod wlan_scan_sta.ko
insmod onebox_wlan_nongpl.ko
insmod onebox_wlan_gpl.ko
<file_sep>/common_hal/osd/linux/onebox_modules_init.c
/**
* @file onebox_osd_main.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* This file contains all the Linux network device specific code.
*/
#include "onebox_common.h"
#include "onebox_linux.h"
#include "onebox_sdio_intf.h"
/**
* This function is invoked when the module is loaded into the
* kernel. It registers the client driver.
*
* @param VOID.
* @return On success 0 is returned else a negative value.
*/
ONEBOX_STATIC int32 __init onebox_module_init(VOID)
{
struct onebox_osd_host_intf_operations *osd_host_intf_ops;
struct driver_assets *d_assets = onebox_get_driver_asset();
/*Unregistering the client driver*/
osd_host_intf_ops = onebox_get_osd_host_intf_operations();
d_assets->card_state = 0;
d_assets->global_priv = NULL;
d_assets->techs[WLAN_ID].drv_state = MODULE_REMOVED;
d_assets->techs[WLAN_ID].fw_state = FW_INACTIVE;
d_assets->techs[BT_ID].drv_state = MODULE_REMOVED;
d_assets->techs[BT_ID].fw_state = FW_INACTIVE;
d_assets->techs[ZB_ID].drv_state = MODULE_REMOVED;
d_assets->techs[ZB_ID].fw_state = FW_INACTIVE;
/* registering the client driver */
if (osd_host_intf_ops->onebox_register_drv() == 0) {
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,
(TEXT("%s: Successfully registered gpl driver\n"),
__func__));
return ONEBOX_STATUS_SUCCESS;
} else {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Unable to register gpl driver\n"), __func__));
/*returning a negative value to imply error condition*/
return ONEBOX_STATUS_FAILURE;
} /* End if <condition> */
}/* End of <onebox_module_init> */
/**
* At the time of removing/unloading the module, this function is
* called. It unregisters the client driver.
*
* @param VOID.
* @return VOID.
*/
ONEBOX_STATIC VOID __exit onebox_module_exit(VOID)
{
struct onebox_osd_host_intf_operations *osd_host_intf_ops;
/*Unregistering the client driver*/
osd_host_intf_ops = onebox_get_osd_host_intf_operations();
if (osd_host_intf_ops->onebox_remove() == 0)
{
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT( "%s: called onebox_remove function\n"), __func__));
}
else
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,
(TEXT("%s: Unable to unregister GPL driver\n"),
__func__));
}
osd_host_intf_ops->onebox_unregister_drv();
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
(TEXT("%s: Unregistered the GPL driver\n"), __func__));
return;
}
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Redpine Signals Inc");
MODULE_DESCRIPTION("Coexistance Solution From Redpine Signals");
MODULE_SUPPORTED_DEVICE("Godavari RS911x WLAN Modules");
module_init(onebox_module_init);
module_exit(onebox_module_exit);
<file_sep>/release/upgrade.sh
#!/bin/sh
echo -e "\033[31mRunning Upgrade Script...\033[0m"
#Driver Mode 1 WiFi mode, 2 for Eval/PER Mode, 3 for Firmware_upgrade
rm firmware/flash_content
#cp RS9113_RS8111_calib_values.txt RS9113_RS8111_calib_values_copy.txt
sed -e 's/,//g' RS9113_RS8111_calib_values.txt > RS9113_RS8111_calib_values_copy.txt
xxd -r -ps RS9113_RS8111_calib_values_copy.txt firmware/flash_content
rm RS9113_RS8111_calib_values_copy.txt
cp RS9113_RS8111_calib_values.txt /home/rsi/release/ -rf
cp firmware/flash_content /home/rsi/release/firmware/ -rf
sh /home/rsi/release/remove.sh
sleep 2;
echo -e "\033[31mRmmoding any left *.ko....\033[0m"
touch /home/rsi/release/flash.sh
#sed 's/=2/=5/' /home/rsi/release/insert.sh > /home/rsi/release/insert_up.sh
echo -e "\033[31mEntered into Upgrade Mode....\033[0m"
echo -e "\033[31mInserting .kos with Driver Mode 3....\033[0m"
sh /home/rsi/release/flash.sh
sleep 2
state=`cat /proc/onebox-mobile/stats | grep "DRIVER_FSM_STATE" | cut -d ' ' -f 2 | cut -d '(' -f 1`
#state=FSM_MAC_INIT_DONE
if [ "$state" == "FSM_MAC_INIT_DONE" ]
then
sh /home/rsi/release/remove.sh
echo -e "\033[31mUpgrade Successful...\033[0m"
# sleep 5;
# sh /home/rsi/release/insert.sh
# state=`cat /proc/onebox-mobile/stats | grep "DRIVER_FSM_STATE" | cut -d ' ' -f 2 | cut -d '(' -f 1`
# if [ "$state" == "FSM_MAC_INIT_DONE" ]
# then
# echo -e "\033[31mEntered into Normal Mode....\033[0m"
# else
# echo -e "\033[31mUnable to find proc entry...\033[0m"
# fi
else
echo -e "\033[31m !!!!! DANGER !!!!\033[0m"
echo -e "\033[31m Upgrade Failed\033[0m"
echo -e "\033[31m Upgrade Failed\033[0m"
fi
<file_sep>/common_hal/intfdep/usb/osd_usb/linux/onebox_usb_main_osd.c
/**
* @file onebox_usb_main_osd.c
* @author
* @version 1.0
*
* @section LICENSE
*
* This software embodies materials and concepts that are confidential to Redpine
* Signals and is made available solely pursuant to the terms of a written license
* agreement with Redpine Signals
*
* @section DESCRIPTION
*
* The file contains Generic HAL changes for USB.
*/
#include "onebox_common.h"
#include <linux/usb.h>
typedef struct urb_context_s {
PONEBOX_ADAPTER adapter;
netbuf_ctrl_block_t *netbuf_addr;
uint8 ep_num;
} urb_context_t;
static PONEBOX_ADAPTER adapter;
ONEBOX_EXTERN int onebox_register_os_intf_operations(struct onebox_os_intf_operations *os_intf_ops);
ONEBOX_STATUS onebox_usb_sg_card_write(PONEBOX_ADAPTER adapter, void *buf,uint16 len,uint8 ep_num);
ONEBOX_EXTERN uint8 *ap_mac_addr;
static uint32 fw;
ONEBOX_STATUS onebox_gspi_init(PONEBOX_ADAPTER adapter);
int onebox_probe (struct usb_interface *pfunction,
const struct usb_device_id *id
);
static uint8 *segment[2];
static uint32 write_fail;
VOID onebox_disconnect (struct usb_interface *pfunction);
uint32 onebox_find_bulkInAndOutEndpoints (struct usb_interface *interface, PONEBOX_ADAPTER rsi_dev);
ONEBOX_STATUS onebox_usb_card_write(PONEBOX_ADAPTER adapter, void *buf, uint16 len, uint8 ep_num);
static const struct usb_device_id onebox_IdTable[] =
{
{ USB_DEVICE(0x0303, 0x0100) },
{ USB_DEVICE(0x041B, 0x0301) },
{ USB_DEVICE(0x041B, 0x0201) },
{ USB_DEVICE(0x041B, 0x9113) },
{ USB_DEVICE(0x1618, 0x9113) },
#ifdef GDVR_DRV
{ USB_DEVICE(0x041B, 0x9330) },
#endif
{ /* Blank */},
};
ONEBOX_STATIC struct usb_driver onebox_driver =
{
.name = "Onebox-USB WLAN",
.probe = onebox_probe,
.disconnect = onebox_disconnect,
.id_table = onebox_IdTable,
};
static ONEBOX_STATUS ulp_read_write(PONEBOX_ADAPTER adapter, uint16 addr, uint16 *data, uint16 len_in_bits)
{
if((master_reg_write(adapter, GSPI_DATA_REG1, ((addr << 6) | (data[1] & 0x3f)), 2) < 0)) {
goto fail;
}
if((master_reg_write(adapter, GSPI_DATA_REG0, *(uint16 *)&data[0], 2)) < 0) {
goto fail;
}
if((onebox_gspi_init(adapter)) < 0) {
goto fail;
}
if((master_reg_write(adapter, GSPI_CTRL_REG1, ((len_in_bits - 1) | GSPI_TRIG), 2)) < 0) {
goto fail;
}
msleep(10);
return ONEBOX_STATUS_SUCCESS;
fail:
return ONEBOX_STATUS_FAILURE;
}
ONEBOX_STATUS onebox_gspi_init(PONEBOX_ADAPTER adapter)
{
uint32 gspi_ctrl_reg0_val;
//! RF control reg
//! clk_ratio [3:0]
/* Programming gspi frequency = soc_frequency / 2 */
/* TODO Warning : ULP seemed to be not working
* well at high frequencies. Modify accordingly */
gspi_ctrl_reg0_val = 0x4;
//! csb_setup_time [5:4]
gspi_ctrl_reg0_val |= 0x10;
//! csb_hold_time [7:6]
gspi_ctrl_reg0_val |= 0x40;
//! csb_high_time [9:8]
gspi_ctrl_reg0_val |= 0x100;
//! spi_mode [10]
gspi_ctrl_reg0_val |= 0x000;
//! clock_phase [11]
gspi_ctrl_reg0_val |= 0x000;
/* Initializing GSPI for ULP read/writes */
return master_reg_write(adapter, GSPI_CTRL_REG0, gspi_ctrl_reg0_val, 2);
}
/**
* This function resets and re-initializes the card.
*
* @param Pointer to usb_func.
* @VOID
*/
static void onebox_reset_card(PONEBOX_ADAPTER adapter)
{
uint16 temp[4] = {0};
*(uint32 *)temp = 2;
printk("%s %d\n",__func__,__LINE__);
if((ulp_read_write(adapter, WATCH_DOG_TIMER_1, &temp[0], 32)) < 0) {
goto fail;
}
*(uint32 *)temp = 0;
printk("%s %d\n",__func__,__LINE__);
if((ulp_read_write(adapter, WATCH_DOG_TIMER_2, temp, 32)) < 0) {
goto fail;
}
*(uint32 *)temp = 50;
printk("%s %d\n",__func__,__LINE__);
if((ulp_read_write(adapter, WATCH_DOG_DELAY_TIMER_1, temp, 32)) < 0) {
goto fail;
}
*(uint32 *)temp = 0;
printk("%s %d\n",__func__,__LINE__);
if((ulp_read_write(adapter, WATCH_DOG_DELAY_TIMER_2, temp, 32)) < 0) {
goto fail;
}
*(uint32 *)temp = ((0xaa000) | RESTART_WDT | BYPASS_ULP_ON_WDT);
printk("%s %d\n",__func__,__LINE__);
if((ulp_read_write(adapter, WATCH_DOG_TIMER_ENABLE, temp, 32)) < 0) {
goto fail;
}
return;
fail:
printk("Reset card Failed\n");
return;
}
/**
* This function is called by kernel when the driver provided
* Vendor and device IDs are matched. All the initialization
* work is done here.
*
* @param Pointer to sdio_func structure.
* @param Pointer to sdio_device_id structure.
* @return SD_SUCCESS in case of successful initialization or
* a negative error code signifying failure.
*/
int onebox_probe(struct usb_interface *pfunction, const struct usb_device_id *id)
{
struct onebox_coex_osi_operations *coex_osi_ops = onebox_get_coex_osi_operations();
struct onebox_osi_host_intf_operations *osi_host_intf_ops = onebox_get_osi_host_intf_operations();
struct onebox_osd_host_intf_operations *osd_host_intf_ops = onebox_get_osd_host_intf_operations();
struct onebox_os_intf_operations *os_intf_ops = onebox_get_os_intf_operations_from_origin();
struct driver_assets *d_assets = onebox_get_driver_asset();
/* Register gpl related os interface operations */
onebox_register_os_intf_operations(os_intf_ops);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Initialization function called\n"), __func__));
adapter = os_intf_ops->onebox_mem_zalloc(sizeof(ONEBOX_ADAPTER),GFP_KERNEL);
if(adapter==NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("%s:Memory allocation for adapter failed\n"), __func__));
goto fail;
}
os_intf_ops->onebox_memset(adapter, 0, sizeof(ONEBOX_ADAPTER));
/*Claim the usb interface*/ /* Need to check whether it is needed or not */
//FIXME://onebox_usb_claim_host(pfunction);
segment[0] = (uint8 *)kmalloc(2048, GFP_ATOMIC);//FIXME:
segment[1] = (uint8 *)kmalloc(2048, GFP_ATOMIC);//FIXME:
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,
(TEXT("Initialized HAL/CORE/DEV_DEPENDENT Operations\n")));
//printk("PROBE: In %s Line %d adapter = %p usbdev = %p\n", __func__, __LINE__, adapter, adapter->usbdev);
adapter->usbdev = interface_to_usbdev(pfunction);
//printk("PROBE: In %s Line %d usbdev = %p\n", __func__, __LINE__, adapter->usbdev);
if(adapter->usbdev == NULL)
{
return ONEBOX_TRUE;
}
if (onebox_find_bulkInAndOutEndpoints (pfunction, adapter))
{
printk ("Error2\n");
goto fail;
}
//printk("PROBE: In %s Line %d adapter = %p usbdev = %p\n", __func__, __LINE__, adapter, adapter->usbdev);
/* storing our device information in interface device for future refrences */
usb_set_intfdata(pfunction, adapter);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Enabled the interface\n"), __func__));
/* Initialise the Core and device dependent operations */
adapter->coex_osi_ops = coex_osi_ops;
adapter->osd_host_intf_ops = osd_host_intf_ops;
adapter->osi_host_intf_ops = osi_host_intf_ops;
adapter->os_intf_ops = os_intf_ops;
adapter->pfunction = pfunction;
d_assets->global_priv = (void *)adapter;
d_assets->pfunc = (void *)pfunction;
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Context setting suceeded\n"), __func__));
adapter->DataRcvPacket = (uint8*)os_intf_ops->onebox_mem_zalloc((ONEBOX_RCV_BUFFER_LEN * 4),
GFP_KERNEL|GFP_DMA);
if(adapter->DataRcvPacket==NULL)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("%s:Memory allocation for receive buffer failed\n"), __func__));
goto fail;
}
os_intf_ops->onebox_init_static_mutex(&adapter->sdio_interrupt_lock);
os_intf_ops->onebox_init_static_mutex(&adapter->usb_dev_sem);
os_intf_ops->onebox_init_dyn_mutex(&adapter->transmit_lock);
/* coex */
if(adapter->coex_osi_ops->onebox_common_hal_init(d_assets, adapter) != ONEBOX_STATUS_SUCCESS) {
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("%s Line %d: Failed to initialize common HAL\n"), __func__, __LINE__));
goto fail;
}
os_intf_ops->onebox_init_event(&(adapter->usb_rx_scheduler_event));
if (adapter->osi_host_intf_ops->onebox_init_host_interface(adapter)!= ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("%s:Failed to init slave regs\n"), __func__));
os_intf_ops->onebox_mem_free(adapter->DataRcvPacket);
goto fail;
}
/*** Receive thread */
adapter->rx_usb_urb[0] = usb_alloc_urb(0, GFP_KERNEL);
adapter->rx_usb_urb[1] = usb_alloc_urb(0, GFP_KERNEL);
adapter->tx_usb_urb[0] = usb_alloc_urb(0, GFP_KERNEL);
adapter->tx_usb_urb[1] = usb_alloc_urb(0, GFP_KERNEL);
adapter->os_intf_ops->onebox_init_event(&(adapter->usb_tx_event));
//adapter->rx_usb_urb[0]->transfer_buffer = adapter->DataRcvPacket;
adapter->TransmitBlockSize = 252;
adapter->ReceiveBlockSize = 252;
if (os_intf_ops->onebox_init_rx_thread(&(adapter->usb_rx_scheduler_thread_handle),
"RX-Thread",
0,
coex_osi_ops->onebox_usb_rx_scheduler_thread,
adapter) != ONEBOX_STATUS_SUCCESS)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("%s: Unable to initialize thrd\n"), __func__));
os_intf_ops->onebox_mem_free(adapter->DataRcvPacket);
goto fail;
}
printk("Receive thread started successfully\n");
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Initialized thread & Event\n"), __func__));
/* start the receive thread */
os_intf_ops->onebox_start_thread( &(adapter->usb_rx_scheduler_thread_handle));
coex_osi_ops->onebox_read_reg_params(adapter);
/*To verify whether Fw is already downloaded */
master_reg_read(adapter, MISC_REG, &fw, 2);//read 12 register
fw &= 1;
if (!(fw))
{
if(adapter->fw_load_mode == FLASH_RAM_NO_SBL) {
if((master_reg_write (adapter,MISC_REG,0x0,2)) < 0) {
printk("Writing into address MISC_REG addr 0x41050012 Failed\n");
//goto fail;
}
}
if(coex_osi_ops->onebox_device_init(adapter, 1)) /* Load firmware */
{
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s:Failed in device initialization\n"), __func__));
//goto fail;
}
if(adapter->fw_load_mode == FLASH_RAM_NO_SBL) {
if((master_reg_write (adapter,ROM_PC_RESET_ADDRESS,0xab,1)) < 0) {
printk("Resetting ROM PC Failed\n");
//goto fail;
}
}
}
adapter->osd_host_intf_ops->onebox_rcv_urb_submit(adapter,
adapter->rx_usb_urb[0], 1);
adapter->osd_host_intf_ops->onebox_rcv_urb_submit(adapter,
adapter->rx_usb_urb[1], 2);
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: master_reg_write done\n"), __func__));
d_assets->card_state = GS_CARD_ABOARD;
return ONEBOX_FALSE;
fail:
#if KERNEL_VERSION_BTWN_2_6_(18, 26)
adapter->os_intf_ops->onebox_kill_thread(&adapter->sdio_scheduler_thread_handle);
#elif KERNEL_VERSION_GREATER_THAN_2_6_(27)
adapter->os_intf_ops->onebox_kill_thread(adapter);
#endif
adapter->os_intf_ops->onebox_remove_proc_entry();
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(TEXT("%s: Failed to initialize...Exiting\n"), __func__));
return ONEBOX_TRUE;
}/* End <onebox_probe> */
static int disconnect_assets(struct driver_assets *d_assets)
{
int s = ONEBOX_STATUS_SUCCESS;
d_assets->card_state = GS_CARD_DETACH;
if (d_assets->techs[WLAN_ID].drv_state == MODULE_ACTIVE) {
d_assets->techs[WLAN_ID].drv_state = MODULE_INSERTED;
if (d_assets->techs[WLAN_ID].disconnect) {
d_assets->techs[WLAN_ID].disconnect();
}
}
if (d_assets->techs[BT_ID].drv_state == MODULE_ACTIVE) {
d_assets->techs[BT_ID].drv_state = MODULE_INSERTED;
if (d_assets->techs[BT_ID].disconnect) {
d_assets->techs[BT_ID].disconnect();
}
}
if (d_assets->techs[ZB_ID].drv_state == MODULE_ACTIVE) {
d_assets->techs[ZB_ID].drv_state = MODULE_INSERTED;
if (d_assets->techs[ZB_ID].disconnect) {
d_assets->techs[ZB_ID].disconnect();
}
}
return s;
}
/**
* This function performs the reverse of the probe function..
*
* @param Pointer to sdio_func structure.
* @param Pointer to sdio_device_id structure.
* @return VOID.
*/
VOID onebox_disconnect ( struct usb_interface *pfunction)
{
struct onebox_os_intf_operations *os_intf_ops;
struct driver_assets *d_assets =
onebox_get_driver_asset();
//PONEBOX_ADAPTER adapter = usb_get_intfdata(pfunction);
//printk("PROBE: In %s Line %d adapter = %p\n", __func__, __LINE__, adapter);
if (!adapter)
{
ONEBOX_DEBUG(ONEBOX_ZONE_ERROR,(" Adapter is NULL \n"));
return;
}
onebox_reset_card(adapter);
//printk("PROBE: In %s Line %d adapter = %p dev = %p\n", __func__, __LINE__, adapter, dev);
os_intf_ops = onebox_get_os_intf_operations_from_origin();
FUNCTION_ENTRY(ONEBOX_ZONE_INFO);
os_intf_ops->onebox_set_event(&adapter->usb_tx_event);
os_intf_ops->onebox_delete_event(&(adapter->usb_tx_event));
/* Remove upper layer protocols firstly */
disconnect_assets(d_assets);
#ifdef USE_WORKQUEUES
flush_workqueue(adapter->int_work_queue);
destroy_workqueue(adapter->int_work_queue);
adapter->os_intf_ops->onebox_queue_purge(&adapter->deferred_rx_queue);
#endif
#ifdef USE_TASKLETS
tasklet_kill(&adapter->int_bh_tasklet);
#endif
os_intf_ops->onebox_mem_free(adapter->DataRcvPacket);
os_intf_ops->onebox_kill_thread(adapter);
os_intf_ops->onebox_kill_rx_thread(adapter);
os_intf_ops->onebox_delete_event(&(adapter->coex_tx_event));
os_intf_ops->onebox_delete_event(&(adapter->flash_event));
/* deinit device */
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: calling device deinitialization\n"), __func__));
adapter->coex_osi_ops->onebox_device_deinit(adapter);
/* Remove the proc file system created for the device*/
adapter->os_intf_ops->onebox_remove_proc_entry();
ONEBOX_DEBUG(ONEBOX_ZONE_INIT,(TEXT("%s: Uninitialized Procfs\n"), __func__));
/*Disable the interface*/
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,(TEXT("%s: Disabling the interface\n"), __func__));
/* Release the interrupt handler */
adapter->stop_card_write = 2; //stopping all writes after deinit
usb_free_urb(adapter->rx_usb_urb[0]);
usb_free_urb(adapter->rx_usb_urb[1]);
usb_free_urb(adapter->tx_usb_urb[0]);
usb_free_urb(adapter->tx_usb_urb[1]);
os_intf_ops->onebox_mem_free(adapter);
if(write_fail)
{
write_fail = 0;
}
FUNCTION_EXIT(ONEBOX_ZONE_INFO);
return;
}/* End <onebox_disconnect> */
/**
* This function reads one byte of information from a register.
*
* @param Pointer to Driver adapter structure.
* @param Function Number.
* @param Address of the register.
* @param Pointer to the data that stores the data read.
* @return On success ONEBOX_STATUS_SUCCESS else ONEBOX_STATUS_FAILURE.
*/
ONEBOX_STATUS read_register(PONEBOX_ADAPTER ext_adapter, uint32 Addr,
uint8 *data)
{
#if ((defined USE_USB_INTF) && (defined USB_BUFFER_STATUS_INDI))
struct driver_assets *d_assets = onebox_get_driver_asset();
uint16 data1 = 0;
PONEBOX_ADAPTER adapter = (PONEBOX_ADAPTER)d_assets->global_priv;
master_reg_read(adapter->usbdev, Addr, &data1, 2);//read single byte from register
*data = *(uint8 *)&data1;
#endif
return ONEBOX_STATUS_SUCCESS;
}/* End <read_register> */
/**
* This function writes one byte of information into a register.
*
* @param Pointer to Driver adapter structure.
* @param Function Number.
* @param Address of the register.
* @param Pointer to the data tha has to be written.
* @return On success ONEBOX_STATUS_SUCCESS else ONEBOX_STATUS_FAILURE.
*/
int write_register(PONEBOX_ADAPTER adapter,uint8 reg_dmn,uint32 Addr,uint8 *data)
{
return ONEBOX_STATUS_SUCCESS;
}/* End <write_register> */
/**
* This function read multiple bytes of information from the SD card.
*
* @param Pointer to Driver adapter structure.
* @param Function Number.
* @param Address of the register.
* @param Length of the data to be read.
* @param Pointer to the read data.
* @return On success ONEBOX_STATUS_SUCCESS else ONEBOX_STATUS_FAILURE.
*/
ONEBOX_STATUS read_register_multiple(PONEBOX_ADAPTER adapter,
uint32 Addr,
uint32 Count,
uint8 *data )
{
return ONEBOX_STATUS_SUCCESS;
}/* End <read_register_multiple> */
/**
* This function writes multiple bytes of information to the SD card.
*
* @param Pointer to Driver adapter structure.
* @param Function Number.
* @param Address of the register.
* @param Length of the data.
* @param Pointer to the data that has to be written.
* @return On success ONEBOX_STATUS_SUCCESS else ONEBOX_STATUS_FAILURE.
*/
ONEBOX_STATUS write_register_multiple(PONEBOX_ADAPTER adapter,
uint32 Addr,
uint8 *data,
uint32 Count
)
{
ONEBOX_STATUS status_l;
status_l = 0;
if (write_fail)
{
return status_l;
}
if(adapter == NULL || Addr == 0 )
{
printk("PROBE: In %s Line %d unable to card write check\n", __func__, __LINE__);
return ONEBOX_STATUS_FAILURE;
}
status_l = onebox_usb_sg_card_write(adapter, data, Count, Addr);
return status_l;
} /* End <write_register_multiple> */
ONEBOX_STATUS onebox_usb_sg_card_write(PONEBOX_ADAPTER adapter, void *buf, uint16 len, uint8 ep_num)
{
ONEBOX_STATUS status_l;
uint8 *seg;
status_l = 0;
if (write_fail)
{
printk("%s: Unable to write, device not responding endpoint:%d\n", __func__, ep_num);
return status_l;
}
if ((adapter->coex_mode == WIFI_ZIGBEE) && (ep_num == 2)) {
seg = segment[0];
memcpy(seg, buf, len);
} else {
seg = segment[0];
memset(seg, 0, ONEBOX_USB_TX_HEAD_ROOM);
memcpy(seg + ONEBOX_USB_TX_HEAD_ROOM, buf, len);
len += ONEBOX_USB_TX_HEAD_ROOM;
}
status_l = onebox_usb_card_write(adapter, seg, len, ep_num);
return status_l;
}
void usb_tx_done_handler(struct urb *urb)
{
PONEBOX_ADAPTER adapter = urb->context;
if (urb->status)
{
ONEBOX_DEBUG (ONEBOX_ZONE_ERROR,
("USB CARD WRITE FAILED WITH ERROR CODE :%10d length %d\n", urb->status, urb->actual_length));
ONEBOX_DEBUG (ONEBOX_ZONE_ERROR, ("PKT Tried to Write is \n"));
adapter->coex_osi_ops->onebox_dump(ONEBOX_ZONE_ERROR, urb->transfer_buffer, urb->actual_length);
write_fail = 1;
return;
}
adapter->os_intf_ops->onebox_set_event(&adapter->usb_tx_event);
}
ONEBOX_STATUS onebox_usb_card_write(PONEBOX_ADAPTER adapter, void *buf, uint16 len, uint8 ep_num)
{
ONEBOX_STATUS status_l;
adapter->tx_usb_urb[0]->transfer_flags |= URB_ZERO_PACKET;
usb_fill_bulk_urb (adapter->tx_usb_urb[0],
adapter->usbdev,
usb_sndbulkpipe (adapter->usbdev,
adapter->bulk_out_endpointAddr[ep_num - 1]),
(void *)buf, len, usb_tx_done_handler,
adapter);
status_l = usb_submit_urb(adapter->tx_usb_urb[0], GFP_KERNEL);
if (status_l < 0)
{
ONEBOX_DEBUG (ONEBOX_ZONE_ERROR, ("Failed To Submit URB Status :%10d \n", status_l));
write_fail = 1;
return status_l;
}
if(adapter->os_intf_ops->onebox_wait_event(&adapter->usb_tx_event, 60*HZ)/*60 secs*/) {
adapter->os_intf_ops->onebox_reset_event(&adapter->usb_tx_event);
return ONEBOX_STATUS_SUCCESS;
}
ONEBOX_DEBUG (ONEBOX_ZONE_ERROR, ("USB CARD WRITE FAILED WITH ERROR CODE :%10d \n", status_l));
adapter->coex_osi_ops->onebox_dump(ONEBOX_ZONE_ERROR,
adapter->tx_usb_urb[0]->transfer_buffer,
adapter->tx_usb_urb[0]->actual_length);
adapter->os_intf_ops->onebox_reset_event(&adapter->usb_tx_event);
write_fail = 1;
return ONEBOX_STATUS_FAILURE;
}
/**
* This function registers the client driver.
*
* @param VOID.
* @return 0 if success else a negative number.
*/
int register_driver(void)
{
return (usb_register(&onebox_driver));
}
/**
* This function unregisters the client driver.
*
* @param VOID.
* @return VOID.
*/
void unregister_driver(void)
{
usb_deregister(&onebox_driver);
}
/*FUNCTION*********************************************************************
Function Name: onebox_remove
Description: Dummy for linux sdio
Returned Value: None
Parameters:
----------------------------+-----+-----+-----+------------------------------
Name | I/P | O/P | I/O | Purpose
----------------------------+-----+-----+-----+------------------------------
None
******************************************************************************/
ONEBOX_STATUS remove(void)
{
/**Dummy for Linux*/
//FIXME: Kill all the VAP'S
return 0;
}
/**
* This function initializes the bulk endpoints
* to the device.
*
* @param
* interface Interface descriptor
* @param
* rsi_dev driver control block
* @return
* 0 on success and -1 on failure
*/
uint32 onebox_find_bulkInAndOutEndpoints (struct usb_interface *interface, PONEBOX_ADAPTER rsi_dev)
{
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
int buffer_size;
int ret_val = -ENOMEM, i, bep_found = 0, binep_found = 0;
uint8 ep_num = 0;
uint32 pipe = 0;
printk ("{%s+}\n", __FUNCTION__);
/* set up the endpoint information */
/* check out the endpoints */
/* use only the first bulk-in and bulk-out endpoints */
if((interface == NULL) || (rsi_dev == NULL))
{
printk ("Null pointer in {%s}\n", __func__);
return ret_val;
}
iface_desc = &(interface->altsetting[0]);
ONEBOX_DEBUG(ONEBOX_ZONE_INFO,
("bNumEndpoints :%08x \n", iface_desc->desc.bNumEndpoints));
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i)
{
endpoint = &(iface_desc->endpoint[i].desc);
ONEBOX_DEBUG (ONEBOX_ZONE_INFO, ("IN LOOP :%08x \n", bep_found));
#if 0
if ((!(rsi_dev->bulk_in_endpointAddr)) &&
(endpoint->bEndpointAddress & USB_DIR_IN) && /* Direction */
((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK))
{
/* we found a bulk in endpoint */
ONEBOX_DEBUG (ONEBOX_ZONE_INFO, ("IN EP :%08x \n", i));
buffer_size = endpoint->wMaxPacketSize;
//buffer_size = MAX_RX_PKT_SZ;
rsi_dev->bulk_in_size = buffer_size;
rsi_dev->bulk_in_endpointAddr = endpoint->bEndpointAddress;
ep_num = endpoint->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
printk("IN ep num is %d\n",ep_num);
pipe = usb_rcvbulkpipe(adapter->usbdev, ep_num);
printk("IN pipe num is %8x\n",pipe);
pipe = usb_rcvbulkpipe(adapter->usbdev, endpoint->bEndpointAddress);
printk("IN pipe num 2 is %8x\n",pipe);
}
#else
if ((!(rsi_dev->bulk_in_endpointAddr[binep_found])) &&
(endpoint->bEndpointAddress & USB_DIR_IN) && /* Direction */
((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK))
{
/* we found a bulk in endpoint */
ONEBOX_DEBUG (ONEBOX_ZONE_INFO, ("IN EP :%08x \n", i));
buffer_size = endpoint->wMaxPacketSize;
//buffer_size = MAX_RX_PKT_SZ;
rsi_dev->bulk_in_endpointAddr[binep_found] = endpoint->bEndpointAddress;
ep_num = endpoint->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
printk("IN ep num is %d\n",ep_num);
pipe = usb_rcvbulkpipe(adapter->usbdev, ep_num);
printk("IN pipe num is %8x\n",pipe);
pipe = usb_rcvbulkpipe(adapter->usbdev, endpoint->bEndpointAddress);
printk("IN pipe num 2 is %8x\n",pipe);
/* on some platforms using this kind of buffer alloc
* call eliminates a dma "bounce buffer".
*
* NOTE: you'd normally want i/o buffers that hold
* more than one packet, so that i/o delays between
* packets don't hurt throughput.
*/
buffer_size = endpoint->wMaxPacketSize;
rsi_dev->bulk_in_size[binep_found] = buffer_size;
//rsi_dev->tx_urb->transfer_flags = (URB_NO_TRANSFER_DMA_MAP );
binep_found++;
}
#endif
if (!rsi_dev->bulk_out_endpointAddr[bep_found] &&
!(endpoint->bEndpointAddress & USB_DIR_IN) &&
((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK))
{
ONEBOX_DEBUG (ONEBOX_ZONE_INFO, ("OUT EP :%08x \n", i));
/* we found a bulk out endpoint */
rsi_dev->bulk_out_endpointAddr[bep_found] = endpoint->bEndpointAddress;
ep_num = endpoint->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
printk("OUT ep num is %d\n",ep_num);
pipe = usb_sndbulkpipe(adapter->usbdev, ep_num);
printk("OUT pipe num is %8x\n",pipe);
pipe = usb_sndbulkpipe(adapter->usbdev, endpoint->bEndpointAddress);
printk("OUT pipe num 2 is %8x\n",pipe);
/* on some platforms using this kind of buffer alloc
* call eliminates a dma "bounce buffer".
*
* NOTE: you'd normally want i/o buffers that hold
* more than one packet, so that i/o delays between
* packets don't hurt throughput.
*/
buffer_size = endpoint->wMaxPacketSize;
rsi_dev->bulk_out_size[bep_found] = buffer_size;
//rsi_dev->tx_urb->transfer_flags = (URB_NO_TRANSFER_DMA_MAP );
bep_found++;
}
if ((bep_found >= MAX_BULK_EP) || (binep_found >= MAX_BULK_EP))
{
break;
}
}
if (!(rsi_dev->bulk_in_endpointAddr[0] && rsi_dev->bulk_out_endpointAddr[0]))
{
printk ("Couldn't find both bulk-in and bulk-out endpoints");
return ret_val;
} else
{
ONEBOX_DEBUG (ONEBOX_ZONE_INFO, ("EP INIT SUCESS \n"));
}
return 0;
}
/* This function reads the data from given register address
*
* @param
* Adapter Pointer to driver's private data area.
* @param
* reg Address of the register
* @param
* value Value to write
* @param
* len Number of bytes to write
* @return
* none
*/
ONEBOX_STATUS master_reg_read (PONEBOX_ADAPTER adapter, uint32 reg, uint32 * value, uint16 len)
{
uint8 temp_buf[4];
ONEBOX_STATUS status_l;
struct usb_device *usbdev = adapter->usbdev;
status_l = ONEBOX_STATUS_SUCCESS;
len = 2;/* FIXME */
//printk("arguments to ctrl msg usbdev = %p value = %p\n", usbdev, value );
status_l = usb_control_msg (usbdev,
usb_rcvctrlpipe (usbdev, 0),
USB_VENDOR_REGISTER_READ,
USB_TYPE_VENDOR | USB_DIR_IN | USB_RECIP_DEVICE,
((reg & 0xffff0000) >> 16), (reg & 0xffff),
(void *) temp_buf, len, HZ * 5);
*value = (temp_buf[0] | (temp_buf[1] << 8));
if (status_l < 0)
{
ONEBOX_DEBUG (ONEBOX_ZONE_INFO,
("REG READ FAILED WITH ERROR CODE :%010x \n", status_l));
return status_l;
}
ONEBOX_DEBUG (ONEBOX_ZONE_INFO, ("USB REG READ VALUE :%10x \n", *value));
return status_l;
}
/**
* This function writes the given data into the given register address
*
* @param
* Adapter Pointer to driver's private data area.
* @param
* reg Address of the register
* @param
* value Value to write
* @param
* len Number of bytes to write
* @return
* none
*/
ONEBOX_STATUS master_reg_write (PONEBOX_ADAPTER adapter, uint32 reg,
uint32 value, uint16 len)
{
uint8 usb_reg_buf[4];
ONEBOX_STATUS status_l;
struct usb_device *usbdev = adapter->usbdev;
printk("IN %s LINE %d\n",__FUNCTION__,__LINE__);
status_l = ONEBOX_STATUS_SUCCESS;
usb_reg_buf[0] = (value & 0x000000ff);
usb_reg_buf[1] = (value & 0x0000ff00) >> 8;
usb_reg_buf[2] = 0x0;
usb_reg_buf[3] = 0x0;
ONEBOX_DEBUG (ONEBOX_ZONE_INFO, ("USB REG WRITE VALUE :%10x \n", value));
status_l = usb_control_msg (usbdev,
usb_sndctrlpipe (usbdev, 0),
USB_VENDOR_REGISTER_WRITE, USB_TYPE_VENDOR,
((reg & 0xffff0000) >> 16), (reg & 0xffff),
(void *) usb_reg_buf, len, HZ * 5);
if (status_l < 0)
{
ONEBOX_DEBUG (ONEBOX_ZONE_INFO,
("REG WRITE FAILED WITH ERROR CODE :%10d \n", status_l));
}
return status_l;
}
/**
* This function submits the given URB to the USB stack
*
* @param
* Adapter Pointer to driver's private data area.
* @param
* URB URB to submit
* @return
* none
*/
void onebox_rx_urb_submit (PONEBOX_ADAPTER adapter, struct urb *urb, uint8 ep_num)
{
void (*done_handler) (struct urb *);
urb_context_t *context_ptr = adapter->os_intf_ops->onebox_mem_zalloc(sizeof(urb_context_t), GFP_ATOMIC);
context_ptr->adapter = adapter;
context_ptr->netbuf_addr = adapter->os_intf_ops->onebox_alloc_skb(ONEBOX_RCV_BUFFER_LEN);
adapter->os_intf_ops->onebox_add_data_to_skb(context_ptr->netbuf_addr, ONEBOX_RCV_BUFFER_LEN);
context_ptr->ep_num = ep_num;
urb->transfer_buffer = context_ptr->netbuf_addr->data;
adapter->total_usb_rx_urbs_submitted++;
if (ep_num == 1) {
done_handler = onebox_rx_done_handler;
} else {
done_handler = onebox_rx_done_handler;
}
usb_fill_bulk_urb (urb,
adapter->usbdev,
usb_rcvbulkpipe (adapter->usbdev,
adapter->bulk_in_endpointAddr[ep_num - 1]),
urb->transfer_buffer, 2100, done_handler,
context_ptr);
if (usb_submit_urb(urb, GFP_ATOMIC))
{
printk ("submit(bulk rx_urb)");
}
}
/**
* This function is called when a packet is received from
* the stack. This is rx done callback.
*
* @param
* URB Received URB
* @return
* none
*/
void onebox_rx_done_handler (struct urb *urb)
{
uint8 pkt_type = 0;
urb_context_t *context_ptr = urb->context;
PONEBOX_ADAPTER adapter = context_ptr->adapter;
netbuf_ctrl_block_t *netbuf_recv_pkt = context_ptr->netbuf_addr;
//printk("rx_done, status %d, length %d", urb->status, urb->actual_length);
//printk("PROBE: In %s Line %d\n", __func__, __LINE__);
if (urb->status)
{
printk("rx_done, status %d, length %d \n", urb->status, urb->actual_length);
adapter->coex_osi_ops->onebox_dump(ONEBOX_ZONE_ERROR, urb->transfer_buffer, urb->actual_length);
//goto resubmit;
return;
}
adapter->total_usb_rx_urbs_done++;
if (urb->actual_length == 0)
{
printk ("==> ERROR: ZERO LENGTH <==\n");
goto resubmit;
}
//netbuf_recv_pkt->len = urb->actual_length;
adapter->os_intf_ops->onebox_netbuf_trim(netbuf_recv_pkt, urb->actual_length);
if (adapter->Driver_Mode == QSPI_FLASHING ||
adapter->flashing_mode_on) {
pkt_type = COEX_PKT;
} else {
if (context_ptr->ep_num == 1) {
pkt_type = WLAN_PKT;
} else if (context_ptr->ep_num == 2) {
if (adapter->coex_mode == WIFI_BT_LE || adapter->coex_mode == WIFI_BT_CLASSIC)
pkt_type = BT_PKT;
else if (adapter->coex_mode == WIFI_ZIGBEE)
pkt_type = ZIGB_PKT;
else
pkt_type = WLAN_PKT;
}
}
netbuf_recv_pkt->rx_pkt_type = pkt_type;
//printk("%s: Packet type Received = %d\n", __func__, pkt_type);
process_usb_rcv_pkt(adapter, netbuf_recv_pkt, pkt_type);
adapter->os_intf_ops->onebox_mem_free(context_ptr);
onebox_rx_urb_submit(adapter, urb, context_ptr->ep_num);
return;
resubmit:
adapter->os_intf_ops->onebox_mem_free(context_ptr);
adapter->os_intf_ops->onebox_free_pkt(adapter, netbuf_recv_pkt, 0);
onebox_rx_urb_submit(adapter, urb, context_ptr->ep_num);
return;
}
/**
* This function writes multiple bytes of information to the SD card.
*
* @param Pointer to Driver adapter structure.
* @param Function Number.
* @param Address of the register.
* @param Length of the data.
* @param Pointer to the data that has to be written.
* @return On success ONEBOX_STATUS_SUCCESS else ONEBOX_STATUS_FAILURE.
*/
ONEBOX_STATUS write_ta_register_multiple(PONEBOX_ADAPTER adapter,
uint32 Addr,
uint8 *data,
uint32 Count
)
{
ONEBOX_STATUS status_l;
uint8 *buf;
uint32 transfer;
//printk("PROBE: In %s Line %d\n", __func__, __LINE__);
buf = kzalloc(4096, GFP_KERNEL);
if (!buf)
{
printk("%s: Failed to allocate memory\n",__func__);
return -ENOMEM;
}
status_l = ONEBOX_STATUS_SUCCESS;
while (Count)
{
transfer = min_t(int, Count, 4096);
printk("In %s Line %d transfer %d\n ",__func__,__LINE__,transfer);
memcpy(buf, data, transfer);
printk("ctrl pipe number is %8x\n",usb_sndctrlpipe(adapter->usbdev, 0));
status_l = usb_control_msg (adapter->usbdev,
usb_sndctrlpipe (adapter->usbdev, 0),
USB_VENDOR_REGISTER_WRITE, USB_TYPE_VENDOR,
((Addr & 0xffff0000) >> 16), (Addr & 0xffff),
(void *) buf, transfer, HZ * 5);
if (status_l < 0)
{
ONEBOX_DEBUG (ONEBOX_ZONE_INFO,
("REG WRITE FAILED WITH ERROR CODE :%10d \n", status_l));
kfree(buf);
return status_l;
}
else
{
Count -= transfer;
data += transfer;
Addr += transfer;
}
}
ONEBOX_DEBUG (ONEBOX_ZONE_INFO,
("REG WRITE WAS SUCCESSFUL :%10d \n", status_l));
kfree(buf);
return 0;
} /* End <write_register_multiple> */
/**
* This function reads multiple bytes of information to the SD card.
*
* @param Pointer to Driver adapter structure.
* @param Function Number.
* @param Address of the register.
* @param Length of the data.
* @param Pointer to the data that has to be written.
* @return On success ONEBOX_STATUS_SUCCESS else ONEBOX_STATUS_FAILURE.
*/
ONEBOX_STATUS read_ta_register_multiple(PONEBOX_ADAPTER adapter,
uint32 Addr,
uint8 *data,
uint32 Count
)
{
ONEBOX_STATUS status_l;
uint8 *buf;
uint32 transfer;
//printk("PROBE: In %s Line %d\n", __func__, __LINE__);
buf = kzalloc(4096, GFP_KERNEL);
if (!buf)
{
//printk("PROBE: Failed to allocate memory\n");
return -ENOMEM;
}
status_l = ONEBOX_STATUS_SUCCESS;
while (Count)
{
transfer = min_t(int, Count, 4096);
printk("In %s Line %d transfer %d count %d \n ",__func__,__LINE__,transfer,Count);
status_l = usb_control_msg (adapter->usbdev,
usb_rcvctrlpipe (adapter->usbdev, 0),
USB_VENDOR_REGISTER_READ,
USB_TYPE_VENDOR | USB_DIR_IN | USB_RECIP_DEVICE,
((Addr & 0xffff0000) >> 16), (Addr & 0xffff),
(void *) buf, transfer, HZ * 5);
memcpy(data, buf, transfer);
adapter->coex_osi_ops->onebox_dump(ONEBOX_ZONE_ERROR, buf, transfer);
if (status_l < 0)
{
ONEBOX_DEBUG (ONEBOX_ZONE_INFO,
("REG WRITE FAILED WITH ERROR CODE :%10d \n", status_l));
kfree(buf);
return status_l;
}
else
{
Count -= transfer;
data += transfer;
Addr += transfer;
}
}
ONEBOX_DEBUG (ONEBOX_ZONE_INFO,
("MASTER READ IS SUCCESSFUL :%10d \n", status_l));
kfree(buf);
return 0;
} /* End <write_register_multiple> */
EXPORT_SYMBOL(onebox_rx_urb_submit);
<file_sep>/release/bt_remove.sh
#hciconfig hci0 down
rmmod onebox_bt_gpl
rmmod onebox_bt_nongpl
| 9357d3090c7586a8cc7bdc5bcb430b3c71aa1126 | [
"C",
"Makefile",
"Shell"
]
| 60 | Shell | ngrundback/redpine | f34d93bab2ee05d8b751d15a1e3a1d8e60803524 | 6ca81d99fa242b3b8f6838e8f5776b4d46f770f2 |
refs/heads/master | <repo_name>Zenithar/go-nest<file_sep>/pkg/util/helpers.go
package util
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
)
const (
DefaultErrorExitCode = 1
)
// ErrExit may be passed to CheckError to instruct it to output nothing but exit with
// status code 1.
var ErrExit = fmt.Errorf("exit")
// CheckErr prints a user friendly error to STDERR and exits with a non-zero
// exit code. Unrecognized errors will be printed with an "error: " prefix.
//
// This method is generic to the command in use and may be used by non-Kubectl
// commands.
func CheckErr(err error) {
if err == nil {
return
}
switch {
case err == ErrExit:
os.Exit(DefaultErrorExitCode)
default:
panic(err)
}
}
// DefaultSubCommandRun prints a command's help string to the specified output if no
// arguments (sub-commands) are provided, or a usage error otherwise.
func DefaultSubCommandRun(c *cobra.Command, args []string) {
c.SetOutput(os.Stderr)
RequireNoArguments(c, args)
c.Help()
CheckErr(ErrExit)
}
// RequireNoArguments exits with a usage error if extra arguments are provided.
func RequireNoArguments(c *cobra.Command, args []string) {
if len(args) > 0 {
CheckErr(UsageErrorf(c, "unknown command %q", strings.Join(args, " ")))
}
}
// UsageErrorf displays the error message as command answer
func UsageErrorf(cmd *cobra.Command, format string, args ...interface{}) error {
msg := fmt.Sprintf(format, args...)
return fmt.Errorf("%s\nSee '%s -h' for help and examples", msg, cmd.CommandPath())
}
<file_sep>/pkg/handler/handler.go
package handler
import (
"os"
"strings"
)
// HandlePluginCommand receives a pluginHandler and command-line arguments and attempts to find
// a plugin executable on the PATH that satisfies the given arguments.
func HandlePluginCommand(pluginHandler PluginHandler, cmdArgs []string) error {
remainingArgs := []string{} // all "non-flag" arguments
for idx := range cmdArgs {
if strings.HasPrefix(cmdArgs[idx], "-") {
break
}
remainingArgs = append(remainingArgs, strings.Replace(cmdArgs[idx], "-", "_", -1))
}
foundBinaryPath := ""
// attempt to find binary, starting at longest possible name with given cmdArgs
for len(remainingArgs) > 0 {
path, found := pluginHandler.Lookup(strings.Join(remainingArgs, "-"))
if !found {
remainingArgs = remainingArgs[:len(remainingArgs)-1]
continue
}
foundBinaryPath = path
break
}
if len(foundBinaryPath) == 0 {
return nil
}
// invoke cmd binary relaying the current environment and args given
// remainingArgs will always have at least one element.
// execve will make remainingArgs[0] the "binary name".
if err := pluginHandler.Execute(foundBinaryPath, append([]string{foundBinaryPath}, cmdArgs[len(remainingArgs):]...), os.Environ()); err != nil {
return err
}
return nil
}
<file_sep>/cmd/nest-bird/cmd/root.go
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
func NewDefaultBirdCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "nest-bird",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Piou piou")
},
}
return cmd
}
<file_sep>/go.mod
module go.zenithar.org/nest
go 1.12
require (
github.com/MakeNowJust/heredoc v0.0.0-20171113091838-e9091a26100e
github.com/russross/blackfriday v1.5.2
github.com/spf13/cobra v0.0.5
)
<file_sep>/README.md
# Nest
Kubectl plugin pattern using cobra command.
No credits to me, code completly extracted from Kubectl source code.
<file_sep>/cmd/nest/cmd/root.go
package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
"go.zenithar.org/nest/pkg/cmd/plugin"
"go.zenithar.org/nest/pkg/handler"
)
func newNestCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "nest",
}
cmd.AddCommand(plugin.NewCmdPlugin())
return cmd
}
func NewDefaultNestCommand() *cobra.Command {
cmd := newNestCommand()
pluginHandler := handler.NewDefaultPluginHandler([]string{"nest"})
if len(os.Args) > 1 {
cmdPathPieces := os.Args[1:]
// only look for suitable extension executables if
// the specified command does not already exist
if _, _, err := cmd.Find(cmdPathPieces); err != nil {
if err := handler.HandlePluginCommand(pluginHandler, cmdPathPieces); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
}
}
return cmd
}
<file_sep>/pkg/handler/api.go
package handler
// PluginHandler is capable of parsing command line arguments
// and performing executable filename lookups to search
// for valid plugin files, and execute found plugins.
type PluginHandler interface {
// exists at the given filename, or a boolean false.
// Lookup will iterate over a list of given prefixes
// in order to recognize valid plugin filenames.
// The first filepath to match a prefix is returned.
Lookup(filename string) (string, bool)
// Execute receives an executable's filepath, a slice
// of arguments, and a slice of environment variables
// to relay to the executable.
Execute(executablePath string, cmdArgs, environment []string) error
}
// DefaultPluginHandler implements PluginHandler
type DefaultPluginHandler struct {
ValidPrefixes []string
}
<file_sep>/pkg/handler/default.go
package handler
import (
"fmt"
"os/exec"
"syscall"
)
// NewDefaultPluginHandler instantiates the DefaultPluginHandler with a list of
// given filename prefixes used to identify valid plugin filenames.
func NewDefaultPluginHandler(validPrefixes []string) *DefaultPluginHandler {
return &DefaultPluginHandler{
ValidPrefixes: validPrefixes,
}
}
// Lookup implements PluginHandler
func (h *DefaultPluginHandler) Lookup(filename string) (string, bool) {
for _, prefix := range h.ValidPrefixes {
path, err := exec.LookPath(fmt.Sprintf("%s-%s", prefix, filename))
if err != nil || len(path) == 0 {
continue
}
return path, true
}
return "", false
}
// Execute implements PluginHandler
func (h *DefaultPluginHandler) Execute(executablePath string, cmdArgs, environment []string) error {
return syscall.Exec(executablePath, cmdArgs, environment)
}
<file_sep>/cmd/nest-snake/cmd/root.go
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
func NewDefaultSnakeCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "nest-snake",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("SsssSSssSsSSss")
},
}
return cmd
}
| 49ebe58719f75b63de7dcae240a9c3ebfdb460d9 | [
"Markdown",
"Go Module",
"Go"
]
| 9 | Go | Zenithar/go-nest | 9e3a5642bac2b17987e70c2abfddf196eac17c35 | 6f7df5c13d2fd15b0dcbd55c63718ba39f68097d |
refs/heads/master | <repo_name>atomaths/talks<file_sep>/go1-preview/my_new_struct_pkg.go
package my_new_struct_pkg
import (
"fmt"
)
type Struct struct {
Public int
secret int
}
func NewStruct(a int) Struct { // Note: not a pointer.
return Struct{a, a*2}
}
func (s Struct) String() string {
return fmt.Sprintf("{%d (secret %d)}", s.Public, s.secret)
}
<file_sep>/url-shortener/key.go
package main
import (
"math/rand"
"time"
)
var keyChar = []byte("<KEY>")
func genKey() string {
rand.Seed(time.Nanoseconds())
var k int
key := make([]byte, 5)
for i := 0; i < 5; i++ {
k = rand.Intn(len(keyChar))
key[i] = keyChar[k]
}
return string(key[:])
}
<file_sep>/go1-preview/Makefile
include $(GOROOT)/src/Make.inc
#TARG=my_new_struct_pkg
#GOFILES=\
my_new_struct_pkg.go\
# build 하기
#include $(GOROOT)/src/Make.cmd
# package 만들기
#include $(GOROOT)/src/Make.pkg
all: append assert close composite_literals copying_structs_with_unexported_fields deleting_from_maps equality_of_structs_and_arrays function_and_map_equality goroutines_during_init multiple_assignment the_rune_type returns_and_shadowed_variables time error
append:
$(GC) [email protected] && $(LD) -o $@ [email protected]
assert:
$(GC) [email protected] && $(LD) -o $@ [email protected]
close:
$(GC) [email protected] && $(LD) -o $@ [email protected]
composite_literals:
$(GC) [email protected] && $(LD) -o $@ [email protected]
copying_structs_with_unexported_fields:
$(GC) [email protected] && $(LD) -o $@ [email protected]
deleting_from_maps:
$(GC) [email protected] && $(LD) -o $@ [email protected]
equality_of_structs_and_arrays:
$(GC) [email protected] && $(LD) -o $@ [email protected]
function_and_map_equality:
$(GC) [email protected] && $(LD) -o $@ [email protected]
goroutines_during_init:
$(GC) [email protected] && $(LD) -o $@ [email protected]
multiple_assignment:
$(GC) [email protected] && $(LD) -o $@ [email protected]
the_rune_type:
$(GC) [email protected] && $(LD) -o $@ [email protected]
returns_and_shadowed_variables:
$(GC) [email protected] && $(LD) -o $@ [email protected]
time:
$(GC) [email protected] && $(LD) -o $@ [email protected]
error:
$(GC) [email protected] && $(LD) -o $@ [email protected]
clean:
rm -f *.6 append assert close composite_literals copying_structs_with_unexported_fields deleting_from_maps equality_of_structs_and_arrays function_and_map_equality goroutines_during_init multiple_assignment the_rune_type returns_and_shadowed_variables time error
<file_sep>/go1-preview/deleting_from_maps.go
package main
import (
"fmt"
)
func main() {
var m = map[string]int{"Jan": 31, "Feb":28, "Mar":31, "Apr":40, "May":31}
//m["Jan"] = -1, false // r60.3 방식
//delete(m, "Jan") // Go 1 방식
fmt.Println(m)
for k, v := range m {
// This loop should not assume "Jan" will be visited first.
fmt.Println(k, v)
}
}
<file_sep>/go-tools/demos/test/sqrt_test.go
package sqrt
import (
"fmt"
"math/rand"
"testing"
)
var testCases = []struct {
got int
want int
}{
{got: 1, want: 1},
{got: 2, want: 4},
{got: 9, want: 81},
}
// TextXXX
func TestSqrt(t *testing.T) {
for _, tc := range testCases {
result := Sqrt(tc.got)
if tc.want != result {
t.Errorf("Didn't match: want(%d), result(%d)", tc.want, result)
continue
}
}
}
// BenchMarkXXX
func BenchmarkSqrt(b *testing.B) {
for i := 0; i < b.N; i++ {
Sqrt(random())
}
}
// Example
func ExampleHello() {
fmt.Println("hello")
fmt.Println("goodbye")
// Output:
// hello
// goodbye
}
func random() int {
return rand.Intn(100)
}
<file_sep>/go1-preview/composite_literals.go
package main
import (
"fmt"
"reflect"
)
type Date struct {
month string
day int
}
func main() {
// Struct values, fully qualified; always legal.
holiday1 := []Date{
Date{"Feb", 14},
Date{"Nov", 11},
Date{"Dec", 25},
}
// Struct values, type name elided; always legal.
holiday2 := []Date{
{"Feb", 14},
{"Nov", 11},
{"Dec", 25},
}
// Pointers, fully qualified, always legal.
holiday3 := []*Date{
// []*Date 표현은 pointer Date 타입들의 slice를 가리키므로
// Date{"Feb", 14}와 같이 type *Date가 와야 할 자리에 type Date가 오면 컴파일 에러가 난다
&Date{"Feb", 14},
&Date{"Nov", 11},
&Date{"Dec", 25},
}
// Pointers, type name elided; legal in Go 1.
// Go 1 이전에는 “missing type in composite literal” 에러남.
holiday4 := []*Date{
{"Feb", 14},
{"Nov", 11},
{"Dec", 25},
}
fmt.Println(holiday1)
fmt.Println(holiday2)
fmt.Printf("%v\n", reflect.ValueOf(holiday3))
fmt.Printf("%v\n", holiday4)
}
<file_sep>/go1-preview/the_rune_type.go
package main
import (
"fmt"
"log"
"unicode"
)
func main() {
var ga rune
ga = '\uAC00' // '가'
fmt.Printf("%q\n", ga)
delta := 'δ' // delta has type rune.
var DELTA rune
DELTA = unicode.ToUpper(delta) // delta의 대문자 'Δ' 문자가 리턴
epsilon := unicode.ToLower(DELTA + 1) // DELTA('Δ')에 1을 더하면 Epsilon(대문자)가 나오는데 여기다 ToLower
if epsilon != 'δ'+1 {
log.Fatal("inconsistent casing for Greek")
}
}
<file_sep>/go-tools/demos/run/foo.go
package main
func Foo(s string) string {
return "Hello, " + s
}
<file_sep>/go1-preview/returns_and_shadowed_variables.go
package main
import (
"fmt"
)
func main() {
fmt.Println(Bug())
Foo()
fmt.Println(Bar())
}
// Go 1 이전에는 5, 0, 100이 리턴되나
// Go 1부터는 컴파일 시, "j is shadowed during return" 에러가 난다.
func Bug() (i, j, k int) {
for i = 0; i < 5; i++ {
for j := 0; j < 5; j++ { // Redeclares j.
k += i*j
if k > 100 {
return // Rejected: j is shadowed here.
}
}
}
return // OK: j is not shadowed here.
}
func Foo() {
i := 10
for j := 0; j < 5; j++ {
i := 3
fmt.Println("other i", i)
// i = 3 // same i
}
fmt.Println(i)
}
func Bar() (i int) {
// i := 10 // 이렇게 block scope 내가 아닌 곳에서 redeclare하면 r60.3, Go 1 모두 컴파일 에러: no new variables on left side of :=
for i := 0; i < 5; i++ {
if i == 4 {
return
// return i
}
}
return
}
<file_sep>/README.md
Some stuff about talks and documents.
<file_sep>/go1-preview/function_and_map_equality.go
package main
func foo() {
println("foo invoked")
}
func main() {
f1 := foo
f2 := foo
// Go 1에서는 function과 map은 직접 == 비교가 안 된다.
// invalid operation: f1 == f2 (func can only be compared to nil) 컴파일 시 이런 에러남
// Go 1 전에는 아래 비교가 가능했다. (결과도 성공)
if f1 == f2 {
println("equal")
} else {
println("not equal")
}
}
<file_sep>/network-programming-with-go/syntax/Makefile
include $(GOROOT)/src/Make.inc
TARG=oop
GOFILES=\
oop.go\
# build 하기
include $(GOROOT)/src/Make.cmd
# package 만들기
#include $(GOROOT)/src/Make.pkg
# 이렇게 쓰는 것도 있네..
#GOFMT=gofmt -s -spaces=true -tabindent=false -tabwidth=4
<file_sep>/go1-preview/goroutines_during_init.go
package main
var PackageGlobal int
func init() {
c := make(chan int)
go initializationFunction(c)
PackageGlobal = <-c // Go 1에서는 deadlock 없이 initializationFunction goroutine이 실행되어
// c channel로 write 할 때까지 read 동작을 기다려준다.
// 하지만 Go 1 이전에는 init()은 goroutine이 생성만 될뿐, 실행되지는 않기때문에
// deadlock이 된다.
// PackageGlobal = 20 // 이렇게 하는 건 Go 1 이전에도 된다. 아무 syncronization event가 없기 때문.
}
func initializationFunction(c chan int) {
// c <- 10
}
func main() {
// Go 1에서는 정상적으로 10이 출력되지만,
// Go 1 이전 버전에서는 컴파일은 에러없이 돼도, "throw: init rescheduling" 런타임 에러가 난다.
println(PackageGlobal)
}
<file_sep>/go-tools/demos/run/main.go
package main
func main() {
// println("Hello, Gopher")
println(Foo("Hello, Gopher"))
}
<file_sep>/go1-preview/error.go
package main
import (
"fmt"
"strconv"
)
type MyError struct {
MyField int
}
func (m *MyError) Error() string {
return "MyError implements the error interface. MyField is " + strconv.Itoa(m.MyField)
}
func (m *MyError) Sum(x, y int) (n int, err error) {
return x+y, m
}
func main() {
myerr := new(MyError)
myerr.MyField = 200
n, err := myerr.Sum(1, 2)
fmt.Println(n, err)
}
<file_sep>/network-programming-with-go/echo_server/client/client.go
package main
import (
"fmt"
"net"
"time"
)
func main() {
conn, e := net.Dial("tcp", "localhost:9009")
if e != nil {
panic(e.Error())
}
buf := make([]byte, 512)
for {
_, err := conn.Write([]byte("hi\n"))
if err != nil {
println(err.Error())
}
n, err := conn.Read(buf)
fmt.Printf("%s", buf[0:n])
time.Sleep(3 * 1e9)
}
}
<file_sep>/network-programming-with-go/syntax/oop.go
// OOP style in Go
package main
import (
"fmt"
)
type Pointer interface {
draw()
}
type Point struct {
x, y int
}
func (p *Point) draw() {
fmt.Println(p.x, p.y)
}
func (p *Point) otherMethod() {
fmt.Println("otherMethod")
}
func main() {
p := Point{3, 4}
p.draw()
p.otherMethod()
np := NamedPoint{Point{5, 6}, "hello"}
np.draw()
np.otherMethod()
}
///////////////////////////////////////////////////
type NamedPoint struct {
Point
name string
}
func (np *NamedPoint) draw() {
fmt.Println(np.x, np.y, np.name)
}
<file_sep>/go1-preview/assert_and_conversion.go
package main
import (
"fmt"
"reflect"
)
func main() {
// Type assertions
// x.(T)
// x는 인터페이스의 타입. x가 nil이 아니고, x에 저장된 값은 T 타입이라고 assertion
// 만일 T가 인터페이스 타입이 아니라면 x.(T)는 x는 T와 같은 타입이라고 assertion
// T가 인터페이스 타입이라면 x는 인터페이스 T를 구현한 것이라고 assertion
// var x interface{}
// x = 10
// c := x.(int)
// c, ok := x.(int) // c == 10, ok == true
// c, ok := x.(string) // c == zeroed value, ok == false
// 인터페이스 변수 x가 MyInterface를 구현했다면 x.(MyInterface).Myfunc() 처럼 method chaining으로 사용 가능
// Conversions
b := []byte{'H', 'e', 'l'}
fmt.Printf("%s\n", string(b))
n := 10
fn := float64(n)
fmt.Printf("%f, %f, %s\n", n, fn, reflect.TypeOf(fn))
}
<file_sep>/network-programming-with-go/websocket/websocket.go
package main
import (
"fmt"
"net/http"
"golang.org/x/net/websocket"
)
const MAX_CLIENT = 100
type Client struct {
conn *websocket.Conn
userId string
}
var (
chConn = make(chan Client, MAX_CLIENT)
chMsg = make(chan string, MAX_CLIENT)
)
func ChatServer(ws *websocket.Conn) {
buf := make([]byte, 1024)
n, _ := ws.Read(buf)
userId := string(buf[0:n])
chMsg <- userId + "님이 들어오셨습니다."
newClient := Client{ws, userId}
chConn <- newClient
for n, e := ws.Read(buf); e == nil; n, e = ws.Read(buf) {
chMsg <- "<b>" + userId + "</b>: " + string(buf[0:n])
}
chMsg <- userId + "님이 나가셨습니다."
ws.Close()
}
func WriteToClient() {
clients := make([]Client, 0, MAX_CLIENT)
for {
select {
case newClient := <-chConn:
clients = append(clients, newClient)
case msg := <-chMsg:
fmt.Println(string(msg))
for _, v := range clients {
v.conn.Write([]byte(msg))
// TODO: Write 실패 시 client 제거
}
}
}
}
func IndexPage(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./index.html")
}
func main() {
go WriteToClient()
http.HandleFunc("/", IndexPage)
http.Handle("/chat", websocket.Handler(ChatServer))
if err := http.ListenAndServe(":9009", nil); err != nil {
panic("ListenAndServe: " + err.Error())
}
}
<file_sep>/using-with-google-api/res/urlshortener_web.go
package main
import (
"flag"
"fmt"
"log"
"os"
"strings"
"code.google.com/p/goauth2/oauth"
)
var (
clientId = flag.String("id", "", "Client ID")
clientSecret = flag.String("secret", "", "Client Secret")
cacheFile = flag.String("cache", "url.cache.json", "Token cache file")
code = flag.String("code", "", "Authorization Code")
)
const usageMsg = `
Usage: yourl http://goo.gl/xxxxx (to look up details)
yourl http://example.com/long (to shorten)
To obtain a request token you must specify both -id and -secret.
To obtain Client ID and Secret, see the "OAuth 2 Credentials" section under
the "API Access" tab on this page: https://code.google.com/apis/console/
Once you have completed the OAuth flow, the credentials should be stored inside
the file specified by -cache and you may run without the -id and -secret flags.
`
func main() {
flag.Parse()
if flag.NArg() != 1 {
flag.Usage()
fmt.Fprint(os.Stderr, usageMsg)
os.Exit(2)
}
config := &oauth.Config{
ClientId: *clientId,
ClientSecret: *clientSecret,
Scope: urlshortener.UrlshortenerScope,
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://accounts.google.com/o/oauth2/token",
TokenCache: oauth.CacheFile(*cacheFile),
}
// Set up a Transport using the config.
transport := &oauth.Transport{Config: config}
// Try to pull the token from the cache; if this fails, we need to get one.
token, err := config.TokenCache.Token()
if err != nil {
if *clientId == "" || *clientSecret == "" {
flag.Usage()
fmt.Fprint(os.Stderr, usageMsg)
os.Exit(2)
}
if *code == "" {
// Get an authorization code from the data provider.
// ("Please ask the user if I can access this resource.")
url := config.AuthCodeURL("")
fmt.Println("Visit this URL to get a code, then run again with -code=YOUR_CODE\n")
fmt.Println(url)
return
}
// Exchange the authorization code for an access token.
// ("Here's the code you gave the user, now give me a token!")
token, err = transport.Exchange(*code)
if err != nil {
log.Fatal("Exchange:", err)
}
// (The Exchange method will automatically cache the token.)
fmt.Printf("Token is cached in %v\n", config.TokenCache)
}
// Make the actual request using the cached token to authenticate.
// ("Here's the token, let me in!")
transport.Token = token
httpClient := transport.Client()
svc, err := urlshortener.New(httpClient)
if err != nil {
panic(err)
}
urlstr := flag.Arg(0)
// short -> long
if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
url, err := svc.Url.Get(urlstr).Do()
if err != nil {
log.Fatalf("URL Get: %v", err)
}
fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
return
}
// long -> short
url, err := svc.Url.Insert(&urlshortener.Url{
Kind: "urlshortener#url", // Not really needed
LongUrl: urlstr,
}).Do()
if err != nil {
log.Fatalf("URL Insert: %v", err)
}
fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
}
<file_sep>/go1-preview/multiple_assignment.go
package main
import (
"fmt"
)
func main() {
sa := []int{1, 2, 3}
i := 0
i, sa[i] = 1, 2
// sets i = 1, sa[0] = 2.
// Go 1 이전에는 왼쪽 i가 먼저 1이 되고 sa[i] 즉, sa[1]이 2가 할당되어 {1, 2, 3} 이 된다.
// Go 1에서는 {2, 2, 3}
fmt.Println(sa)
sb := []int{1, 2, 3}
j := 0
sb[j], j = 2, 1
// sets sb[0] = 2, j = 1
// 이건 둘다 결과는 {2 2 3}, j == 1
fmt.Println(sb, j)
sc := []int{1, 2, 3}
sc[0], sc[0] = 1, 2
// sets sc[0] = 1, then sc[0] = 2 (so sc[0] = 2 at end)
// 이건 둘다 결과는 {2 2 3}
fmt.Println(sc)
}
<file_sep>/url-shortener/main.go
package main
import (
"encoding/json"
"flag"
"html/template"
"net/http"
)
var (
listenAddr = flag.String("port", "80", "http listen port")
hostName = flag.String("host", "you.rl", "http host name")
//hostName = flag.String("host", "localhost", "http host name")
)
type Title struct {
Logo string
}
var store Store
func Redirect(w http.ResponseWriter, r *http.Request) {
key := r.URL.Path[1:]
if key == "favicon.ico" {
http.NotFound(w, r)
} else if key == "" {
logo := &Title{Logo: "You.RL"}
tpl, _ := template.ParseFile("index.html", nil)
tpl.Execute(w, logo)
} else if key == "index.js" {
http.ServeFile(w, r, "index.js")
} else {
var url string
store.Get(&key, &url)
http.Redirect(w, r, url, http.StatusFound)
}
}
func Shorten(w http.ResponseWriter, r *http.Request) {
var key string
for key = genKey(); store.Check(&key) == false; {
}
long_url := r.FormValue("url")
store.Put(&key, &long_url)
v := make(map[string]string)
v["url"] = "http://" + *hostName + "/" + key
enc := json.NewEncoder(w)
enc.Encode(&v)
}
func main() {
flag.Parse()
store = new(URLStore)
http.HandleFunc("/", Redirect)
http.HandleFunc("/shorten", Shorten)
http.ListenAndServe(":"+*listenAddr, nil)
}
<file_sep>/go-tools/demos/install/pkg/lru.go
package lru
type Cache struct {
MaxEntries int
}
func New(maxEntries int) *Cache {
return &Cache{
MaxEntries: maxEntries,
}
}
<file_sep>/go1-preview/copying_structs_with_unexported_fields.go
package main
import "fmt"
import "my_new_struct_pkg"
// Go 1 이전에는 "implicit assignment of unexported field 'secret' of my_new_struct_pkg.Struct in assignment"
// 에러가 난다
func main() {
myStruct := my_new_struct_pkg.NewStruct(23)
copyOfMyStruct := myStruct
fmt.Println(myStruct, copyOfMyStruct)
}
<file_sep>/go-tools/README.md
GDG DevFest 2013 Slide Template
Author: <NAME>
Slide: http://go-tools.appspot.com/
GDG DevFest 2013: https://sites.google.com/site/gdgdevfestkorea/conference
<file_sep>/go1-preview/append.go
package main
import (
"fmt"
)
func main() {
// Before Go 1
fmt.Printf("%s\n", append([]byte("Hello "), []byte("World")...)) // Go 1에서 에러는 아님
// After Go 1
fmt.Printf("%s\n", append([]byte("Hello "), " World"...))
fmt.Printf("%s\n", append([]string{"Hello "}, " World", " other strings"))
var s Stack
s.Push("hell") // 이렇게 사용 가능
}
type Stack struct {
data []interface{}
}
func (s *Stack) Push(x interface{}) {
s.data = append(s.data, x)
}
func (s *Stack) Pop() interface{} {
i := len(s.data) - 1
res := s.data[i]
s.data[i] = nil // to avoid memory leak
s.data = s.data[:i]
return res
}
<file_sep>/go1-preview/time.go
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
timestamp := now.Unix()
fmt.Printf("%v\n", timestamp)
// Month()는 Month 타입 (int)가 리턴되는데 String() 메서드가 있어서 January로 프린트된다.
fmt.Println(now.Year(), int(now.Month()), now.Day(), now.Hour(), now.Minute(), now.Second())
}
<file_sep>/network-programming-with-go/echo_server/server/server.go
package main
import (
"fmt"
"io"
"log"
"net"
)
func echo(conn net.Conn) { // io.ReadWriter 가능
fmt.Println("Connected from:", conn.RemoteAddr().String())
defer conn.Close()
buf := make([]byte, 512)
for {
n, err := conn.Read(buf)
if err != nil {
if err == io.EOF {
fmt.Println("Client closed:", conn.RemoteAddr().String())
}
return
}
conn.Write(buf[0:n])
fmt.Printf("%s", buf[0:n])
}
}
func startServer() {
listener, e := net.Listen("tcp", ":9009") // *net.TCPListener
if e != nil {
log.Fatalln(e)
}
defer listener.Close()
for {
conn, e := listener.Accept() // *net.TCPConn
if e != nil {
log.Println("Aceept error:", e)
continue
}
echo(conn)
// go echo(conn)
}
}
func main() {
startServer()
}
<file_sep>/go1-preview/equality_of_structs_and_arrays.go
package main
import (
"fmt"
)
type Day struct {
name string
date int
}
func main() {
Christmas := Day{"Christmas", 25}
Christmas2 := Day{"Christmas", 25}
Thanksgiving := Day{"Thanksgiving", 31}
// Go 1 이전에는
// "invalid operation: Christmas == Thanksgiving (operator == not defined on struct)" 컴파일 에러
if Christmas == Thanksgiving {
println("Christmas and Thanksgiving is not equal")
}
if Christmas == Christmas2 {
println("Christmas and Thanksgiving is equal")
}
holiday := map[Day]bool{
Christmas: true,
Thanksgiving: true,
}
fmt.Printf("Christmas is a holiday: %t\n", holiday[Christmas])
}
<file_sep>/go-tools/demos/gofmt/gofmt.go
package main
import (
"fmt"
"log"
)
func sqrt(i int) int {
return i * i
}
func main() {
for i := 0; i < 10; i++ {
fmt.Println(sqrt(i))
}
log.Print("Hello" + "World")
}
<file_sep>/go1-preview/close.go
package main
import (
"fmt"
)
func numberGen(start, count int, out chan<- int) {
for i := 0; i < count; i++ {
out <- start + i
}
close(out)
// 이 코드는 여기서 close() 하지 않으면 deadlock 됨
// A receive from an unbuffered channel happens before the send on that channel completes.
}
func printNumbers(in <-chan int, done chan<- bool) {
for num := range in {
fmt.Printf("%d\n", num)
}
// close(in) // receive-only 채널은 close를 할 수 없다.
done <- true
}
func main() {
numberChan := make(chan int)
done := make(chan bool)
go numberGen(1, 10, numberChan)
go printNumbers(numberChan, done)
<-done
}
<file_sep>/using-with-google-api/README.md
GDG Korea Golang 4월 미니 컨퍼런스에서 발표한 Go로 **Google API 사용하기** 슬라이드
<file_sep>/go-tools/demos/test/sqrt.go
package sqrt
func Sqrt(i int) int {
return i * i
}
func Divide(x, y int) int {
return x / y
}
<file_sep>/url-shortener/store.go
package main
import (
"os"
"launchpad.net/gobson/bson"
"launchpad.net/mgo"
)
type Store interface {
Check(key *string) bool
Put(key, url *string) os.Error
Get(key, url *string) os.Error
}
type URLStore struct {
Key string
Long_url string
}
func (s *URLStore) Check(key *string) bool {
session, _ := mgo.Mongo("127.0.0.1")
defer session.Close()
c := session.DB("yourl").C("urls")
result := URLStore{}
if err := c.Find(bson.M{"key": *key}).One(&result); err != nil {
return true
}
return false
}
func (s *URLStore) Put(key, url *string) os.Error {
session, _ := mgo.Mongo("127.0.0.1")
defer session.Close()
c := session.DB("yourl").C("urls")
err := c.Insert(&URLStore{*key, *url})
if err != nil {
panic(err)
}
return nil
}
func (s *URLStore) Get(key, url *string) os.Error {
session, _ := mgo.Mongo("127.0.0.1")
defer session.Close()
c := session.DB("yourl").C("urls")
result := URLStore{}
err := c.Find(bson.M{"key": *key}).One(&result)
if err != nil {
panic(err)
}
*url = result.Long_url
return nil
}
| b0d2ea9cee66c943125d6e3002d1426fab2b3e38 | [
"Makefile",
"Go",
"Markdown"
]
| 34 | Go | atomaths/talks | 24fae9f6aa462f2855a0da4dcb2638440c6d5420 | 2f7f02bdf4ac432916cc3238c216d38db5a7bc84 |
refs/heads/master | <repo_name>samy-deghou/jOOQ<file_sep>/jOOQ/src/test/java/org/jooq/tools/jdbc/MockFileDatabaseTest.java
package org.jooq.tools.jdbc;
import org.jooq.exception.ErroneousRowSpecificationException;
import org.junit.Test;
import java.io.IOException;
/**
* Created by deghou on 19/11/2016.
*/
public class MockFileDatabaseTest{
@Test
public void testCorrectRowSpecification() throws IOException {
//File contains one statement
MockFileDatabase mockFileDatabase1 = new MockFileDatabase(this.getClass().getResourceAsStream("/mock-file-database-file-1.txt"));
//File contains multiple statements
MockFileDatabase mockFileDatabase2 = new MockFileDatabase(this.getClass().getResourceAsStream("/mock-file-database-file-4.txt"));
}
@Test(expected = ErroneousRowSpecificationException.class)
public void testErroneousRowSpecification() throws IOException {
MockFileDatabase mockFileDatabase = new MockFileDatabase(this.getClass().getResourceAsStream("/mock-file-database-file-2.txt"));
}
@Test(expected = NumberFormatException.class)
public void testCorrectRowSpecificationValue() throws IOException {
MockFileDatabase mockFileDatabase = new MockFileDatabase(this.getClass().getResourceAsStream("/mock-file-database-file-3.txt"));
}
}
| 29784886cc9419e27d848148100ec5e58eea4f9c | [
"Java"
]
| 1 | Java | samy-deghou/jOOQ | 01d386b95cd3b1e2b54d3404cbb395321cf3fd2f | 361fd50e8a471f5ec5ecbdf985c51ee4c75fbe86 |
refs/heads/master | <repo_name>stphnnnn/contact-form<file_sep>/src/js/main.js
import { domReady } from './utilities/helpers';
import { initContactForm } from './modules/contact-form';
function start() {
initContactForm();
}
domReady(start);
<file_sep>/README.md
# Example contact form
A demo of this can be viewed here: https://optimistic-mahavira-a9ae45.netlify.com/
## Local development
```sh
$ npm install
$ npm start
```
Then visit http://localhost:1234 in your browser
## Build for deployment
```sh
$ npm run build
```
| 69020eb6c22705d42f653878ab78813a26025e6f | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | stphnnnn/contact-form | 498556928037c3feaeaaca5fdf58141a88cb6f70 | 1014dae4eccfd0275f5b4da30bbb03555ff55e47 |
refs/heads/master | <file_sep>""" Tests for libsana module
Utilities for analyzing library dependencies in trees and wheels
"""
import os
import shutil
from os.path import dirname
from os.path import join as pjoin
from os.path import realpath, relpath, split
from typing import Dict, Iterable, Text
import pytest
from ..delocating import DelocationError, filter_system_libs
from ..libsana import (
DependencyNotFound,
get_dependencies,
get_prefix_stripper,
get_rp_stripper,
resolve_dynamic_paths,
resolve_rpath,
stripped_lib_dict,
tree_libs,
tree_libs_from_directory,
walk_directory,
walk_library,
wheel_libs,
)
from ..tmpdirs import InTemporaryDirectory
from ..tools import set_install_name
from .pytest_tools import assert_equal
from .test_install_names import (
DATA_PATH,
EXT_LIBS,
LIBA,
LIBB,
LIBC,
LIBSYSTEMB,
TEST_LIB,
_copy_libs,
)
from .test_wheelies import PLAT_WHEEL, PURE_WHEEL, RPATH_WHEEL, PlatWheel
def get_ext_dict(local_libs):
# type: (Iterable[Text]) -> Dict[Text, Dict[Text, Text]]
ext_deps = {}
for ext_lib in EXT_LIBS:
lib_deps = {}
for local_lib in local_libs:
lib_deps[realpath(local_lib)] = ext_lib
ext_deps[realpath(ext_lib)] = lib_deps
return ext_deps
@pytest.mark.filterwarnings("ignore:tree_libs:DeprecationWarning")
def test_tree_libs():
# type: () -> None
# Test ability to walk through tree, finding dynamic library refs
# Copy specific files to avoid working tree cruft
to_copy = [LIBA, LIBB, LIBC, TEST_LIB]
with InTemporaryDirectory() as tmpdir:
local_libs = _copy_libs(to_copy, tmpdir)
rp_local_libs = [realpath(L) for L in local_libs]
liba, libb, libc, test_lib = local_libs
rp_liba, rp_libb, rp_libc, rp_test_lib = rp_local_libs
exp_dict = get_ext_dict(local_libs)
exp_dict.update(
{
rp_liba: {rp_libb: "liba.dylib", rp_libc: "liba.dylib"},
rp_libb: {rp_libc: "libb.dylib"},
rp_libc: {rp_test_lib: "libc.dylib"},
}
)
# default - no filtering
assert tree_libs(tmpdir) == exp_dict
def filt(fname):
# type: (Text) -> bool
return fname.endswith(".dylib")
exp_dict = get_ext_dict([liba, libb, libc])
exp_dict.update(
{
rp_liba: {rp_libb: "liba.dylib", rp_libc: "liba.dylib"},
rp_libb: {rp_libc: "libb.dylib"},
}
)
# filtering
assert tree_libs(tmpdir, filt) == exp_dict
# Copy some libraries into subtree to test tree walking
subtree = pjoin(tmpdir, "subtree")
slibc, stest_lib = _copy_libs([libc, test_lib], subtree)
st_exp_dict = get_ext_dict([liba, libb, libc, slibc])
st_exp_dict.update(
{
rp_liba: {
rp_libb: "liba.dylib",
rp_libc: "liba.dylib",
realpath(slibc): "liba.dylib",
},
rp_libb: {
rp_libc: "libb.dylib",
realpath(slibc): "libb.dylib",
},
}
)
assert tree_libs(tmpdir, filt) == st_exp_dict
# Change an install name, check this is picked up
set_install_name(slibc, "liba.dylib", "newlib")
inc_exp_dict = get_ext_dict([liba, libb, libc, slibc])
inc_exp_dict.update(
{
rp_liba: {rp_libb: "liba.dylib", rp_libc: "liba.dylib"},
realpath("newlib"): {realpath(slibc): "newlib"},
rp_libb: {
rp_libc: "libb.dylib",
realpath(slibc): "libb.dylib",
},
}
)
assert tree_libs(tmpdir, filt) == inc_exp_dict
# Symlink a depending canonical lib - should have no effect because of
# the canonical names
os.symlink(liba, pjoin(dirname(liba), "funny.dylib"))
assert tree_libs(tmpdir, filt) == inc_exp_dict
# Symlink a depended lib. Now 'newlib' is a symlink to liba, and the
# dependency of slibc on newlib appears as a dependency on liba, but
# with install name 'newlib'
os.symlink(liba, "newlib")
sl_exp_dict = get_ext_dict([liba, libb, libc, slibc])
sl_exp_dict.update(
{
rp_liba: {
rp_libb: "liba.dylib",
rp_libc: "liba.dylib",
realpath(slibc): "newlib",
},
rp_libb: {
rp_libc: "libb.dylib",
realpath(slibc): "libb.dylib",
},
}
)
assert tree_libs(tmpdir, filt) == sl_exp_dict
def test_tree_libs_from_directory() -> None:
# Test ability to walk through tree, finding dynamic library refs
# Copy specific files to avoid working tree cruft
to_copy = [LIBA, LIBB, LIBC, TEST_LIB]
with InTemporaryDirectory() as tmpdir:
local_libs = _copy_libs(to_copy, tmpdir)
rp_local_libs = [realpath(L) for L in local_libs]
liba, libb, libc, test_lib = local_libs
rp_liba, rp_libb, rp_libc, rp_test_lib = rp_local_libs
exp_dict = get_ext_dict(local_libs)
exp_dict.update(
{
rp_liba: {rp_libb: "liba.dylib", rp_libc: "liba.dylib"},
rp_libb: {rp_libc: "libb.dylib"},
rp_libc: {rp_test_lib: "libc.dylib"},
}
)
# default - no filtering
assert tree_libs_from_directory(tmpdir) == exp_dict
def filt(fname: str) -> bool:
return filter_system_libs(fname) and fname.endswith(".dylib")
exp_dict = get_ext_dict([liba, libb, libc])
exp_dict.update(
{
rp_liba: {rp_libb: "liba.dylib", rp_libc: "liba.dylib"},
rp_libb: {rp_libc: "libb.dylib"},
}
)
# filtering
assert tree_libs_from_directory(tmpdir, lib_filt_func=filt) == exp_dict
# Copy some libraries into subtree to test tree walking
subtree = pjoin(tmpdir, "subtree")
slibc, stest_lib = _copy_libs([libc, test_lib], subtree)
st_exp_dict = get_ext_dict([liba, libb, libc, slibc])
st_exp_dict.update(
{
rp_liba: {
rp_libb: "liba.dylib",
rp_libc: "liba.dylib",
realpath(slibc): "liba.dylib",
},
rp_libb: {
rp_libc: "libb.dylib",
realpath(slibc): "libb.dylib",
},
}
)
assert (
tree_libs_from_directory(tmpdir, lib_filt_func=filt) == st_exp_dict
)
# Change an install name, check this is ignored
set_install_name(slibc, "liba.dylib", "newlib")
inc_exp_dict = get_ext_dict([liba, libb, libc, slibc])
inc_exp_dict.update(
{
rp_liba: {rp_libb: "liba.dylib", rp_libc: "liba.dylib"},
rp_libb: {
rp_libc: "libb.dylib",
realpath(slibc): "libb.dylib",
},
}
)
assert (
tree_libs_from_directory(
tmpdir, lib_filt_func=filt, ignore_missing=True
)
== inc_exp_dict
)
# Symlink a depending canonical lib - should have no effect because of
# the canonical names
os.symlink(liba, pjoin(dirname(liba), "funny.dylib"))
assert (
tree_libs_from_directory(
tmpdir, lib_filt_func=filt, ignore_missing=True
)
== inc_exp_dict
)
# Symlink a depended lib. Now 'newlib' is a symlink to liba, and the
# dependency of slibc on newlib appears as a dependency on liba, but
# with install name 'newlib'
os.symlink(liba, "newlib")
sl_exp_dict = get_ext_dict([liba, libb, libc, slibc])
sl_exp_dict.update(
{
rp_liba: {
rp_libb: "liba.dylib",
rp_libc: "liba.dylib",
realpath(slibc): "newlib",
},
rp_libb: {
rp_libc: "libb.dylib",
realpath(slibc): "libb.dylib",
},
}
)
assert (
tree_libs_from_directory(
tmpdir, lib_filt_func=filt, ignore_missing=True
)
== sl_exp_dict
)
def test_get_prefix_stripper():
# type: () -> None
# Test function factory to strip prefixes
f = get_prefix_stripper("")
assert_equal(f("a string"), "a string")
f = get_prefix_stripper("a ")
assert_equal(f("a string"), "string")
assert_equal(f("b string"), "b string")
assert_equal(f("b a string"), "b a string")
def test_get_rp_stripper():
# type: () -> None
# realpath prefix stripper
# Just does realpath and adds path sep
cwd = realpath(os.getcwd())
f = get_rp_stripper("") # pwd
test_path = pjoin("test", "path")
assert_equal(f(test_path), test_path)
rp_test_path = pjoin(cwd, test_path)
assert_equal(f(rp_test_path), test_path)
f = get_rp_stripper(pjoin(cwd, "test"))
assert_equal(f(rp_test_path), "path")
def get_ext_dict_stripped(local_libs, start_path):
# type: (Iterable[Text], Text) -> Dict[Text, Dict[Text, Text]]
ext_dict = {}
for ext_lib in EXT_LIBS:
lib_deps = {}
for local_lib in local_libs:
dep_path = relpath(local_lib, start_path)
if dep_path.startswith("./"):
dep_path = dep_path[2:]
lib_deps[dep_path] = ext_lib
ext_dict[realpath(ext_lib)] = lib_deps
return ext_dict
def test_stripped_lib_dict():
# type: () -> None
# Test routine to return lib_dict with relative paths
to_copy = [LIBA, LIBB, LIBC, TEST_LIB]
with InTemporaryDirectory() as tmpdir:
local_libs = _copy_libs(to_copy, tmpdir)
exp_dict = get_ext_dict_stripped(local_libs, tmpdir)
exp_dict.update(
{
"liba.dylib": {
"libb.dylib": "liba.dylib",
"libc.dylib": "liba.dylib",
},
"libb.dylib": {"libc.dylib": "libb.dylib"},
"libc.dylib": {"test-lib": "libc.dylib"},
}
)
my_path = realpath(tmpdir) + os.path.sep
assert (
stripped_lib_dict(tree_libs_from_directory(tmpdir), my_path)
== exp_dict
)
# Copy some libraries into subtree to test tree walking
subtree = pjoin(tmpdir, "subtree")
liba, libb, libc, test_lib = local_libs
slibc, stest_lib = _copy_libs([libc, test_lib], subtree)
exp_dict = get_ext_dict_stripped(
local_libs + [slibc, stest_lib], tmpdir
)
exp_dict.update(
{
"liba.dylib": {
"libb.dylib": "liba.dylib",
"libc.dylib": "liba.dylib",
"subtree/libc.dylib": "liba.dylib",
},
"libb.dylib": {
"libc.dylib": "libb.dylib",
"subtree/libc.dylib": "libb.dylib",
},
"libc.dylib": {
"test-lib": "libc.dylib",
"subtree/test-lib": "libc.dylib",
},
}
)
assert (
stripped_lib_dict(tree_libs_from_directory(tmpdir), my_path)
== exp_dict
)
def test_wheel_libs(plat_wheel: PlatWheel) -> None:
# Test routine to list dependencies from wheels
assert wheel_libs(PURE_WHEEL) == {}
mod2 = pjoin("fakepkg1", "subpkg", "module2.abi3.so")
assert wheel_libs(plat_wheel.whl) == {
plat_wheel.stray_lib: {mod2: plat_wheel.stray_lib},
realpath(LIBSYSTEMB): {
mod2: LIBSYSTEMB,
plat_wheel.stray_lib: LIBSYSTEMB,
},
}
def filt(fname: str) -> bool:
return not fname.endswith(mod2)
assert wheel_libs(PLAT_WHEEL, filt) == {}
def test_wheel_libs_ignore_missing() -> None:
# Test wheel_libs ignore_missing parameter.
with InTemporaryDirectory() as tmpdir:
shutil.copy(RPATH_WHEEL, pjoin(tmpdir, "rpath.whl"))
with pytest.raises(DelocationError):
wheel_libs("rpath.whl")
wheel_libs("rpath.whl", ignore_missing=True)
def test_resolve_dynamic_paths():
# type: () -> None
# A minimal test of the resolve_rpath function
path, lib = split(LIBA)
lib_rpath = pjoin("@rpath", lib)
# Should skip '/nonexist' path
assert resolve_dynamic_paths(
lib_rpath, ["/nonexist", path], path
) == realpath(LIBA)
# Should raise DependencyNotFound if the dependency can not be resolved.
with pytest.raises(DependencyNotFound):
resolve_dynamic_paths(lib_rpath, [], path)
def test_resolve_rpath():
# type: () -> None
# A minimal test of the resolve_rpath function
path, lib = split(LIBA)
lib_rpath = pjoin("@rpath", lib)
# Should skip '/nonexist' path
assert_equal(resolve_rpath(lib_rpath, ["/nonexist", path]), realpath(LIBA))
# Should return the given parameter as is since it can't be found
assert_equal(resolve_rpath(lib_rpath, []), lib_rpath)
def test_get_dependencies(tmpdir):
# type: (object) -> None
tmpdir = str(tmpdir)
with pytest.raises(DependencyNotFound):
list(get_dependencies("nonexistent.lib"))
ext_libs = {(lib, lib) for lib in EXT_LIBS}
assert set(get_dependencies(LIBA)) == ext_libs
os.symlink(
pjoin(DATA_PATH, "libextfunc_rpath.dylib"),
pjoin(tmpdir, "libextfunc_rpath.dylib"),
)
assert set(
get_dependencies(
pjoin(tmpdir, "libextfunc_rpath.dylib"),
filt_func=filter_system_libs,
)
) == {
(None, "@rpath/libextfunc2_rpath.dylib"),
(LIBSYSTEMB, LIBSYSTEMB),
}
assert set(
get_dependencies(
pjoin(tmpdir, "libextfunc_rpath.dylib"),
executable_path=DATA_PATH,
filt_func=filter_system_libs,
)
) == {
(
pjoin(DATA_PATH, "libextfunc2_rpath.dylib"),
"@rpath/libextfunc2_rpath.dylib",
),
(LIBSYSTEMB, LIBSYSTEMB),
}
def test_walk_library():
# type: () -> None
with pytest.raises(DependencyNotFound):
list(walk_library("nonexistent.lib"))
assert set(walk_library(LIBA, filt_func=filter_system_libs)) == {
LIBA,
}
assert set(
walk_library(
pjoin(DATA_PATH, "libextfunc_rpath.dylib"),
filt_func=filter_system_libs,
)
) == {
pjoin(DATA_PATH, "libextfunc_rpath.dylib"),
pjoin(DATA_PATH, "libextfunc2_rpath.dylib"),
}
def test_walk_directory(tmpdir):
# type: (object) -> None
tmpdir = str(tmpdir)
assert set(walk_directory(tmpdir)) == set()
shutil.copy(pjoin(DATA_PATH, "libextfunc_rpath.dylib"), tmpdir)
assert set(walk_directory(tmpdir, filt_func=filter_system_libs)) == {
pjoin(tmpdir, "libextfunc_rpath.dylib"),
}
assert set(
walk_directory(
tmpdir, executable_path=DATA_PATH, filt_func=filter_system_libs
)
) == {
pjoin(tmpdir, "libextfunc_rpath.dylib"),
pjoin(DATA_PATH, "libextfunc2_rpath.dylib"),
}
<file_sep>""" Tools for getting and setting install names """
import os
import re
import stat
import subprocess
import time
import warnings
import zipfile
from os.path import exists, isdir
from os.path import join as pjoin
from os.path import relpath
from typing import Any, FrozenSet, List, Optional, Sequence, Set, Union
class InstallNameError(Exception):
pass
def back_tick(
cmd: Union[str, Sequence[str]],
ret_err: bool = False,
as_str: bool = True,
raise_err: Optional[bool] = None,
) -> Any:
"""Run command `cmd`, return stdout, or stdout, stderr if `ret_err`
Roughly equivalent to ``check_output`` in Python 2.7
Parameters
----------
cmd : sequence
command to execute
ret_err : bool, optional
If True, return stderr in addition to stdout. If False, just return
stdout
as_str : bool, optional
Whether to decode outputs to unicode string on exit.
raise_err : None or bool, optional
If True, raise RuntimeError for non-zero return code. If None, set to
True when `ret_err` is False, False if `ret_err` is True
Returns
-------
out : str or tuple
If `ret_err` is False, return stripped string containing stdout from
`cmd`. If `ret_err` is True, return tuple of (stdout, stderr) where
``stdout`` is the stripped stdout, and ``stderr`` is the stripped
stderr.
Raises
------
Raises RuntimeError if command returns non-zero exit code and `raise_err`
is True
.. deprecated:: 0.10
This function was deprecated because the return type is too dynamic.
You should use :func:`subprocess.run` instead.
"""
warnings.warn(
"back_tick is deprecated, replace this call with subprocess.run.",
DeprecationWarning,
stacklevel=2,
)
if raise_err is None:
raise_err = False if ret_err else True
cmd_is_seq = isinstance(cmd, (list, tuple))
try:
proc = subprocess.run(
cmd,
shell=not cmd_is_seq,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=as_str,
check=raise_err,
)
except subprocess.CalledProcessError as exc:
raise RuntimeError(
f"{exc.cmd} returned code {exc.returncode} with error {exc.stderr}"
)
if not ret_err:
return proc.stdout.strip()
return proc.stdout.strip(), proc.stderr.strip()
def unique_by_index(sequence):
"""unique elements in `sequence` in the order in which they occur
Parameters
----------
sequence : iterable
Returns
-------
uniques : list
unique elements of sequence, ordered by the order in which the element
occurs in `sequence`
"""
uniques = []
for element in sequence:
if element not in uniques:
uniques.append(element)
return uniques
def chmod_perms(fname):
# Permissions relevant to chmod
return stat.S_IMODE(os.stat(fname).st_mode)
def ensure_permissions(mode_flags=stat.S_IWUSR):
"""decorator to ensure a filename has given permissions.
If changed, original permissions are restored after the decorated
modification.
"""
def decorator(f):
def modify(filename, *args, **kwargs):
m = chmod_perms(filename) if exists(filename) else mode_flags
if not m & mode_flags:
os.chmod(filename, m | mode_flags)
try:
return f(filename, *args, **kwargs)
finally:
# restore original permissions
if not m & mode_flags:
os.chmod(filename, m)
return modify
return decorator
# Open filename, checking for read permission
open_readable = ensure_permissions(stat.S_IRUSR)(open)
# Open filename, checking for read / write permission
open_rw = ensure_permissions(stat.S_IRUSR | stat.S_IWUSR)(open)
# For backward compatibility
ensure_writable = ensure_permissions()
# otool on 10.15 appends more information after versions.
IN_RE = re.compile(
r"(.*) \(compatibility version (\d+\.\d+\.\d+), "
r"current version (\d+\.\d+\.\d+)(?:, \w+)?\)"
)
def parse_install_name(line):
"""Parse a line of install name output
Parameters
----------
line : str
line of install name output from ``otool``
Returns
-------
libname : str
library install name
compat_version : str
compatibility version
current_version : str
current version
"""
line = line.strip()
return IN_RE.match(line).groups()
# otool -L strings indicating this is not an object file. The string changes
# with different otool versions.
RE_PERM_DEN = re.compile(r"Permission denied[.) ]*$")
BAD_OBJECT_TESTS = [
# otool version cctools-862
lambda s: "is not an object file" in s,
# cctools-862 (.ico)
lambda s: "The end of the file was unexpectedly encountered" in s,
# cctools-895
lambda s: "The file was not recognized as a valid object file" in s,
# 895 binary file
lambda s: "Invalid data was encountered while parsing the file" in s,
# cctools-900
lambda s: "Object is not a Mach-O file type" in s,
# cctools-949
lambda s: "object is not a Mach-O file type" in s,
# File may not have read permissions
lambda s: RE_PERM_DEN.search(s) is not None,
]
def _cmd_out_err(cmd: Sequence[str]) -> List[str]:
"""Run command, return stdout or stderr if stdout is empty."""
proc = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
out = proc.stdout.strip()
if not out:
out = proc.stderr.strip()
return out.split("\n")
# Sometimes the line starts with (architecture arm64) and sometimes not
# The regex is used for matching both
_LINE0_RE = re.compile(r"^(?: \(architecture .*\))?:(?P<further_report>.*)")
def _line0_says_object(line0, filename):
line0 = line0.strip()
for test in BAD_OBJECT_TESTS:
if test(line0):
return False
if line0.startswith("Archive :"):
# nothing to do for static libs
return False
if not line0.startswith(filename):
raise InstallNameError("Unexpected first line: " + line0)
match = _LINE0_RE.match(line0[len(filename) :])
if not match:
raise InstallNameError("Unexpected first line: " + line0)
further_report = match.group("further_report")
if further_report == "":
return True
raise InstallNameError(
'Too ignorant to know what "{0}" means'.format(further_report)
)
def get_install_names(filename):
"""Return install names from library named in `filename`
Returns tuple of install names
tuple will be empty if no install names, or if this is not an object file.
Parameters
----------
filename : str
filename of library
Returns
-------
install_names : tuple
tuple of install names for library `filename`
"""
lines = _cmd_out_err(["otool", "-L", filename])
if not _line0_says_object(lines[0], filename):
return ()
names = tuple(parse_install_name(line)[0] for line in lines[1:])
install_id = get_install_id(filename)
if install_id is not None:
assert names[0] == install_id
return names[1:]
return names
def get_install_id(filename):
"""Return install id from library named in `filename`
Returns None if no install id, or if this is not an object file.
Parameters
----------
filename : str
filename of library
Returns
-------
install_id : str
install id of library `filename`, or None if no install id
"""
lines = _cmd_out_err(["otool", "-D", filename])
if not _line0_says_object(lines[0], filename):
return None
if len(lines) == 1:
return None
if len(lines) != 2:
raise InstallNameError("Unexpected otool output " + "\n".join(lines))
return lines[1].strip()
@ensure_writable
def set_install_name(
filename: str, oldname: str, newname: str, ad_hoc_sign: bool = True
) -> None:
"""Set install name `oldname` to `newname` in library filename
Parameters
----------
filename : str
filename of library
oldname : str
current install name in library
newname : str
replacement name for `oldname`
ad_hoc_sign : {True, False}, optional
If True, sign library with ad-hoc signature
"""
names = get_install_names(filename)
if oldname not in names:
raise InstallNameError(
"{0} not in install names for {1}".format(oldname, filename)
)
subprocess.run(
["install_name_tool", "-change", oldname, newname, filename],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
)
if ad_hoc_sign:
# ad hoc signature is represented by a dash
# https://developer.apple.com/documentation/security/seccodesignatureflags/kseccodesignatureadhoc
replace_signature(filename, "-")
@ensure_writable
def set_install_id(filename: str, install_id: str, ad_hoc_sign: bool = True):
"""Set install id for library named in `filename`
Parameters
----------
filename : str
filename of library
install_id : str
install id for library `filename`
ad_hoc_sign : {True, False}, optional
If True, sign library with ad-hoc signature
Raises
------
RuntimeError if `filename` has not install id
"""
if get_install_id(filename) is None:
raise InstallNameError("{0} has no install id".format(filename))
subprocess.run(
["install_name_tool", "-id", install_id, filename],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
)
if ad_hoc_sign:
replace_signature(filename, "-")
RPATH_RE = re.compile(r"path (.*) \(offset \d+\)")
def get_rpaths(filename):
"""Return a tuple of rpaths from the library `filename`.
If `filename` is not a library then the returned tuple will be empty.
Parameters
----------
filename : str
filename of library
Returns
-------
rpath : tuple
rpath paths in `filename`
"""
try:
lines = _cmd_out_err(["otool", "-l", filename])
except RuntimeError:
return ()
if not _line0_says_object(lines[0], filename):
return ()
lines = [line.strip() for line in lines]
paths = []
line_no = 1
while line_no < len(lines):
line = lines[line_no]
line_no += 1
if line != "cmd LC_RPATH":
continue
cmdsize, path = lines[line_no : line_no + 2]
assert cmdsize.startswith("cmdsize ")
paths.append(RPATH_RE.match(path).groups()[0])
line_no += 2
return tuple(paths)
def get_environment_variable_paths():
"""Return a tuple of entries in `DYLD_LIBRARY_PATH` and
`DYLD_FALLBACK_LIBRARY_PATH`.
This will allow us to search those locations for dependencies of libraries
as well as `@rpath` entries.
Returns
-------
env_var_paths : tuple
path entries in environment variables
"""
# We'll search the extra library paths in a specific order:
# DYLD_LIBRARY_PATH and then DYLD_FALLBACK_LIBRARY_PATH
env_var_paths = []
extra_paths = ["DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH"]
for pathname in extra_paths:
path_contents = os.environ.get(pathname)
if path_contents is not None:
for path in path_contents.split(":"):
env_var_paths.append(path)
return tuple(env_var_paths)
@ensure_writable
def add_rpath(filename: str, newpath: str, ad_hoc_sign: bool = True) -> None:
"""Add rpath `newpath` to library `filename`
Parameters
----------
filename : str
filename of library
newpath : str
rpath to add
ad_hoc_sign : {True, False}, optional
If True, sign file with ad-hoc signature
"""
subprocess.run(
["install_name_tool", "-add_rpath", newpath, filename],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
)
if ad_hoc_sign:
replace_signature(filename, "-")
def zip2dir(zip_fname: str, out_dir: str) -> None:
"""Extract `zip_fname` into output directory `out_dir`
Parameters
----------
zip_fname : str
Filename of zip archive to write
out_dir : str
Directory path containing files to go in the zip archive
"""
# Use unzip command rather than zipfile module to preserve permissions
# http://bugs.python.org/issue15795
subprocess.run(
["unzip", "-o", "-d", out_dir, zip_fname],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
)
def dir2zip(in_dir, zip_fname):
"""Make a zip file `zip_fname` with contents of directory `in_dir`
The recorded filenames are relative to `in_dir`, so doing a standard zip
unpack of the resulting `zip_fname` in an empty directory will result in
the original directory contents.
Parameters
----------
in_dir : str
Directory path containing files to go in the zip archive
zip_fname : str
Filename of zip archive to write
"""
z = zipfile.ZipFile(zip_fname, "w", compression=zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(in_dir):
for file in files:
in_fname = pjoin(root, file)
in_stat = os.stat(in_fname)
# Preserve file permissions, but allow copy
info = zipfile.ZipInfo(in_fname)
info.filename = relpath(in_fname, in_dir)
if os.path.sep == "\\":
# Make the path unix friendly on windows.
# PyPI won't accept wheels with windows path separators
info.filename = relpath(in_fname, in_dir).replace("\\", "/")
# Set time from modification time
info.date_time = time.localtime(in_stat.st_mtime)
# See https://stackoverflow.com/questions/434641/how-do-i-set-permissions-attributes-on-a-file-in-a-zip-file-using-pythons-zip/48435482#48435482 # noqa: E501
# Also set regular file permissions
perms = stat.S_IMODE(in_stat.st_mode) | stat.S_IFREG
info.external_attr = perms << 16
with open_readable(in_fname, "rb") as fobj:
contents = fobj.read()
z.writestr(info, contents, zipfile.ZIP_DEFLATED)
z.close()
def find_package_dirs(root_path: str) -> Set[str]:
"""Find python package directories in directory `root_path`
Parameters
----------
root_path : str
Directory to search for package subdirectories
Returns
-------
package_sdirs : set
Set of strings where each is a subdirectory of `root_path`, containing
an ``__init__.py`` file. Paths prefixed by `root_path`
"""
package_sdirs = set()
for entry in os.listdir(root_path):
fname = entry if root_path == "." else pjoin(root_path, entry)
if isdir(fname) and exists(pjoin(fname, "__init__.py")):
package_sdirs.add(fname)
return package_sdirs
def cmp_contents(filename1, filename2):
"""Returns True if contents of the files are the same
Parameters
----------
filename1 : str
filename of first file to compare
filename2 : str
filename of second file to compare
Returns
-------
tf : bool
True if binary contents of `filename1` is same as binary contents of
`filename2`, False otherwise.
"""
with open_readable(filename1, "rb") as fobj:
contents1 = fobj.read()
with open_readable(filename2, "rb") as fobj:
contents2 = fobj.read()
return contents1 == contents2
def get_archs(libname: str) -> FrozenSet[str]:
"""Return architecture types from library `libname`
Parameters
----------
libname : str
filename of binary for which to return arch codes
Returns
-------
arch_names : frozenset
Empty (frozen)set if no arch codes. If not empty, contains one or more
of 'ppc', 'ppc64', 'i386', 'x86_64', 'arm64'.
"""
if not exists(libname):
raise RuntimeError(libname + " is not a file")
try:
lipo = subprocess.run(
["lipo", "-info", libname],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
check=True,
)
stdout = lipo.stdout.strip()
except subprocess.CalledProcessError:
return frozenset()
lines = [line.strip() for line in stdout.split("\n") if line.strip()]
# For some reason, output from lipo -info on .a file generates this line
if lines[0] == "input file {0} is not a fat file".format(libname):
line = lines[1]
else:
assert len(lines) == 1
line = lines[0]
for reggie in (
"Non-fat file: {0} is architecture: (.*)".format(re.escape(libname)),
"Architectures in the fat file: {0} are: (.*)".format(
re.escape(libname)
),
):
match = re.match(reggie, line)
if match is not None:
return frozenset(match.groups()[0].split(" "))
raise ValueError("Unexpected output: '{0}' for {1}".format(stdout, libname))
def lipo_fuse(
in_fname1: str, in_fname2: str, out_fname: str, ad_hoc_sign: bool = True
) -> str:
"""Use lipo to merge libs `filename1`, `filename2`, store in `out_fname`
Parameters
----------
in_fname1 : str
filename of library
in_fname2 : str
filename of library
out_fname : str
filename to which to write new fused library
ad_hoc_sign : {True, False}, optional
If True, sign file with ad-hoc signature
Raises
------
RuntimeError
If the lipo command exits with an error.
"""
try:
lipo = subprocess.run(
["lipo", "-create", in_fname1, in_fname2, "-output", out_fname],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
universal_newlines=True,
)
except subprocess.CalledProcessError as exc:
raise RuntimeError(f"Command {exc.cmd} failed with error: {exc.stderr}")
if ad_hoc_sign:
replace_signature(out_fname, "-")
return lipo.stdout.strip()
@ensure_writable
def replace_signature(filename: str, identity: str) -> None:
"""Replace the signature of a binary file using `identity`
See the codesign documentation for more info
Parameters
----------
filename : str
Filepath to a binary file.
identity : str
The signing identity to use.
"""
subprocess.run(
["codesign", "--force", "--sign", identity, filename],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
)
def validate_signature(filename: str) -> None:
"""Remove invalid signatures from a binary file
If the file signature is missing or valid then it will be ignored
Invalid signatures are replaced with an ad-hoc signature. This is the
closest you can get to removing a signature on MacOS
Parameters
----------
filename : str
Filepath to a binary file
"""
codesign = subprocess.run(
["codesign", "--verify", filename],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
if not codesign.stderr:
return # The existing signature is valid
if "code object is not signed at all" in codesign.stderr:
return # File has no signature, and adding a new one isn't necessary
# This file's signature is invalid and needs to be replaced
replace_signature(filename, "-") # Replace with an ad-hoc signature
<file_sep>[tool.black]
line-length = 80
target-version = ['py36']
extend-exclude = '''versioneer.py|delocate/_version.py'''
experimental-string-processing = true
[tool.isort]
profile = "black"
py_version = 36
src_paths = ["isort", "test"]
line_length = 80
extend_skip = ["versioneer.py", "delocate/_version.py"]
<file_sep>""" Tests for install name utilities """
import os
import shutil
from os.path import basename, dirname, exists
from os.path import join as pjoin
from ..tmpdirs import InTemporaryDirectory
from ..tools import (
InstallNameError,
add_rpath,
get_environment_variable_paths,
get_install_id,
get_install_names,
get_rpaths,
parse_install_name,
set_install_id,
set_install_name,
)
from .env_tools import TempDirWithoutEnvVars
from .pytest_tools import assert_equal, assert_raises
# External libs linked from test data
LIBSTDCXX = "/usr/lib/libc++.1.dylib"
LIBSYSTEMB = "/usr/lib/libSystem.B.dylib"
EXT_LIBS = (LIBSTDCXX, LIBSYSTEMB)
DATA_PATH = pjoin(dirname(__file__), "data")
LIBA = pjoin(DATA_PATH, "liba.dylib")
LIBB = pjoin(DATA_PATH, "libb.dylib")
LIBC = pjoin(DATA_PATH, "libc.dylib")
LIBAM1_ARCH = pjoin(DATA_PATH, "libam1-arch.dylib")
LIBA_STATIC = pjoin(DATA_PATH, "liba.a")
A_OBJECT = pjoin(DATA_PATH, "a.o")
TEST_LIB = pjoin(DATA_PATH, "test-lib")
ICO_FILE = pjoin(DATA_PATH, "icon.ico")
PY_FILE = pjoin(DATA_PATH, "some_code.py")
BIN_FILE = pjoin(DATA_PATH, "binary_example.bin")
def test_get_install_names():
# Test install name listing
assert_equal(set(get_install_names(LIBA)), set(EXT_LIBS))
assert_equal(set(get_install_names(LIBB)), set(("liba.dylib",) + EXT_LIBS))
assert_equal(
set(get_install_names(LIBC)),
set(("liba.dylib", "libb.dylib") + EXT_LIBS),
)
assert_equal(
set(get_install_names(TEST_LIB)), set(("libc.dylib",) + EXT_LIBS)
)
assert_equal(set(get_install_names(LIBAM1_ARCH)), set(EXT_LIBS))
# Non-object file returns empty tuple
assert_equal(get_install_names(__file__), ())
# Static archive and object files returns empty tuple
assert_equal(get_install_names(A_OBJECT), ())
assert_equal(get_install_names(LIBA_STATIC), ())
# ico file triggers another error message and should also return an empty tuple # noqa: E501
assert_equal(get_install_names(ICO_FILE), ())
# Python file (__file__ above may be a pyc file)
assert_equal(get_install_names(PY_FILE), ())
# Binary file (in fact a truncated SAS file)
assert_equal(get_install_names(BIN_FILE), ())
# Test when no read permission
with InTemporaryDirectory():
shutil.copyfile(LIBA, "test.dylib")
assert_equal(set(get_install_names("test.dylib")), set(EXT_LIBS))
# No permissions, no found libs
os.chmod("test.dylib", 0)
assert_equal(get_install_names("test.dylib"), ())
def test_parse_install_name():
assert_equal(
parse_install_name(
"liba.dylib (compatibility version 0.0.0, current version 0.0.0)"
),
("liba.dylib", "0.0.0", "0.0.0"),
)
assert_equal(
parse_install_name(
" /usr/lib/libstdc++.6.dylib (compatibility version 1.0.0, "
"current version 120.0.0)"
),
("/usr/lib/libstdc++.6.dylib", "1.0.0", "120.0.0"),
)
assert_equal(
parse_install_name(
"\t\t /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, "
"current version 1197.1.1)"
),
("/usr/lib/libSystem.B.dylib", "1.0.0", "1197.1.1"),
)
def test_install_id():
# Test basic otool library listing
assert_equal(get_install_id(LIBA), "liba.dylib")
assert_equal(get_install_id(LIBB), "libb.dylib")
assert_equal(get_install_id(LIBC), "libc.dylib")
assert_equal(get_install_id(TEST_LIB), None)
# Non-object file returns None too
assert_equal(get_install_id(__file__), None)
assert_equal(get_install_id(ICO_FILE), None)
def test_change_install_name():
# Test ability to change install names in library
libb_names = get_install_names(LIBB)
with InTemporaryDirectory() as tmpdir:
libfoo = pjoin(tmpdir, "libfoo.dylib")
shutil.copy2(LIBB, libfoo)
assert_equal(get_install_names(libfoo), libb_names)
set_install_name(libfoo, "liba.dylib", "libbar.dylib")
assert_equal(
get_install_names(libfoo), ("libbar.dylib",) + libb_names[1:]
)
# If the name not found, raise an error
assert_raises(
InstallNameError,
set_install_name,
libfoo,
"liba.dylib",
"libpho.dylib",
)
def test_set_install_id():
# Test ability to change install id in library
liba_id = get_install_id(LIBA)
with InTemporaryDirectory() as tmpdir:
libfoo = pjoin(tmpdir, "libfoo.dylib")
shutil.copy2(LIBA, libfoo)
assert_equal(get_install_id(libfoo), liba_id)
set_install_id(libfoo, "libbar.dylib")
assert_equal(get_install_id(libfoo), "libbar.dylib")
# If no install id, raise error (unlike install_name_tool)
assert_raises(InstallNameError, set_install_id, TEST_LIB, "libbof.dylib")
def test_get_rpaths():
# Test fetch of rpaths
# Not dynamic libs, no rpaths
for fname in (LIBB, A_OBJECT, LIBA_STATIC, ICO_FILE, PY_FILE, BIN_FILE):
assert_equal(get_rpaths(fname), ())
def test_get_environment_variable_paths():
# Test that environment variable paths are fetched in a specific order
with TempDirWithoutEnvVars(
"DYLD_FALLBACK_LIBRARY_PATH", "DYLD_LIBRARY_PATH"
):
os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = "three"
os.environ["DYLD_LIBRARY_PATH"] = "two"
assert_equal(get_environment_variable_paths(), ("two", "three"))
def test_add_rpath():
# Test adding to rpath
with InTemporaryDirectory() as tmpdir:
libfoo = pjoin(tmpdir, "libfoo.dylib")
shutil.copy2(LIBB, libfoo)
assert_equal(get_rpaths(libfoo), ())
add_rpath(libfoo, "/a/path")
assert_equal(get_rpaths(libfoo), ("/a/path",))
add_rpath(libfoo, "/another/path")
assert_equal(get_rpaths(libfoo), ("/a/path", "/another/path"))
def _copy_libs(lib_files, out_path):
copied = []
if not exists(out_path):
os.makedirs(out_path)
for in_fname in lib_files:
out_fname = pjoin(out_path, basename(in_fname))
shutil.copy2(in_fname, out_fname)
copied.append(out_fname)
return copied
| e2826af6b90f723ef8a5baf06d037a3e0d569a84 | [
"TOML",
"Python"
]
| 4 | Python | PhillCli/delocate | 9c2c6a42c96b02602ce8d2059423a77e257a1a98 | c70eee1117a236df288b30e6128c4a3f0c20ed53 |
refs/heads/master | <file_sep>var puzzle_to_solve;
var solver_interval = null;
var is_running = false;
var can_set_constraints = false;
var palette_selection;
var backtrack_limit;
var backtracks_done = 0;
var total_backtracks_done = 0;
var restart_limit;
var restarts_done = 0;
//ONCLICK FUNCTIONS
function solve_button_clicked() {
if(puzzle_to_solve === undefined || puzzle_to_solve == null) {
window.alert("No puzzle to solve");
return -1;
}
if(is_running) return -1;
var delay_input = document.getElementById("time_input");
var restart_input = document.getElementById("restart_input");
var fail_input = document.getElementById("fail_input");
var delay = 100;
if(delay_input != undefined && delay_input != null) {
delay = parseInt(delay_input.value);
if(isNaN(delay) || delay < 0) delay = 100;
}
if(restart_input != undefined && restart_input != null) {
backtrack_limit = parseInt(restart_input.value);
if(isNaN(backtrack_limit) || backtrack_limit < 0)
backtrack_limit = undefined;
}
else {
backtrack_limit = undefined;
}
//Don't reset backtracks_done; needs to be preserved over pauses.
if(fail_input != undefined && fail_input != null) {
restart_limit = parseInt(fail_input.value);
if(isNaN(restart_limit) || restart_limit < 0)
restart_limit = undefined;
}
else {
restart_limit = undefined;
}
solver_interval = setInterval(solver_callback, delay);
is_running = true;
make_constraints_fixed();
set_status("Running");
}
//Create a new puzzle according to the values in the input fields.
function create_puzzle_clicked() {
if(is_running) return;
var size_input = document.getElementById("size_input");
var constraints_input = document.getElementById("constraints_input");
var display_area = document.getElementById("display_area");
var row_template = document.getElementById("display_row_template");
var field_template = document.getElementById("field_template");
if(size_input === null || constraints_input === null || display_area === null
|| row_template === null || field_template === null) return;
//Check that a valid board size is given
var size = parseInt(size_input.value);
var num_constraints = parseInt(constraints_input.value);
if(isNaN(size)) {
window.alert("A board size must be specified.");
return;
}
else if(size <= 0) {
window.alert("Board size must be greater than zero.");
return;
}
else if(size > 30) {
window.alert("Board size above 30 is not supported.");
//30 chosen because, with a larger board, the numbers will make the fields distort.
return;
}
if(isNaN(num_constraints)) {
window.alert("The number of initial constraints must be specified.");
return;
}
else if(num_constraints < 0) {
window.alert("Number of constraints cannot be negative.");
return;
}
else if(num_constraints > size*size) {
window.alert("There cannot be more constraints than grid squares.");
return;
}
field_matrix = create_puzzle_grid(size, display_area, row_template, field_template);
create_initial_constraints(field_matrix, num_constraints);
create_palette(size);
puzzle_to_solve = field_matrix;
reset_button_clicked(); //To get correct initial possibilities
make_constraints_settable();
}
//Creates a pattern that can demonstrate a heavy-tailed distribution of solving
//times (number of backtracks). Always creates 10x10.
function create_heavy_tailed_pattern() {
if(is_running) return;
var display_area = document.getElementById("display_area");
var row_template = document.getElementById("display_row_template");
var field_template = document.getElementById("field_template");
if(display_area === null || row_template === null || field_template === null) return;
field_matrix = create_puzzle_grid(10, display_area, row_template, field_template);
create_palette(10);
//Creating the pattern:
for(var i = 0; i < 4; i++) {
field_matrix[3-i][i].set_as_initial_constraint(10);
field_matrix[i+4][i+4].set_as_initial_constraint(10);
field_matrix[5-i][i+2].set_as_initial_constraint(7);
if(i < 3) field_matrix[9-i][i+7].set_as_initial_constraint(7);
}
puzzle_to_solve = field_matrix;
reset_button_clicked(); //To get correct initial possibilities
make_constraints_settable();
}
//Creates a pattern where the diagonal is filled with one colour, except for
//one cell, which is a different colour (this pattern has no solution). This
//pattern can be made at various board sizes.
function create_impossible_pattern() {
if(is_running) return;
var size_input = document.getElementById("size_input");
var display_area = document.getElementById("display_area");
var row_template = document.getElementById("display_row_template");
var field_template = document.getElementById("field_template");
if(size_input === null || display_area === null || row_template === null ||
field_template === null) return;
//Check that a valid board size is given
var size = parseInt(size_input.value);
var num_constraints = parseInt(constraints_input.value);
if(isNaN(size)) {
window.alert("A board size must be specified.");
return;
}
else if(size < 2) {
window.alert("Pattern requires a board size of at least 2");
return;
}
else if(size > 30) {
window.alert("Board size above 30 is not supported.");
return;
}
field_matrix = create_puzzle_grid(size, display_area, row_template, field_template);
create_palette(size);
//Creating the pattern:
var off_index = Math.floor(size/2);
var blue_val = Math.floor(2*size/3);
for(var i = 0; i < size; i++) {
if(i === off_index) field_matrix[i][i].set_as_initial_constraint(size);
else field_matrix[i][i].set_as_initial_constraint(blue_val);
}
puzzle_to_solve = field_matrix;
reset_button_clicked(); //To get correct initial possibilities
make_constraints_settable();
}
function stop_button_clicked() {
if(!is_running) return;
clearInterval(solver_interval);
solver_interval = null;
is_running = false;
//Should call this pause really
set_status("Paused");
}
function reset_button_clicked() {
if(is_running) return;
solve_call_stack = [];
backtracks_done = 0;
total_backtracks_done = 0;
restarts_done = 0;
if(puzzle_to_solve != undefined && puzzle_to_solve != null) {
reset_puzzle(puzzle_to_solve);
make_constraints_settable();
}
set_status("Ready");
}
function palette_field_clicked() {
if(!can_set_constraints) return;
if(palette_selection != undefined && palette_selection != null) {
palette_selection.display_deselect();
}
this.display_select();
palette_selection = this;
}
function puzzle_field_clicked() {
if(!can_set_constraints) return;
if(palette_selection === undefined || palette_selection === null) return;
this.unset_as_initial_constraint();
if(palette_selection.is_initial_constraint) { //Otherwise is unsetting field.
this.set_as_initial_constraint(palette_selection.value);
}
reset_button_clicked(); //Maintain possibilities.
}
//SOLVER CALLBACK
function solver_callback() {
//Is it time to restart?
if(backtrack_limit != undefined && backtrack_limit != null) {
if(backtracks_done > backtrack_limit) {
backtracks_done = 0;
reset_puzzle(puzzle_to_solve);
solve_call_stack = [];
restarts_done++;
}
}
var retval = take_solver_step(puzzle_to_solve);
if(restart_limit != undefined && restart_limit != null)
if(restarts_done > restart_limit)
retval = -2;
update_counters();
//console.log(retval.toString());
if(retval != 0)
{
clearInterval(solver_interval);
solver_interval = null;
is_running = false;
if(retval === -1) {
reset_button_clicked();
set_status("Failed: No Solution", "red");
}
else if(retval === -2) {
reset_button_clicked();
set_status("Failed: Limit Reached", "red");
}
else set_status("Solved", "blue");
}
}
//PUZZLE CREATION
//Creates a new puzzle grid with all fields empty, puts it in display_area.
function create_puzzle_grid(size, display_area, row_template, field_template) {
//Destroy the old board
var temp;
while(temp = display_area.lastChild) display_area.removeChild(temp);
//Create a new board
var field_matrix = [];
for(var i = 0; i < size; i++) {
var new_row = row_template.cloneNode();
new_row.id = "row_"+i.toString();
new_row.style.display = "flex";
display_area.appendChild(new_row);
var field_matrix_row = [];
field_matrix.push(field_matrix_row);
for(var j = 0; j < size; j++) {
var field_element = field_template.cloneNode();
field_element.id = "field_"+i.toString()+"_"+j.toString();
field_element.style.display = "block";
new_row.appendChild(field_element);
var field_object = new Field(size, field_element);
field_matrix_row.push(field_object);
field_element.onclick = puzzle_field_clicked.bind(field_object);
}
}
//Add sets of constraining fields. Could be faster but whatever.
for(var i1 = 0; i1 < size; i1++)
{
for(var j1 = 0; j1 < size; j1++)
{
for(var i2 = 0; i2 < size; i2++)
if(i2 != i1)
field_matrix[i1][j1].add_constraint(field_matrix[i2][j1]);
for(var j2 = 0; j2 < size; j2++)
if(j2 != j1)
field_matrix[i1][j1].add_constraint(field_matrix[i1][j2]);
}
}
return field_matrix;
}
//Selects num_constraints fields and fills each with a random value.
function create_initial_constraints(field_matrix, num_constraints) {
var usable_fields = [];
var chosen_fields = [];
for(var i = 0; i < field_matrix.length; i++) {
usable_fields = usable_fields.concat(field_matrix[i]);
}
for(var i = 0; i < num_constraints && usable_fields.length > 0; i++) {
var choice = Math.floor(Math.random()*usable_fields.length);
chosen_fields.push(usable_fields[choice]);
usable_fields.splice(choice, 1);
}
for(var i = 0; i < chosen_fields.length; i++) {
chosen_fields[i].update_options();
var retval = chosen_fields[i].set_as_initial_constraint();
if(retval != 1) {
window.alert("Chosen constraint field is already over-determined");
return;
}
}
}
function create_palette(size) {
var palette = document.getElementById("palette_area");
var field_template = document.getElementById("palette_field_template");
if(palette === undefined || palette === null) return;
if(field_template === undefined || field_template === null) return;
//Remove old options.
var temp;
while(temp = palette.lastChild) palette.removeChild(temp);
//Create blanke option.
var field_element = field_template.cloneNode();
field_element.id = "palette_field_blank";
field_element.style.display = "block";
field_element.appendChild(document.createTextNode("Clear"));
palette.appendChild(field_element);
var field_object = new Field(size, field_element);
field_element.onclick = palette_field_clicked.bind(field_object);
//Create color options.
for(var i = 0; i < size; i++) {
field_element = field_template.cloneNode();
field_element.id = "palette_field_"+i.toString();
field_element.style.display = "block";
palette.appendChild(field_element);
field_object = new Field(size, field_element);
field_object.set_as_initial_constraint(i+1);
field_element.onclick = palette_field_clicked.bind(field_object);
}
}
//OTHER
function make_constraints_settable() {
var palette = document.getElementById("palette_bar");
can_set_constraints = true;
if(palette != undefined && palette != null) {
palette.style.visibility = "visible";
}
}
function make_constraints_fixed() {
var palette = document.getElementById("palette_bar");
can_set_constraints = false;
if(palette != undefined && palette != null) {
palette.style.visibility = "hidden";
}
}
function update_counters() {
var backt = document.getElementById("backtracks_since_restart_display");
var total_backt = document.getElementById("total_backtracks_display");
var res = document.getElementById("restarts_display");
if(backt === undefined || total_backt === undefined || res === undefined) return;
backt.lastChild.nodeValue = backtracks_done.toString();
total_backt.lastChild.nodeValue = total_backtracks_done.toString();
res.lastChild.nodeValue = restarts_done.toString();
}
function set_status(status_text, status_color) {
var stat_disp = document.getElementById("status_display");
if(stat_disp === undefined || stat_disp === null) return;
if(status_color === undefined || status_color === null)
status_color = "black";
stat_disp.lastChild.nodeValue = status_text;
stat_disp.style.color = status_color
}
<file_sep>function Field(num_options, display_element) {
this.value = 0;
this.options = [];
this.max_option = num_options;
this.constraint_set = [];
this.display = display_element;
this.is_initial_constraint = false;
this.is_set = false;
this.set_externally = false;
this.update_options();
}
Field.prototype.remove_option = function(opt) {
var index = this.options.indexOf(opt);
if(index != -1)
this.options.splice(index, 1);
}
//Sets this field's value; choice is an index into options to determine what
//value to set. Assumes options are up-to-date (use update_options first if not).
Field.prototype.set_value = function(choice, fields_set) {
if(this.is_set) return 0;
if(this.options.length === 0) return -1;
//var choice = Math.floor(Math.random()*this.options.length);
this.value = this.options[choice];
this.display.style.backgroundColor = hue_to_hex(this.value / this.max_option);
this.display.appendChild(document.createTextNode(this.value.toString())); //TEMP
this.is_set = true;
fields_set.push(this);
for(var i = 0; i < this.constraint_set.length; i++)
{
var other = this.constraint_set[i];
if(other.is_initial_constraint) continue;
other.remove_option(this.value);
if(other.options.length === 0) return -1;
//Maybe need to store val & change things anyway to ensure things are put back properly?
if(!other.is_set && other.options.length === 1) {
//var retval = other.set_value(fields_set); //With this it's constraint propogation?
var retval = other.set_value_externally();
if(retval === -1) return -1;
fields_set.push(other);
}
}
return 1;
}
//Assumes there is only one possible value left
Field.prototype.set_value_externally = function() {
if(this.is_set) return 0;
if(this.options.length != 1) return -1;
this.value = this.options[0];
this.display.style.backgroundColor = hue_to_hex(this.value / this.max_option);
this.display.appendChild(document.createTextNode(this.value.toString())); //TEMP
this.is_set = true;
this.set_externally = true;
for(var i = 0; i < this.constraint_set.length; i++)
this.constraint_set[i].remove_option(this.value);
return 1;
}
Field.prototype.set_as_initial_constraint = function(value_arg) {
if(this.is_set) return 0;
if(this.options.length === 0) return -1;
if(value_arg === undefined || value_arg === null) {
choice = Math.floor(Math.random()*this.options.length);
this.value = this.options[choice];
}
else {
if(value_arg <= 0 || value_arg > this.max_option) return -1;
this.value = value_arg;
}
this.display.style.backgroundColor = hue_to_hex(this.value / this.max_option);
this.display.appendChild(document.createTextNode(this.value.toString())); //TEMP
this.is_set = true;
this.is_initial_constraint = true;
return 1;
}
Field.prototype.unset_as_initial_constraint = function() {
if(!this.is_initial_constraint) return 0;
this.is_initial_constraint = false;
this.unset_value();
return 1;
}
Field.prototype.unset_value = function() {
if(!this.is_set) return 0;
if(this.is_initial_constraint) return -1;
var old_val = this.value;
this.value = 0;
this.display.style.backgroundColor = "white";
this.display.removeChild(this.display.lastChild); //TEMP
this.is_set = false;
this.set_externally = false;
return 1;
}
Field.prototype.update_options = function() {
this.options = [];
if(this.is_set) { //If a field is set, its value is its only possible option.
this.options.push(this.value);
}
else {
for(var i = 1; i <= this.max_option; i++)
this.options.push(i);
}
for(var i = 0; i < this.constraint_set.length; i++)
if(this.constraint_set[i].is_set)
this.remove_option(this.constraint_set[i].value);
return this.options.length;
}
Field.prototype.add_constraint = function(new_constraint) {
this.constraint_set.push(new_constraint);
}
Field.prototype.concat_constraints = function(new_constraints) {
this.constraint_set = this.constraint_set.concat(new_constraints);
}
Field.prototype.display_select = function() {
this.display.style.border = "3px solid #000000";
}
Field.prototype.display_deselect = function() {
this.display.style.border = "3px solid #FFFFFF";
}
var solve_call_stack = [];
function take_solver_step(field_matrix) {
//Precondition: some fields have just been set or solving has just started
//(i.e. time to make a new frame).
if(solve_call_stack === undefined || solve_call_stack === null) return -1;
//Create new frame, return success if that frame has nothing to do.
var curr_frame = new SolveStackFrame(field_matrix);
solve_call_stack.push(curr_frame);
if(curr_frame.solving_succeeded()) return 1; //All done
while(curr_frame.continue_frame() === -1) {
solve_call_stack.pop();
backtracks_done++;
total_backtracks_done++;
if(solve_call_stack.length > 0) {
curr_frame = stack_peek();
}
else return -1;
}
return 0;
}
function stack_peek() {
if(solve_call_stack === undefined || solve_call_stack === null) return null;
if(solve_call_stack.length == 0) return null;
return solve_call_stack[solve_call_stack.length-1];
}
function compare_num_options(a, b) {
return a.options.length - b.options.length;
}
function reset_puzzle(field_matrix) {
for(var i = 0; i < field_matrix.length; i++)
for(var j = 0; j < field_matrix[i].length; j++)
field_matrix[i][j].unset_value();
for(var i = 0; i < field_matrix.length; i++)
for(var j = 0; j < field_matrix[i].length; j++)
field_matrix[i][j].update_options();
}
function hue_to_hex(h) {
var rgb;
var hp = (h*6)%6;
var x = Math.floor(15*(1 - Math.abs(hp%2 - 1)));
switch(Math.floor(hp)) {
case 0 : rgb = [15, x, 0];
break;
case 1 : rgb = [x, 15, 0];
break;
case 2 : rgb = [0, 15, x];
break;
case 3 : rgb = [0, x, 15];
break;
case 4 : rgb = [x, 0, 15];
break;
case 5 : rgb = [15, 0, x];
break;
default : rgb = [15,15,15];
}
return "#" + rgb[0].toString(16) + rgb[1].toString(16) + rgb[2].toString(16);
}
<file_sep>JS-based Latin Squares solver/visualization.
Allows creation of randomized puzzles with a specified size and number of initial
constraints. Constraints can also be manually added. Also includes two predefined
puzzles. One is unsolvable and takes the solver a relatively long time to
determine it is unsolvable. The other exhibits heavy-tailed behavior: usually it
will be solved quickly, but occassionally it will require a lot of backtracking.
The solver uses a backtracking search with forward checking. It is possible to
specify a number of allowed backtracks before restarting, and a number of allowed
restarts before failing.
Constraints and prospective assignments are displayed as a color as well as a
number. The display will be updated in real time as the solution is found. Given
the recursive nature of the solver and the use of single-threaded JavaScript, an
execution stack was simulated to facilitate the updating of the display while the
solution is in progress.
The purpose of this solver is to illustrate certain interesting behaviors of the
algorithm. As such there is an adjustable delay between each step of the solution.
| 33c3bed6eeac8253f857f472fd7ff02a1dbaa78a | [
"JavaScript",
"Text"
]
| 3 | JavaScript | mchlshr-laminar/Latin-Squares-Solver | ea09e62edbf7c12a7f804318f5253ec2118763bc | 68f50f9e298fd2a9c74eab8a166a9851a902cf85 |
refs/heads/master | <file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package metier.modele;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* @author Antoine
*/
@Entity
public class Sejour extends Voyage {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected int id;
private String residence;
public Sejour(Pays pays, String codeVoyage, String nom, String description, int duree,String residence) {
super(pays, codeVoyage, nom, description, duree);
this.residence = residence;
}
public Sejour() {
}
@Override
public int getId() {
return id;
}
@Override
public String toString() {
String s="Résidence :";
s+= residence;
return s;
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import java.util.List;
import javax.persistence.Query;
import metier.modele.Devis;
import metier.modele.Client;
/**
*
* @author Antoine
*/
public class DevisDAOJpa implements DevisDAO {
@Override
public void creerDevis(Devis d) {
JpaUtil.obtenirEntityManager().persist(d);
}
@Override
public void modifierDevis(Devis d) {
JpaUtil.obtenirEntityManager().merge(d);
}
@Override
public void supprimerDevis(Devis d) {
JpaUtil.obtenirEntityManager().remove(d);
}
@Override
public List<Devis> rechercherDevisParClient(Client c) {
Query q = JpaUtil.obtenirEntityManager().createQuery("Select d from Devis d where d.client= :client")
.setParameter("client", c);
List<Devis> d = (List<Devis>) q.getResultList();
return d;
}
@Override
public Devis rechercherDevisParId(int id) {
Query q = JpaUtil.obtenirEntityManager().createQuery("Select d from Devis d where d.id = :id")
.setParameter("id", id);
Devis d = (Devis) q.getSingleResult();
return d;
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import java.util.List;
import metier.modele.Conseiller;
import metier.modele.Pays;
/**
*
* @author Antoine
*/public interface ConseillerDAO {
/**
* Persiste un conseiller dans la base de données
* @param c
*/
public void creerConseiller(Conseiller c);
/**
* Modifie un conseiller persisté dans la base
* @param c
*/
public void modifierConseiller(Conseiller c);
/**
* Supprime un conseiller persisté dans la base
* @param c
*/
public void supprimerConseiller(Conseiller c);
/**
* Retourne les conseillers dont le nom est nom
* @param nom
* @return
*/
public List<Conseiller> rechercherConseillerParNom(String nom);
/**
* Retourne le conseiller dont l'id est id
* @param id
* @return
*/
public Conseiller rechercherConseillerParId(int id);
/**
* Retourne le conseiller dont l'e-mail est mail
* @param mail
* @return
*/
public Conseiller rechercherConseillerParMail(String mail);
/**
* Retourne le conseiller qui dispose du moins de clients pour le pays
* passé en paramètre
* @param p
* @return
*/
public Conseiller rechercherConseillerDispoParPays(Pays p);
/**
* Retourne le conseiller qui dispose du moins de clients
* @return
*/
public Conseiller rechercherConseillerDispo();
}
<file_sep>package util;
import au.com.bytecode.opencsv.CSVReader;
import dao.JpaUtil;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import metier.modele.Circuit;
import metier.modele.Client;
import metier.modele.Conseiller;
import metier.modele.Pays;
import metier.modele.Sejour;
import metier.modele.Vol;
import metier.modele.Voyage;
import metier.service.Service;
/**
* La classe LectureDonneesCsv permet (comme son nom l'indique) la lecture de
* données CSV dans des fichiers. Elle doit être complétée et personnalisée pour
* interagir avec VOTRE couche service pour la création effective des entités.
* Elle comprend initialement la lecture d'un fichier Clients et d'un fichier
* Pays. Une méthode {@link main()} permet de tester cette classe avant de
* l'intégrer dans le reste de votre code.
*
* @author <NAME> - 2013/2014
*/
public class LectureDonneesCsv {
Service service = new Service();
/**
* Format de date pour la lecture des dates dans les fichiers CSV fournis.
*/
protected static DateFormat CSV_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
/**
* Format de date pour l'affichage à l'écran.
*/
protected static DateFormat USER_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
/**
* Le lecteur de fichier CSV. Il doit être initialisé avant l'appel aux
* méthodes de la classe.
*/
protected CSVReader lecteurFichier;
/**
* Unique constructeur de la classe. Le fichier CSV donné en paramètre doit
* avoir le point-virgule ';' comme séparateur et être encodé en UTF-8. Le
* fichier est immédiatement ouvert (en lecture) par ce constructeur.
*
* @param cheminVersFichier Chemin vers le fichier CSV.
* @throws FileNotFoundException Si le chemin vers le fichier n'est pas
* valide ou le fichier non-lisible.
*/
public LectureDonneesCsv(String cheminVersFichier) throws FileNotFoundException, UnsupportedEncodingException {
this.lecteurFichier = new CSVReader(new InputStreamReader(new FileInputStream(cheminVersFichier), "UTF-8"), ';');
}
/**
* Ferme le fichier CSV. Les autres méthodes ne doivent plus être appelées
* après cela.
*
* @throws IOException
*/
public void fermer() throws IOException {
this.lecteurFichier.close();
}
/**
* Méthode statique pour lire une date à partir d'une chaîne de caractère.
* Adapté au format de date des fichiers CSV fournis, par exemple:
* 2014-02-01.
*
* @param date Chaîne de caractère représentant la date.
* @return La date interpétée ou la date actuelle en cas mauvais format en
* entrée.
*/
protected static Date parseDate(String date) {
try {
return CSV_DATE_FORMAT.parse(date);
} catch (ParseException ex) {
return new Date();
}
}
/**
* Méthode statique pour formater une date pour l'affichage. Par exemple:
* 01/02/2014.
*
* @param date Date à formater.
* @return Chaîne de caractère représentant la date.
*/
protected static String formatDate(Date date) {
return USER_DATE_FORMAT.format(date);
}
/**
* Méthode statique pour afficher l'en-tête d'un fichier CSV lu par le
* lecteur. L'affichage se fait sur la "sortie d'erreur" (en rouge dans la
* console sous Netbeans). Le nom des colonnes est précédé de leur index
* dans le tableau (commençant à 0).
*
* @param colonnes le tableau des noms de colonnes.
*/
protected static void afficherEnTeteCsv(String[] colonnes) {
for (int i = 0; i < colonnes.length; i++) {
if (i > 0) {
System.err.print("; ");
}
System.err.print("#" + Integer.toString(i) + " => " + colonnes[i]);
}
System.err.println();
}
/**
* Lit le fichier CSV, affiche son en-tête, puis appelle la création de
* Client pour chaque ligne.
*
* @param limite Nombre maximum de lignes à lire ou -1 pour ne pas limiter
* @throws IOException
*/
public void lireClients(int limite) throws IOException {
String[] nextLine;
// En-tete du fichier CSV
nextLine = this.lecteurFichier.readNext();
afficherEnTeteCsv(nextLine);
// Lecture des lignes
while ((nextLine = this.lecteurFichier.readNext()) != null) {
creerClient(nextLine);
// Limite (ou -1 si pas de limite)
if (!(limite < 0) && (--limite < 1)) {
break;
}
}
}
/**
* Créée un Client à partir de sa description. La date de naissance est
* notamment interpétée comme un objet Date.
*
* @param descriptionClient Ligne du fichier CSV de Clients.
*/
public void creerClient(String[] descriptionClient) {
/*String civilite = descriptionClient[0];
String nom = descriptionClient[1];
String prenom = descriptionClient[2];
Date dateNaissance = parseDate(descriptionClient[3]);
String adresse = descriptionClient[4];
String telephone = descriptionClient[5];
String email = descriptionClient[6];
String codeVoy = descriptionClient[7];*/
// System.out.println("CodeVoyCLient : " + codeVoy +" Client: "+ civilite + " " + nom + " " + prenom + ", né le " + formatDate(dateNaissance) + ", habitant à " + adresse + ", téléphone: " + telephone + ", e-mail: " + email);
Client client = new Client(descriptionClient[0], descriptionClient[1], descriptionClient[2], parseDate(descriptionClient[3]), descriptionClient[4], descriptionClient[5], descriptionClient[6], false);
Service.creerClientcsv(client, descriptionClient[7]);
}
/**
* Créée un Pays à partir de sa description. La superficie et la population
* sont notamment interpétées comme des nombres.
*
* @param descriptionPays Ligne du fichier CSV de Pays.
*/
public void creerPays(String[] descriptionPays) {
// String nom = descriptionPays[0];
// String code = descriptionPays[1];
// String region = descriptionPays[2];
// String capitale = descriptionPays[3];
// String langues = descriptionPays[4];
// float superficie = Float.parseFloat(descriptionPays[5]);
// float population = Float.parseFloat(descriptionPays[6]);
// String regime = descriptionPays[7];
Pays pays = new Pays(descriptionPays[0], descriptionPays[1], descriptionPays[2], descriptionPays[3], descriptionPays[4], Float.parseFloat(descriptionPays[5]), Float.parseFloat(descriptionPays[6]), descriptionPays[7]);
// System.out.println("Pays: "+ nom + " [" + code + "] (" + regime + "), Capitale: " + capitale + ", Région: " + region + ", Langues: " + langues + ", " + superficie + " km², " + population + " millions d'hbitants");
Service.creerPayscsv(pays);
}
/**
* Lit le fichier CSV, affiche son en-tête, puis appelle la création de Pays
* pour chaque ligne.
*
* @param limite Nombre maximum de lignes à lire ou -1 pour ne pas limiter
* @throws IOException
*/
public void lirePays(int limite) throws IOException {
String[] nextLine;
// En-tete du fichier CSV
nextLine = this.lecteurFichier.readNext();
afficherEnTeteCsv(nextLine);
// Lecture des lignes
while ((nextLine = this.lecteurFichier.readNext()) != null) {
creerPays(nextLine);
// Limite (ou -1 si pas de limite)
if (!(limite < 0) && (--limite < 1)) {
break;
}
}
}
/**
* Lit le fichier CSV, affiche son en-tête, puis appelle la création de
* Conseiller pour chaque ligne.
*
* @param limite Nombre maximum de lignes à lire ou -1 pour ne pas limiter
* @throws IOException
*/
public void lireVol(int limite) throws IOException {
String[] nextLine;
// En-tete du fichier CSV
nextLine = this.lecteurFichier.readNext();
afficherEnTeteCsv(nextLine);
// Lecture des lignes
while ((nextLine = this.lecteurFichier.readNext()) != null) {
creerVol(nextLine);
// Limite (ou -1 si pas de limite)
if (!(limite < 0) && (--limite < 1)) {
break;
}
}
}
/**
* Créée un Vol à partir de sa description. La superficie et la population
* sont notamment interpétées comme des nombres.
*
* @param descriptionVol Ligne du fichier CSV de Pays.
*/
public void creerVol(String[] descriptionVol) {
// String codeVoy = descriptionVol[0];
// Date dateDep = parseDate(descriptionVol[1]);
// String villeDep = descriptionVol[2];
// int prix = Integer.parseInt(descriptionVol[3]);
// String transport = descriptionVol[4];
// System.out.println("Vol: "+ codeVoy + " Tarif :" + prix + " Ville depart : " + villeDep + " transport : " + transport );
Vol vol = new Vol(parseDate(descriptionVol[1]), Integer.parseInt(descriptionVol[3]), descriptionVol[2], descriptionVol[4]);
Service.creerVolcsv(vol, descriptionVol[0]);
}
/**
* Lit le fichier CSV, affiche son en-tête, puis appelle la création de
* Conseiller pour chaque ligne.
*
* @param limite Nombre maximum de lignes à lire ou -1 pour ne pas limiter
* @throws IOException
*/
public void lireConseiller(int limite) throws IOException {
String[] nextLine;
// En-tete du fichier CSV
nextLine = this.lecteurFichier.readNext();
afficherEnTeteCsv(nextLine);
// Lecture des lignes
while ((nextLine = this.lecteurFichier.readNext()) != null) {
creerConseiller(nextLine);
// Limite (ou -1 si pas de limite)
if (!(limite < 0) && (--limite < 1)) {
break;
}
}
}
/**
* Créée un Conseiller à partir de sa description. La superficie et la
* population sont notamment interpétées comme des nombres.
*
* @param descriptionConseiller Ligne du fichier CSV de Pays.
*/
public void creerConseiller(String[] descriptionConseiller) {
// String civilite = descriptionConseiller[0];
// String nom = descriptionConseiller[1];
// String prenom = descriptionConseiller[2];
// Date dateNaissance = parseDate(descriptionConseiller[3]);
// String adresse = descriptionConseiller[4];
// String telephone = descriptionConseiller[5];
// String email = descriptionConseiller[6];
List<String> pays = new ArrayList<String>();
for (int i = 7; i < descriptionConseiller.length; i++) {
pays.add(descriptionConseiller[i]);
}
// System.out.println("Conseiller: "+ civilite + " " + nom + " " + prenom + ", né le " + formatDate(dateNaissance) + ", habitant à " + adresse + ", téléphone: " + telephone + ", e-mail: " + email);
Conseiller conseiller = new Conseiller(descriptionConseiller[0], descriptionConseiller[1], descriptionConseiller[2], parseDate(descriptionConseiller[3]), descriptionConseiller[4], descriptionConseiller[5], descriptionConseiller[6]);
Service.creerConseillercsv(conseiller, pays);
}
/**
* Lit le fichier CSV, affiche son en-tête, puis appelle la création de
* Sejours pour chaque ligne.
*
* @param limite Nombre maximum de lignes à lire ou -1 pour ne pas limiter
* @throws IOException
*/
public void lireSejours(int limite) throws IOException {
String[] nextLine;
// En-tete du fichier CSV
nextLine = this.lecteurFichier.readNext();
afficherEnTeteCsv(nextLine);
// Lecture des lignes
while ((nextLine = this.lecteurFichier.readNext()) != null) {
creerSejour(nextLine);
// Limite (ou -1 si pas de limite)
if (!(limite < 0) && (--limite < 1)) {
break;
}
}
}
/**
* Créée un Conseiller à partir de sa description. La superficie et la
* population sont notamment interpétées comme des nombres.
*
* @param descriptionSejour Ligne du fichier CSV de Sejours.
*/
public void creerSejour(String[] descriptionSejour) {
// String codePays = descriptionSejour[0];
// String codeVoy = descriptionSejour[1];
// String nom = descriptionSejour[2];
// int duree = Integer.parseInt(descriptionSejour[3]);
// String description = descriptionSejour[4];
// String residence = descriptionSejour[5];
// System.out.println("Sejour: "+ nom + " Code : " + codeVoy + " Description : " + description + " Duree : " + duree + "Residence : " + residence );
Pays pays = Service.rechercherPaysParCodePayscsv(descriptionSejour[0]);
Voyage sejour = new Sejour(pays, descriptionSejour[1], descriptionSejour[2], descriptionSejour[4], Integer.parseInt(descriptionSejour[3]), descriptionSejour[5]);
Service.creerVoyagecsv(sejour, descriptionSejour[0]);
}
/**
* Lit le fichier CSV, affiche son en-tête, puis appelle la création de
* Sejours pour chaque ligne.
*
* @param limite Nombre maximum de lignes à lire ou -1 pour ne pas limiter
* @throws IOException
*/
public void lireCircuit(int limite) throws IOException {
String[] nextLine;
// En-tete du fichier CSV
nextLine = this.lecteurFichier.readNext();
afficherEnTeteCsv(nextLine);
// Lecture des lignes
while ((nextLine = this.lecteurFichier.readNext()) != null) {
creerCircuit(nextLine);
// Limite (ou -1 si pas de limite)
if (!(limite < 0) && (--limite < 1)) {
break;
}
}
}
/**
* Créée un Circuit à partir de sa description. La superficie et la
* population sont notamment interpétées comme des nombres.
*
* @param descriptionCircuit Ligne du fichier CSV de Sejours.
*/
public void creerCircuit(String[] descriptionCircuit) {
// System.out.println("Circuit: "+ nom + " Code : " + codeVoy + " Description : " + description + " Duree : " + duree + " nbkm : " + nbkm + " Transport : " + transport );
Pays pays = (Pays) Service.rechercherPaysParCodePayscsv(descriptionCircuit[0]);
Circuit circuit = new Circuit(pays, descriptionCircuit[1], descriptionCircuit[2], descriptionCircuit[4], Integer.parseInt(descriptionCircuit[3]), Integer.parseInt(descriptionCircuit[6]), descriptionCircuit[5]);
Service.creerVoyagecsv(circuit, descriptionCircuit[0]);
}
/**
* Cette méthode main() permet de tester cette classe avant de l'intégrer
* dans votre code. Elle exploite initialement un fichier de Client et un
* fichier de Pays, en limitant la lecture aux 10 premiers éléments de
* chaque fichier.
*
* @param args non utilisé ici
*/
public static void main(String[] args) {
try {
String fichierClients = "data/IFRoutard-Clients.csv";
String fichierPays = "data/IFRoutard-Pays.csv";
String fichierConseillers = "data/IFRoutard-Conseillers.csv";
String fichierDeparts = "data/IFRoutard-Departs.csv";
String fichierCircuits = "data/IFRoutard-Voyages-Circuits.csv";
String fichierSejours = "data/IFRoutard-Voyages-Sejours.csv";
LectureDonneesCsv lectureDonneesCsv_Clients = new LectureDonneesCsv(fichierClients);
LectureDonneesCsv lectureDonneesCsv_Pays = new LectureDonneesCsv(fichierPays);
LectureDonneesCsv lectureDonneesCsv_Conseillers = new LectureDonneesCsv(fichierConseillers);
LectureDonneesCsv lectureDonneesCsv_Departs = new LectureDonneesCsv(fichierDeparts);
LectureDonneesCsv lectureDonneesCsv_Circuits = new LectureDonneesCsv(fichierCircuits);
LectureDonneesCsv lectureDonneesCsv_Sejours = new LectureDonneesCsv(fichierSejours);
//Pour tester: limite à 10
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
lectureDonneesCsv_Pays.lirePays(-1);
lectureDonneesCsv_Circuits.lireCircuit(-1);
lectureDonneesCsv_Sejours.lireSejours(-1);
lectureDonneesCsv_Departs.lireVol(-1);
lectureDonneesCsv_Conseillers.lireConseiller(-1);
lectureDonneesCsv_Clients.lireClients(100);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
// Puis, quand tout est au point!
//lectureDonneesCsv_Clients.lireClients(-1);
lectureDonneesCsv_Clients.fermer();
lectureDonneesCsv_Pays.fermer();
lectureDonneesCsv_Departs.fermer();
lectureDonneesCsv_Circuits.fermer();
lectureDonneesCsv_Sejours.fermer();
lectureDonneesCsv_Conseillers.fermer();
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
}
}
<file_sep>deploy.ant.properties.file=C:\\Users\\Maria-PC\\AppData\\Roaming\\NetBeans\\7.3\\gfv31366867125.properties
file.reference.derby.jar=E:\\3IF\\pp-raluca\\proiecte\\DASI 2\\PredictIF3429\\dist\\lib\\derbyclient.jar
file.reference.derbyclient.jar=E:\\3IF\\pp-raluca\\proiecte\\DASI 2\\PredictIF3429\\dist\\lib\\derbyclient.jar
file.reference.derbynet.jar=C:\\Users\\Maria-PC\\Desktop\\B3427\\Routard\\Routard\\IF_Routard_Web\\opencsv-2.3.jar
file.reference.eclipselink-2.3.2.jar=E:\\3IF\\pp-raluca\\proiecte\\DASI 2\\PredictIF3429\\dist\\lib\\derbyclient.jar
file.reference.javax.persistence-2.0.3.jar=C:\\Users\\Maria-PC\\Desktop\\B3427\\BDD\\derby.log
file.reference.opencsv-2.3.jar=C:\\Users\\Maria-PC\\Desktop\\B3427\\Routard\\Routard\\IF_Routard_Web\\opencsv-2.3.jar
file.reference.org.eclipse.persistence.jpa.jpql_1.0.1.jar=C:\\Users\\Maria-PC\\Desktop\\B3427\\Routard\\Routard\\IF_Routard_Web\\opencsv-2.3.jar
j2ee.platform.is.jsr109=true
j2ee.server.domain=C:/Users/Maria-PC/AppData/Roaming/NetBeans/7.3/config/GF3/domain1
j2ee.server.home=C:/Program Files/glassfish-3.1.2.2/glassfish
j2ee.server.instance=[C:\\Program Files\\glassfish-3.1.2.2\\glassfish;C:\\Program Files\\glassfish-3.1.2.2\\glassfish\\domains\\domain1]deployer:gfv3ee6wc:localhost:4848
j2ee.server.middleware=C:/Program Files/glassfish-3.1.2.2
user.properties.file=C:\\Users\\Maria-PC\\AppData\\Roaming\\NetBeans\\7.3\\build.properties
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import metier.service.Service;
/**
*
* @author Administrateur
*/
public abstract class Action {
protected Service service;
public void setServiceMetier(Service service)
{
this.service=service;
}
public abstract boolean execute (HttpServletRequest request );
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import metier.modele.Consultant;
/**
*
* @author Antoine
*/
public class ConsultantDAOJpa implements ConsultantDAO {
@Override
public void creerConsultant(Consultant c) {
//TODO Ajouter try catch
JpaUtil.obtenirEntityManager().persist(c);
}
@Override
public void modifierConsultant(Consultant c) {
JpaUtil.obtenirEntityManager().merge(c);
}
@Override
public void supprimerConsultant(Consultant c) {
JpaUtil.obtenirEntityManager().remove(c);
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import action.Action;
import action.InscriptionAction;
import action.LoginAction;
import action.SelectionAction;
import action.SelectionActionD;
import action.SelectionActionP;
import action.SelectionActionT;
import dao.JpaUtil;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Administrateur
*/
@WebServlet(name = "ActionServlet", urlPatterns = {"/ActionServlet"})
public class ActionServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String tache = request.getParameter("todo");
System.out.println(tache);
Action action = this.getAction(tache);
if(action!=null)
{
action.execute(request);
}
String vue = this.setVue(tache);
request.getRequestDispatcher(vue).forward(request, response);
destroy();
}
private Action getAction(String todo)
{
Action action = null;
if( "validerInscription".equals(todo) )
{
action = new InscriptionAction();
}
if( "authentification".equals(todo))
{
action = new LoginAction();
}
if( "selectionerVoyage".equals(todo))
{
action = new SelectionAction();
}
if( "selectionerVoyageT".equals(todo))
{
action = new SelectionActionT();
}
if( "selectionerVoyageD".equals(todo))
{
action = new SelectionActionD();
}
if( "selectionerVoyageP".equals(todo))
{
action = new SelectionActionP();
}
return action;
}
private String setVue(String todo)
{
String vue = null;
if( "inscription".equals(todo) ) {
vue = "Inscription.jsp" ;
}
if( "login".equals(todo) ||"authentification".equals(todo) )
{
vue = "login.jsp";
}
if( "selectionerVoyage".equals(todo)|| "validerInscription".equals(todo)||"selectionerVoyageT".equals(todo)||"selectionerVoyageP".equals(todo)||"selectionerVoyageD".equals(todo))
{
vue = "selectionVoyage.jsp";
}
return vue;
}
@Override
public void init() throws ServletException {
super.init();
JpaUtil.init();
}
@Override
public void destroy() {
super.destroy();
JpaUtil.destroy();
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>package action;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import metier.modele.Client;
import metier.modele.Pays;
import metier.modele.Voyage;
import metier.service.Service;
/**
*
* @author Administrateur
*/
//@WebServlet(name = "inscription", urlPatterns = {"/inscription"})
public class InscriptionAction extends Action {
/**
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
@Override
public boolean execute (HttpServletRequest request )
{
List<Pays> pays = Service.rechercherPays();
List <Voyage> voyages = Service.rechercherVoyage();
request.setAttribute("voyages", voyages);
if(!pays.isEmpty())request.setAttribute("pays", pays);
else{
Pays p=new Pays();
request.setAttribute("pays", p);
}
String civilite = (String)request.getParameter("civilite");
String nom = (String)request.getParameter("nom");
String prenom = (String)request.getParameter("prenom");
String mail =(String) request.getParameter("mail");
String dateNaissance =(String) request.getParameter("dateNaiss");
DateFormat CSV_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
Date dateNaiss = new Date();
try {
dateNaiss = CSV_DATE_FORMAT.parse(dateNaissance);
} catch (ParseException ex) {
}
String tel = (String)request.getParameter("tel");
String adresse = (String) request.getParameter("adresse");
String password = (String)request.getParameter("password");
String confirmation = (String)request.getParameter("confirmation");
String enregistre;
if(confirmation.equals(password)) {
Client c = new Client(civilite, nom, prenom, dateNaiss, adresse, tel, mail, password, true);
Service.creerClient(c);
if (dateNaiss != null && nom != null && !nom.equals("")) {
enregistre = "ok";
request.getSession().setAttribute("client", c);
} else {
enregistre = "fail"; //le client n'a pas pu s'enregister
}
} else {
enregistre = "fail";
}
request.getSession().setAttribute("enregistre", enregistre);
return true;
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package metier.modele;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author Amaury
*/
@Entity
public class Client implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String civilite;
private String nom;
private String prenom;
@Temporal(TemporalType.DATE) //DATE,TIME OU TIMESTAMP
private Date dateNaiss;
private String adresse;
private String tel;
private String mail;
private String password;
private Short spam;
@OneToMany(mappedBy = "client", cascade = CascadeType.PERSIST)
private List<Devis> devis = new ArrayList();
public String getCivilite() {
return civilite;
}
public void setCivilite(String civilite) {
this.civilite = civilite;
}
public String getNom() {
return nom;
}
public boolean isSpam() {
return (spam==1);
}
public void setSpam(boolean spam) {
this.spam = (short)(spam?1:0);
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId() {
return id;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public Date getDateNaiss() {
return dateNaiss;
}
public void setDateNaiss(Date date) {
this.dateNaiss = date;
}
public List<Devis> getDevis() {
return devis;
}
public void setDevis(List<Devis> devis) {
this.devis = devis;
}
public void addDevis(Devis devis) {
this.devis.add(devis);
}
/**
* Constructeur par défaut de client
*/
public Client() {
}
public Client(String civilite, String nom, String prenom, Date dateNaiss, String adresse, String tel, String mail, String password, boolean spam) {
this.civilite = civilite;
this.nom = nom;
this.prenom = prenom;
this.dateNaiss = dateNaiss;
this.adresse = adresse;
this.tel = tel;
this.mail = mail;
this.password = <PASSWORD>;
this.spam = (short)(spam?1:0);
}
public Client(String civilite, String nom, String prenom, Date dateNaiss, String adresse, String tel, String mail, boolean spam) {
this.civilite = civilite;
this.nom = nom;
this.prenom = prenom;
this.dateNaiss = dateNaiss;
this.adresse = adresse;
this.tel = tel;
this.mail = mail;
this.password = "<PASSWORD>";
this.spam = (short)(spam?1:0);
}
@Override
public String toString() {
return nom + " " + prenom + "\n" + adresse + "\n" + tel;
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import java.util.Date;
import java.util.List;
import metier.modele.Pays;
import metier.modele.Voyage;
/**
*
* @author Antoine
*/
public interface VoyageDAO{
/**
* Persiste un voyage dans la base de données
* @param v
*/
public void creerVoyage(Voyage v);
/**
* Modifie un voyage persisté dans la base de données
* @param v
*/
public void modifierVoyage(Voyage v);
/**
* Supprime le voyage persisté de la base de données
* @param v
*/
public void supprimerVoyage(Voyage v);
/**
* Retourne tous les voyages de la base
* @return
*/
public List<Voyage> rechercherVoyage();
/**
* Retourne le voyage dont le nom est nom
* @param nom
* @return
*/
public Voyage rechercherVoyageParNom(String nom);
/**
* Retourne le voyage dont l'id est id
* @param id
* @return
*/
public Voyage rechercherVoyageParId(int id);
/**
* Retourne le voyage dont le code est codeVoy
* @param codeVoy
* @return
*/
public Voyage rechercherVoyageParCode(String codeVoy);
/**
* Retourne les voyages qui débutent à la date passée en paramètre
* @param date
* @return
*/
public List<Voyage> rechercherVoyageParDate(Date date);
/**
* Retourne les voyages dont la durée est comprise entre min et max
* @param min
* @param max
* @return
*/
public List<Voyage> rechercherVoyageParDuree(int min,int max);
/**
* Retourne les voyages qui se déroulent dans le pays passé en paramètre
* @param pays
* @return
*/
public List<Voyage> rechercherVoyageParPays(Pays pays);
/**
* Retourne les voyages qui correspondent aux filtres passés en paramètre
* @param codeVoyage
* @param nom
* @param pays
* @return
*/
public List<Voyage> rechercheFiltre (String codeVoyage, String nom, String pays);
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import java.util.Iterator;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import metier.modele.Conseiller;
import metier.modele.Pays;
/**
*
* @author Antoine
*/
public class ConseillerDAOJpa implements ConseillerDAO {
@Override
public void creerConseiller(Conseiller c) {
JpaUtil.obtenirEntityManager().persist(c);
}
@Override
public void modifierConseiller(Conseiller c) {
JpaUtil.obtenirEntityManager().merge(c);
}
@Override
public void supprimerConseiller(Conseiller c) {
JpaUtil.obtenirEntityManager().remove(c);
}
@Override
public List<Conseiller> rechercherConseillerParNom(String nom) {
Query q = dao.JpaUtil.obtenirEntityManager().createQuery("Select c from Conseiller c where c.nom= :nom")
.setParameter("nom", nom);
List<Conseiller> c = (List<Conseiller>) q.getResultList();
return c;
}
@Override
public Conseiller rechercherConseillerParId(int id) {
Query q = dao.JpaUtil.obtenirEntityManager().createQuery("Select c from Conseiller c where c.id= :id")
.setParameter("id", id);
Conseiller c = (Conseiller) q.getSingleResult();
return c;
}
@Override
public Conseiller rechercherConseillerParMail(String mail) {
Query q = JpaUtil.obtenirEntityManager().createQuery("Select c from Conseiller c where c.mail= :mail")
.setParameter("mail", mail);
Conseiller c = (Conseiller) q.getSingleResult();
return c;
}
@Override
public Conseiller rechercherConseillerDispoParPays(Pays pays) {
try {
Query q = JpaUtil.obtenirEntityManager().createQuery("Select c "
+ "FROM Conseiller c join c.pays p "
+ "where p.id = :pays "
+ "order by c.nbreClient ASC");
q.setParameter("pays", pays.getId());
q.setMaxResults(1);
Conseiller conseiller = (Conseiller) q.getSingleResult();
return conseiller;
} catch (NoResultException e) {
return null;
}
}
@Override
public Conseiller rechercherConseillerDispo() {
try {
Query query = JpaUtil.obtenirEntityManager().createQuery("SELECT c FROM Conseiller c "
+ "ORDER BY c.nbreClient ASC");
query.setMaxResults(1);
Conseiller conseiller = (Conseiller) query.getSingleResult();
return conseiller;
} catch (NoResultException e) {
return null;
}
}
}<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import java.util.List;
import javax.persistence.Query;
import metier.modele.Client;
/**
*
* @author Antoine
*/
public class ClientDAOJpa implements ClientDAO {
@Override
public void creerClient(Client c) {
JpaUtil.obtenirEntityManager().persist(c);
}
@Override
public void modifierClient(Client c) {
JpaUtil.obtenirEntityManager().merge(c);
}
@Override
public void supprimerClient(Client c) {
JpaUtil.obtenirEntityManager().remove(c);
}
@Override
public List<Client> rechercherClient() {
Query q = JpaUtil.obtenirEntityManager().createQuery("Select c from Client c");
List<Client> c = (List<Client>) q.getResultList();
return c;
}
@Override
public List<Client> rechercherClientParNom(String nom) {
Query q = JpaUtil.obtenirEntityManager().createQuery("Select c from Client c where c.nom= :nom")
.setParameter("nom", nom);
List<Client> c = (List<Client>) q.getResultList();
return c;
}
@Override
public Client rechercherClientParId(int id) {
Query q = JpaUtil.obtenirEntityManager().createQuery("Select c from Client c where c.id= :id")
.setParameter("id", id);
Client c = (Client) q.getSingleResult();
return c;
}
@Override
public Client rechercherClientParMail(String mail) {
Query q = JpaUtil.obtenirEntityManager().createQuery("Select c from Client c where c.mail= :mail")
.setParameter("mail", mail);
Client c = (Client) q.getSingleResult();
return c;
}
@Override
public boolean rechercherClientConnexion(String mail, String mdp) {
try
{
Query q = JpaUtil.obtenirEntityManager().createQuery("Select c from Client c where c.mail= :mail and c.password = :mdp")
.setParameter("mail", mail).setParameter("mdp", mdp);
Client c = (Client) q.getSingleResult();
}
catch (Exception e)
{
return false;
}
return true;
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package metier.modele;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
/**
*
* @author Antoine
*/
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Voyage implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected int id;
protected String codeVoyage;
protected String nom;
protected String description;
protected int duree;
/**
* Liste des vols disponibles pour ce voyage
*/
@OneToMany( mappedBy = "voyage")
private List<Vol> vols;
@OneToMany(mappedBy = "voyage")
private List<Devis> devis;
@ManyToOne
private Pays pays;
public Voyage() {
}
public Voyage(Pays pays, String codeVoyage, String nom, String description, int duree) {
this.codeVoyage = codeVoyage;
this.nom = nom;
this.description = description;
this.duree = duree;
this.pays = pays;
this.devis = new ArrayList();
this.vols = new ArrayList();
}
public List<Vol> getVols() {
return vols;
}
public void setVols(List<Vol> vols) {
this.vols = vols;
}
public List<Devis> getDevis() {
return devis;
}
public void setDevis(List<Devis> devis) {
this.devis = devis;
}
public void addDevis(Devis d) {
this.devis.add(d);
}
public int getId() {
return id;
}
public Pays getPays() {
return pays;
}
public void setPays(Pays pays) {
this.pays = pays;
}
public String getCodeVoyage() {
return codeVoyage;
}
public void setCodeVoyage(String codeVoyage) {
this.codeVoyage = codeVoyage;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getDuree() {
return duree;
}
public void setDuree(int duree) {
this.duree = duree;
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import java.util.List;
import metier.modele.Client;
/**
*
* @author Antoine
*/
public interface ClientDAO {
/**
* Persiste un client dans la base de données
* @param c
*/
public void creerClient(Client c);
/**
* Modifie un client persisté dans la base de données
* @param c
*/
public void modifierClient(Client c);
/**
* Supprime un client persisté dans la base de données
* @param c
*/
public void supprimerClient(Client c);
/**
* Retourne tous les clients de la base de données
* @return
*/
public List<Client> rechercherClient();
/**
* Retourne les clients dont le nom est nom
* @param nom
* @return
*/
public List<Client> rechercherClientParNom(String nom);
/**
* Retourne le client dont l'id est id
* @param id
* @return
*/
public Client rechercherClientParId(int id);
/**
* Retourne le client dont l'e-mail est mail
* @param mail
* @return
*/
public Client rechercherClientParMail(String mail);
/**
* Retourne true si un client existe avec ce mail et ce mot de passe dans la base.
* False sinon.
* @param mail Email du client
* @param mdp Mot de passe du client
* @return
*/
public boolean rechercherClientConnexion(String mail, String mdp);
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package metier.service;
import dao.ClientDAO;
import dao.ClientDAOJpa;
import dao.ConseillerDAO;
import dao.ConseillerDAOJpa;
import dao.DevisDAO;
import dao.DevisDAOJpa;
import dao.JpaUtil;
import dao.PaysDAO;
import dao.PaysDAOJpa;
import dao.VolDAO;
import dao.VolDAOJpa;
import dao.VoyageDAO;
import dao.VoyageDAOJpa;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import metier.modele.Client;
import metier.modele.Conseiller;
import metier.modele.Devis;
import metier.modele.Pays;
import metier.modele.Vol;
import metier.modele.Voyage;
/**
*
* @author Antoine
*/
public class Service {
private static ClientDAO clientDAO = new ClientDAOJpa();
private static ConseillerDAO conseillerDAO = new ConseillerDAOJpa();
private static DevisDAO devisDAO = new DevisDAOJpa();
private static PaysDAO paysDAO = new PaysDAOJpa();
private static VoyageDAO voyageDAO = new VoyageDAOJpa();
private static VolDAO volDAO = new VolDAOJpa();
/**
*
* Crée un devis dans la bdd à partir des attributs en parametre. Sert
* uniquement pour rentrer les données csv
*
* @param nbPersonne =1 en général
* @param client Client depuis le quel le service à été généré
* @param codeVoy Code associé au client dans les données csv.
*/
public static Devis creerDeviscsv(int nbPersonne, Client client, String codeVoy) {
Voyage voyage = rechercherVoyageParCodecsv(codeVoy);
//On attribue un conseiller disponible au client dans ce nouveau devis
Conseiller conseiller = rechercherConseillerDispoParPayscsv(voyage.getPays());
if (conseiller == null)//Si aucun conseiller n'est spécialiste de ce pays, on attribue le conseiller qui
//travaille le moins à ce nouveau pays
{
conseiller = rechercherConseillerDispocsv();
}
//Selection du premier vol de la liste des vols du voyage associé (par defaut)
Vol vol = rechercherUnVolParVoyagecsv(codeVoy);
Devis d = new Devis(client, conseiller, voyage, vol, nbPersonne);
client.addDevis(d);
conseiller.addDevis(d);
conseiller.ajouterClient();
voyage.addDevis(d);
modifierClientcsv(client);
modifierConseillercsv(conseiller);
modifierVoyagecsv(voyage);
// JpaUtil.creerEntityManager();
// JpaUtil.ouvrirTransaction();
devisDAO.creerDevis(d);
// JpaUtil.validerTransaction();
// JpaUtil.fermerEntityManager();
return d;
}
/**
*
* Génére un devis pour un client comportant un vol et un voyage, et
* attribue un conseiller au client
*
* @param nbPersonne renseigné par le client dans l'ihm Web
* @param client Client ayant généré le devis depuis l'ihm Web
* @param voyage Voyage concerné par la génération du devis
* @param vol Vol sélectionné par le client lors de la génération du devis
*/
public static Devis creerDevis(int nbPersonne, Client client, Voyage voyage, Vol vol) {
//On attribue un conseiller au client dans ce nouveau devis
Conseiller conseiller = rechercherConseillerDispoParPays(voyage.getPays());
//Conseiller conseiller = ListeConseiller.get(util.Aleatoire.random(ListeConseiller.size()));
//Ajout d pays du voyage dans la liste des pays du conseiller choisi
conseiller.ajouterClient();
modifierClientcsv(client);
modifierConseillercsv(conseiller);
modifierVoyagecsv(voyage);
//Creation du devis
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Devis d = new Devis(client, conseiller, voyage, vol, nbPersonne);
devisDAO.creerDevis(d);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return d;
}
/**
* Utilisée uniquement pour la génération des clients depuis les fichiers
* csv Création d'un client puis génération d'un devis avec le codeVoyage et
* choix du premier départ
*
* @param c : ligne du fichier csv
* @param codeVoy : Réorgannisation des données : codeVoy n'est plus un
* attribut de client mais génére un devis
*/
public static void creerClientcsv(Client c, String codeVoy) {
clientDAO.creerClient(c);
Devis d = creerDeviscsv(1, c, codeVoy);
}
/**
* Création d'un client après son eneregistrement sur l'ihm web
*
* @param c : Client
*/
public static void creerClient(Client c) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
clientDAO.creerClient(c);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Modifie le client passé en paramètre dans la base de données
*
* @param c Client devant être modifié
*/
public static void modifierClient(Client c) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
clientDAO.modifierClient(c);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Modifie le client passé en paramètre en utilisant l'entity manager actuel
*
* @param c Client devant être modifié
*/
public static void modifierClientcsv(Client c) {
clientDAO.modifierClient(c);
}
/**
* Supprime le client passé en paramètre de la base de donnée
*
* @param c Client devant être supprimé
*/
public static void supprimerClient(Client c) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
clientDAO.supprimerClient(c);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Crée un pays dans la base de données
*
* @param p Pays devant être créé
*/
public static void creerPays(Pays p) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
paysDAO.creerPays(p);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Crée un pays dans la base de données en utilisant l'entity manager actuel
*
* @param p
*/
public static void creerPayscsv(Pays p) {
paysDAO.creerPays(p);
}
/**
* Modifie un pays dans la base de données
*
* @param p
*/
public static void modifierPays(Pays p) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
paysDAO.modifierPays(p);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Modifie un pays dans la base de données en utilisant l'entity manager
* actuel
*
* @param p
*/
public static void modifierPayscsv(Pays p) {
paysDAO.modifierPays(p);
}
/**
* Supprime un pays de la base de données
*
* @param p
*/
public static void supprimerPays(Pays p) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
paysDAO.supprimerPays(p);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Création d'un conseiller depuis la base Csv
* @param c
* @param codePays
*/
public static void creerConseillercsv(Conseiller c, List<String> codePays) {
Iterator itr = codePays.iterator();
conseillerDAO.creerConseiller(c);
while (itr.hasNext()) {
Pays pays = rechercherPaysParCodePayscsv((String) itr.next());
c.AjouterPays(pays);
pays.ajouterConseiller(c);
modifierPayscsv(pays);
}
}
/**
* Modifie le conseiller passé en paramètre dans la base de données
* @param c
*/
public static void modifierConseiller(Conseiller c) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
conseillerDAO.modifierConseiller(c);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Modifie le conseiller passé en paramètre en utilisant l'entity manager actuel
* @param c
*/
public static void modifierConseillercsv(Conseiller c) {
conseillerDAO.modifierConseiller(c);
}
/**
* Supprime le conseiller de la base de données
* @param c
*/
public static void supprimerConseiller(Conseiller c) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
conseillerDAO.supprimerConseiller(c);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Crée un vol et l'associe avec le voyage dont le code est égal à voyage
* @param v Vol
* @param voyage Code du voyage auquel le vol doit être associé
*/
public static void creerVol(Vol v, String voyage) {
Voyage voy = rechercherVoyageParCode(voyage);
v.setVoyage(voy);
modifierVoyage(voy);
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
volDAO.creerVol(v);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Crée un vol et l'associe avec le voyage dont le code est égal à voyage
* en utilisant l'entity manager actuel
* @param v Vol
* @param voyage Code du voyage auquel le vol doit être associé
*/
public static void creerVolcsv(Vol v, String voyage) {
Voyage voy = rechercherVoyageParCodecsv(voyage);
v.setVoyage(voy);
modifierVoyagecsv(voy);
volDAO.creerVol(v);
}
/**
* Crée un vol dans la base de données
* @param v
*/
/*public void creerVol(Vol v) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
volDAO.creerVol(v);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}*/
/**
* Modifie le vol passé en paramètre dans la base de données
* @param v
*/
public static void modifierVol(Vol v) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
volDAO.modifierVol(v);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Supprime le vol de la base de données
* @param v
*/
public static void supprimerVol(Vol v) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
volDAO.supprimerVol(v);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Crée un voyage et l'associe au pays dont le code est égal à codePays
* @param v
* @param codePays
*/
public static void creerVoyage(Voyage v, String codePays) {
Pays pays = rechercherPaysParCodePays(codePays);
pays.addVoyage(v);
modifierPays(pays);
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
voyageDAO.creerVoyage(v);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Crée un voyage et l'associe au pays dont le code est égal à codePays
* en utilisant l'entity manager actuel
* @param v
* @param codePays
*/
public static void creerVoyagecsv(Voyage v, String codePays) {
Pays pays = rechercherPaysParCodePayscsv(codePays);
pays.addVoyage(v);
v.setPays(pays);
modifierPayscsv(pays);
//voyageDAO.creerVoyage(v);
}
public static boolean connexionClient(String email, String mdp)
{
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
boolean connexion = clientDAO.rechercherClientConnexion(email, mdp);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return connexion;
}
/**
* Modifie la voyage dans la base de données
* @param v
*/
public static void modifierVoyage(Voyage v) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
voyageDAO.modifierVoyage(v);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
/**
* Modifie la voyage dans la base de données en utilisant l'entity manager actuel
* @param v
*/
public static void modifierVoyagecsv(Voyage v) {
voyageDAO.modifierVoyage(v);
}
/**
* Supprime le voyage de la base de données
* @param v
*/
public static void supprimerVoyage(Voyage v) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
voyageDAO.supprimerVoyage(v);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
}
//------------Services de recherche------------------------
/**
* Retourne tous les clients de la base de données
* @return tous les clients de la base
*/
public static List<Client> rechercherClient() {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Client> client = clientDAO.rechercherClient();
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return client;
}
/**
* Retourne tous les clients dont le nom = nom
* @param nom
* @return
*/
public static List<Client> rechercherClientParNom(String nom) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Client> client = clientDAO.rechercherClientParNom(nom);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return client;
}
/**
* Retourne le client dont l'id est id
* @param id
* @return
*/
public static Client rechercherClientParId(int id) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Client client = clientDAO.rechercherClientParId(id);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return client;
}
/**
* Retourne le client dont l' e-mail est mail
* @param mail
* @return
*/
public static Client rechercherClientParMail(String mail) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Client client = clientDAO.rechercherClientParMail(mail);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return client;
}
/**
* Retourne la liste des conseillers dont le nom est nom
* @param nom
* @return
*/
public static List<Conseiller> rechercherConseillerParNom(String nom) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Conseiller> conseiller = conseillerDAO.rechercherConseillerParNom(nom);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return conseiller;
}
/**
* Retourne le conseiller dont l'id est id
* @param id
* @return
*/
public static Conseiller rechercherConseillerParId(int id) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Conseiller conseiller = conseillerDAO.rechercherConseillerParId(id);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return conseiller;
}
/**
* Retourne le conseiller dont l'e-mail est mail
* @param mail
* @return
*/
public static Conseiller rechercherConseillerParMail(String mail) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Conseiller conseiller = conseillerDAO.rechercherConseillerParMail(mail);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return conseiller;
}
/**
* Retourne le conseiller disposant du moins de clients pour le pays passé en paramètre
* @param p
* @return
*/
public static Conseiller rechercherConseillerDispoParPays(Pays p) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Conseiller conseiller = conseillerDAO.rechercherConseillerDispoParPays(p);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return conseiller;
}
/**
* Retourne le conseiller disposant du moins de clients pour le pays passé en paramètre
* en utilisant l'entity manager actuel
* @param p
* @return
*/
public static Conseiller rechercherConseillerDispoParPayscsv(Pays p) {
Conseiller conseiller = conseillerDAO.rechercherConseillerDispoParPays(p);
return conseiller;
}
/**
* Retourne le conseiller disposant du moins de clients
* @return
*/
public static Conseiller rechercherConseillerDispo() {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Conseiller conseiller = conseillerDAO.rechercherConseillerDispo();
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return conseiller;
}
/**
* Retourne le conseiller disposant du moins de clients en utilisant l'entity manager actuel
* @return
*/
public static Conseiller rechercherConseillerDispocsv() {
Conseiller conseiller = conseillerDAO.rechercherConseillerDispo();
return conseiller;
}
/**
* Retourne la liste des devis du client passé en paramètre
* @param c
* @return
*/
public static List<Devis> rechercherDevisParClient(Client c) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Devis> devis = devisDAO.rechercherDevisParClient(c);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return devis;
}
/**
* Retourne le pays dont l'id est id
* @param id
* @return
*/
public static Pays rechercherPaysParId(int id) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Pays pays = paysDAO.rechercherPaysParId(id);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return pays;
}
/**
* Retourne le pays dont le nom est nom
* @param nom
* @return
*/
public static Pays rechercherPaysParNom(String nom) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Pays pays = paysDAO.rechercherPaysParNom(nom);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return pays;
}
/**
* Retourne une liste de pays sur le continent passé en paramètre
* @param continent
* @return
*/
public static List<Pays> rechercherPaysParContinent(String continent) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Pays> pays = paysDAO.rechercherPaysParContinent(continent);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return pays;
}
/**
* Retourne tous les pays de la base
* @return
*/
public static List<Pays> rechercherPays() {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Pays> pays = paysDAO.rechercherPays();
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return pays;
}
/**
* Retourne le pays dont le code est codePays
* @param codePays
* @return
*/
public static Pays rechercherPaysParCodePays(String codePays) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Pays pays = paysDAO.rechercherPaysParCodePays(codePays);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return pays;
}
/**
* Retourne le pays dont le code est codePays en utilisant l'entity manager actuel
* @param codePays
* @return
*/
public static Pays rechercherPaysParCodePayscsv(String codePays) {
Pays pays = paysDAO.rechercherPaysParCodePays(codePays);
return pays;
}
/**
* Retourne tous les Vols de la base
* @return
*/
public static List<Vol> rechercherVol() {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Vol> vols = volDAO.rechercherVol();
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return vols;
}
/**
* Retourne le vol dont l'id est id
* @param id
* @return
*/
public static Vol rechercherVolParId(int id) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Vol vol = volDAO.rechercherVolParId(id);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return vol;
}
/**
* Retourne les vols qui partent à la date passée en paramètre
* @param date
* @return
*/
public static List<Vol> rechercherVolParDate(Date date) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Vol> vols = volDAO.rechercherVolParDate(date);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return vols;
}
/**
* Retourne les vols qui partent de la ville indiquée en paramètre
* @param ville
* @return
*/
public static List<Vol> rechercherVolParVilleDep(String ville) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Vol> vols = volDAO.rechercherVolParVilleDep(ville);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return vols;
}
/**
* Retourne les vols dont le prix est compris entre min et max
* @param min
* @param max
* @return
*/
public static List<Vol> rechercherVolParPrix(int min, int max) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Vol> vols = volDAO.rechercherVolParPrix(min, max);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return vols;
}
//TODO
/**
*
* @param codeVoy
* @return
*/
public static Vol rechercherUnVolParVoyage(String codeVoy) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Vol vol = volDAO.rechercherUnVolParVoyage(codeVoy);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return vol;
}
public static Vol rechercherUnVolParVoyagecsv(String codeVoy) {
Vol vol = volDAO.rechercherUnVolParVoyage(codeVoy);
return vol;
}
/**
* Retourne tous les voyages de la base
* @return
*/
public static List<Voyage> rechercherVoyage() {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Voyage> voyages = voyageDAO.rechercherVoyage();
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return voyages;
}
/**
* Retourne le voyage dont le nom est nom
* @param nom
* @return
*/
public static Voyage rechercherVoyageParNom(String nom) {
//TODO
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Voyage voyage = voyageDAO.rechercherVoyageParNom(nom);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return voyage;
}
/**
* Retourne le voyage dont l'id est id
* @param id
* @return
*/
public static Voyage rechercherVoyageParId(int id) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Voyage voyage = voyageDAO.rechercherVoyageParId(id);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return voyage;
}
/**
* Retourne le voyage dont le code est codeVoy
* @param codeVoy
* @return
*/
public static Voyage rechercherVoyageParCode(String codeVoy) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Voyage voyage = voyageDAO.rechercherVoyageParCode(codeVoy);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return voyage;
}
/**
* Retourne le voyage dont le code est codeVoy en utilisant l'entity manager actuel
* @param codeVoy
* @return
*/
public static Voyage rechercherVoyageParCodecsv(String codeVoy) {
Voyage voyage = voyageDAO.rechercherVoyageParCode(codeVoy);
return voyage;
}
/**
* Retourne les voyages qui commencent à la date passée en paramètre
* @param date
* @return
*/
public static List<Voyage> rechercherVoyageParDate(Date date) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Voyage> voyages = voyageDAO.rechercherVoyageParDate(date);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return voyages;
}
/**
* Retourne les voyages dont la durée est comprise entre min et max
* @param min
* @param max
* @return
*/
public static List<Voyage> rechercherVoyageParDuree(int min, int max) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Voyage> voyages = voyageDAO.rechercherVoyageParDuree(min, max);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return voyages;
}
/**
* Retourne les voyages qui se déroulent dans le pays passé en paramère
* @param pays
* @return
*/
public static List<Voyage> rechercherVoyageParPays(Pays pays) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Voyage> voyages = voyageDAO.rechercherVoyageParPays(pays);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return voyages;
}
/**
* Retourne le devis dont l'id est id
* @param id
* @return
*/
public static Devis rechercherDevisParId(int id) {
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
Devis d = devisDAO.rechercherDevisParId(id);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return d;
}
public static List<Vol> rechercherVolsParVoyage(String codeVoy)
{
JpaUtil.creerEntityManager();
JpaUtil.ouvrirTransaction();
List<Vol> v = volDAO.rechercherVolsParVoyage(codeVoy);
JpaUtil.validerTransaction();
JpaUtil.fermerEntityManager();
return v;
}
}<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package metier.modele;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
/**
*
* @author Antoine
*/
@Entity
public class Pays implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String nom;
private String codePays;
private String region;
private String capitale;
private String langues;
private float superficie;
private float population;
private String regime;
@OneToMany(mappedBy="pays")
private List<Voyage> voyage;
@ManyToMany
private List<Conseiller> conseillers;
public Pays() {
}
public Pays( String nom, String code, String region, String capitale, String langues, float superficie, float population, String regime) {
this.nom = nom;
this.codePays = code;
this.region = region;
this.capitale = capitale;
this.langues = langues;
this.superficie = superficie;
this.population = population;
this.regime = regime;
this.voyage = new ArrayList();
this.conseillers = new ArrayList();
}
public void addVoyage(Voyage v) {
this.voyage.add(v);
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getCodePays() {
return codePays;
}
public void setCodePays(String code) {
this.codePays = code;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCapitale() {
return capitale;
}
public void setCapitale(String capitale) {
this.capitale = capitale;
}
public String getLangues() {
return langues;
}
public void setLangues(String langues) {
this.langues = langues;
}
public float getSuperficie() {
return superficie;
}
public void setSuperficie(float superficie) {
this.superficie = superficie;
}
public float getPopulation() {
return population;
}
public void setPopulation(float population) {
this.population = population;
}
public String getRegime() {
return regime;
}
public void setRegime(String regime) {
this.regime = regime;
}
public int getId() {
return id;
}
public void ajouterConseiller(Conseiller conseiller) {
this.conseillers.add(conseiller);
}
}
<file_sep>package action;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import metier.modele.Pays;
import metier.modele.Voyage;
import metier.service.Service;
/**
*
* @author Administrateur
*/
//@WebServlet(name = "inscription", urlPatterns = {"/inscription"})
public class SelectionActionP extends Action {
/**
*
* @param request
* @throws ServletException
* @throws IOException
*/
@Override
public boolean execute (HttpServletRequest request)
{
String nomPays = request.getParameter("pays");
Pays pays = Service.rechercherPaysParNom(nomPays);
List <Voyage> voyages = Service.rechercherVoyageParPays(pays);
request.setAttribute("voyages", voyages);
request.setAttribute("typeRech", "pays");
return true;
}
}<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package metier.modele;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
/**
*
* @author Amaury
*/
@Entity
public class Devis implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@ManyToOne
private Client client;
@ManyToOne
private Conseiller conseiller;
@ManyToOne
private Voyage voyage;
@ManyToOne
private Vol vol;
private int nbPersonnes;
public Devis() {
}
public Devis(Client client, Conseiller conseiller, Voyage voyage, Vol vol, int nbPersonnes) {
this.client = client;
this.conseiller = conseiller;
this.voyage = voyage;
this.vol = vol;
this.nbPersonnes = nbPersonnes;
}
public int getId() {
return id;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public Conseiller getConseiller() {
return conseiller;
}
public void setConseiller(Conseiller conseiller) {
this.conseiller = conseiller;
}
public Voyage getVoyage() {
return voyage;
}
public void setVoyage(Voyage voyage) {
this.voyage = voyage;
}
public Vol getVol() {
return vol;
}
public void setVol(Vol vol) {
this.vol = vol;
}
public int getNbPersonnes() {
return nbPersonnes;
}
public void setNbPersonnes(int nbPersonnes) {
this.nbPersonnes = nbPersonnes;
}
}
| dc1c3d924cbadd65a16c7b8575acdb90172829dc | [
"Java",
"INI"
]
| 19 | Java | metegan/routard | 6772e857913371a381fb7421ba04243c9eaa7ad2 | c02a494ee00b382fd3a0ce77e42fad991ad0c0c2 |
refs/heads/master | <repo_name>hiddeottens/shopify-scraper<file_sep>/extract.py
path = './stores.csv'
import pandas as pd
from shopify import extract_products_json
result = ''
with open(path) as csvfile:
df = pd.read_csv(csvfile)
url = df['url']
products = extract_products_json(url)
print(products)<file_sep>/README.md
# shopify-scraper
Simple scraper to extract all products from shopify sites
Requirements:
Python 3
Usage:
python3 shopify.py [site's url]
Listing collections:
python3 shopify.py --list-collections [site's url]
Scraping products only in given collections:
python3 shopify.py -c col1,col2,col3 [site's url]
Example:
python3 shopify.py -c vip,babs-and-bab-lows https://www.greats.com
The products get saved into a file named products.csv in the current directory.
| e31f3af10ee8bdb280cd3751dbd65dded03b511d | [
"Markdown",
"Python"
]
| 2 | Python | hiddeottens/shopify-scraper | 479d6ee3687448413ededb5f6205675614961ebc | 01d0dd69ea6c97010b77a88d93d780da6de15e76 |
refs/heads/master | <repo_name>conanforever22/Miscellaneous-Things<file_sep>/README.md
# Some miscellaneous items I cannot give it a certain name.
<file_sep>/override_in_cpp_test.cpp
#include <iostream>
class Base
{
public:
virtual void print_one(void)
{
std::cout << "base" << std::endl;
}
void print_two(void)
{
print_one();
}
};
class Derived : public Base
{
public:
void print_one(void)
{
std::cout << "derived" << std::endl;
}
};
int main(void)
{
Base* foo = NULL;
foo = new Derived();
foo -> print_two();
return 0;
}
<file_sep>/test_const.cpp
#include <iostream>
int main(void)
{
const char* p = "abc";
p = "xyz";
std::cout << *p << std::endl;
return 0;
}
<file_sep>/init_array.cpp
#include <iostream>
int main(void)
{
int arrNum[10] = {0};
std::cout << sizeof(arrNum) << std::endl;
for (int i = 0; i < sizeof(arrNum) / sizeof(int); ++i)
std::cout << arrNum[i] << " ";
std::cout << std::endl;
return 0;
}
<file_sep>/protected_keyword.cpp
#include <iostream>
class Base
{
protected:
int iProtectedVar = 100;
};
class Derived : public Base
{
public:
void print_base_var(void)
{
std::cout << "iProtectedVar = " << iProtectedVar << std::endl;
}
};
int main(void)
{
Derived oTest;
oTest.print_base_var();
return 0;
}
<file_sep>/virtual_in_cpp.cpp
#include <iostream>
class Base
{
public:
Base() {}
virtual void print()
{
std::cout << "Base" << std::endl;
}
};
class Derived : public Base
{
public:
Derived() {}
void print()
{
std::cout << "Derived" << std::endl;
}
};
int main(void)
{
Base* point = new Derived();
point -> print();
return 0;
}
<file_sep>/miss_para.cpp
#include <iostream>
void print(int a = 1, int b = 2, bool c = true);
int main(void)
{
print();
return 0;
}
void print(int a, int b, bool c)
{
std::cout << "foo" << std::endl;
}
<file_sep>/strncpy.cpp
#include <iostream>
#include <cstring>
int main(void)
{
char dest[5];
char src[] = "ab";
char src2[] = "abc";
strncpy(dest, src, sizeof(dest) - 1);
strncpy(dest, src2, sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0';
std::cout << dest[sizeof(dest) - 1] << std::endl;
return 0;
}
<file_sep>/public_test.cpp
#include <iostream>
class Foo
{
public:
static void print(void) { std::cout << "bar" << std::endl;}
};
int main(void)
{
Foo::print();
return 0;
}
<file_sep>/memset.cpp
#include <cstring>
#include <iostream>
int main(void)
{
char str[] = "mashaoliang";
char* dest = str;
std::cout << "before:\t" << dest << std::endl;
memset(dest, 97, 2);
std::cout << "after:\t" << dest << std::endl;
return 0;
}
<file_sep>/strcat.cpp
#include <iostream>
#include <cstring>
int main(void)
{
char str[26];
strcat(str, "abcde");
std::cout << sizeof(str) << std::endl;
std::cout << str[27] << std::endl;
return 0;
}
<file_sep>/zero_in_char.cpp
#include <iostream>
int main(void)
{
char ch = '\0';
int i = 0;
std::cout << "ch = " << ch << std::endl;
std::cout << "i = " << i << std::endl;
return 0;
}
<file_sep>/cpp_primer/chap13/constructor_test0.cpp
#include <iostream>
class Foo
{
public:
Foo(int val):bar(val){} // constructor
Foo(char ch) = delete;
// Foo(const Foo&); // copy constructor
void print_foo();
private:
int bar;
};
void Foo::print_foo()
{
std::cout << this-> bar << std::endl;
}
// Foo::Foo(const Foo& para) : bar(para.bar) {}
int main(void)
{
Foo oTest(1);
Foo oTest2= oTest;
oTest2.print_foo();
return 0;
}
<file_sep>/typeid.cpp
#include <iostream>
#include <typeinfo>
class Foo
{
public:
int ibar;
};
int main(void)
{
Foo foo();
std::cout << "typeid(int)" << typeid(int).name() << std::endl;
return 0;
}
<file_sep>/pointer_of_a_class.cpp
#include <iostream>
#include <string>
class Test
{
public:
Test(std::string str = "Hello World") { std::cout << str << std::endl; }
};
int main(void)
{
Test* test = NULL;
test = new Test;
return 0;
}
<file_sep>/strcmp.cpp
#include <cstring>
#include <iostream>
int main(void)
{
char* str1 = "bbc";
char* str2 = "abc";
std::cout << "strcmp(str1, str2):" << strcmp(str1, str2) << std::endl;
return 0;
}
<file_sep>/override-test-in-base-function.cpp
#include <iostream>
class Base
{
public:
void Initialize(void) { print();}
virtual void print(void) { std::cout << "print in Base" << std::endl;}
};
class Derived : public Base
{
protected:
void print(void) { std::cout << "print in Derived" << std::endl;}
};
int main(void)
{
Base* pTest = NULL;
pTest = new Derived();
pTest -> Initialize();
return 0;
}
| fa01ce27f4a2ce874d37a307d839b5fd48552dda | [
"Markdown",
"C++"
]
| 17 | Markdown | conanforever22/Miscellaneous-Things | a87a2546753b7dbc59326f4c897518d5bd080ec6 | 8cad0a14a0b3ef3ae91a06248312b71d919b439a |
refs/heads/master | <repo_name>swastikpattnaik/WebToursFlightCancellationDynamicBody<file_sep>/Cancel_Flight.c
Cancel_Flight()
{
// <input type="hidden" name="flightID" value="123311596-87802-SP" />
web_reg_save_param_ex(
"ParamName=cFlightID",
"LB=<input type=\"hidden\" name=\"flightID\" value=\"",
"RB=\"",
"Ordinal=ALL",
SEARCH_FILTERS,
LAST);
// <input type="hidden" name=".cgifields" value="1" />
web_reg_save_param_ex(
"ParamName=cCGIFields",
"LB=<input type=\"hidden\" name=\".cgifields\" value=\"",
"RB=\"",
"Ordinal=ALL",
SEARCH_FILTERS,
LAST);
lr_start_transaction("SC03_CancelFlight_T03_Click_Itinerary");
web_reg_find("Text=Flight Transaction Summary",
"SaveCount=TxnSummary_Count",
LAST);
web_url("Itinerary Button",
"URL=http://{pServerName}:{pPortNo}/cgi-bin/welcome.pl?page=itinerary",
"TargetFrame=body",
"Resource=0",
"RecContentType=text/html",
"Referer=http://{pServerName}:{pPortNo}/cgi-bin/nav.pl?page=menu&in=home",
"Snapshot=t3.inf",
"Mode=HTML",
LAST);
if(atoi(lr_eval_string("{TxnSummary_Count}")) > 0)
{
lr_end_transaction("SC03_CancelFlight_T03_Click_Itinerary", LR_PASS);
}
else
{
lr_end_transaction("SC03_CancelFlight_T03_Click_Itinerary", LR_FAIL);
lr_output_message("VUser ID %d encountered an error in Iteration No. %d.", atoi(lr_eval_string("{pVUserID}")), atoi(lr_eval_string("{pIterationNumber}")));
}
lr_think_time(10);
paramArray_count = atoi(lr_eval_string("{cFlightID_count}"));
//For picking up a random booking to cancel
sprintf(buffRow, "%d", rand() % paramArray_count + 1);
// lr_output_message("%s", buffRow);
lr_param_sprintf("pReqBody", "%s=on", buffRow);
for(i=1; i<=paramArray_count; i++)
{
sprintf(pFlightID, "{cFlightID_%d}", i);
lr_param_sprintf("flightIDval", "%s", lr_eval_string(pFlightID));
lr_param_sprintf("pReqBody", "%s&flightID=%s", lr_eval_string("{pReqBody}"), lr_eval_string("{flightIDval}"));
sprintf(pCGIField, "{cCGIFields_%d}", i);
lr_param_sprintf("cgiFieldval", "%s", lr_eval_string(pCGIField));
lr_param_sprintf("pReqBody", "%s&.cgifields=%s", lr_eval_string("{pReqBody}"), lr_eval_string("{cgiFieldval}"));
}
lr_param_sprintf("pReqBody", "%s&removeFlights.x=37&removeFlights.y=7", lr_eval_string("{pReqBody}"));
// lr_output_message(lr_eval_string("{pReqBody}"));
lr_start_transaction("SC03_CancelFlight_T04_Click_CancelChecked");
web_reg_find("Text=Flights List",
"SaveCount=FlightsList_Count",
LAST);
/*
web_submit_data("itinerary.pl",
"Action=http://{pServerName}:{pPortNo}/cgi-bin/itinerary.pl",
"Method=POST",
"TargetFrame=",
"RecContentType=text/html",
"Referer=http://{pServerName}:{pPortNo}/cgi-bin/itinerary.pl",
"Snapshot=t4.inf",
"Mode=HTML",
ITEMDATA,
"Name=1", "Value={c1}", ENDITEM,
"Name=flightID", "Value={cFlightID}", ENDITEM,
"Name=removeFlights.x", "Value=48", ENDITEM,
"Name=removeFlights.y", "Value=7", ENDITEM,
"Name=.cgifields", "Value={cCGIFields}", ENDITEM,
LAST);
*/
web_custom_request("itinerary.pl",
"URL=http://{pServerName}:{pPortNo}/cgi-bin/itinerary.pl",
"Method=POST",
"Resource=0",
"RecContentType=text/html",
"Referer=http://{pServerName}:{pPortNo}/cgi-bin/itinerary.pl",
"Snapshot=t4.inf",
"Mode=HTTP",
"Body={pReqBody}",
LAST);
if(atoi(lr_eval_string("{FlightsList_Count}")) > 0)
{
lr_end_transaction("SC03_CancelFlight_T04_Click_CancelChecked", LR_PASS);
}
else
{
lr_end_transaction("SC03_CancelFlight_T04_Click_CancelChecked", LR_FAIL);
lr_output_message("VUser ID %d encountered an error in Iteration No. %d.", atoi(lr_eval_string("{pVUserID}")), atoi(lr_eval_string("{pIterationNumber}")));
}
lr_think_time(10);
i = 1;
lr_param_sprintf("pReqBody", "");
return 0;
} | 337b00406060414a4df111d1a27e49566ed1c920 | [
"C"
]
| 1 | C | swastikpattnaik/WebToursFlightCancellationDynamicBody | 6b6e2a1bbfc49afe11ef83f84c98122adaed1ba1 | 30f06e4b634c4cf736bc116ac170df8a758f7ca0 |
refs/heads/master | <repo_name>cloneko/awsmaujan<file_sep>/README.md
# AWS麻雀牌イメージ for まうじゃん by @cloneko

## これは何?
[AWS麻雀牌の作り方 - カタヤマンがプログラマチックに今日もコードアシスト](http://c9katayama.hatenablog.com/entry/2014/12/15/002712)で配布されているAWS麻雀牌のイメージをまうじゃん用に変換したものです。
## 使い方
適当なツールで展開してください。
### グラフィックの変更のしかた
ゲーム開始時に設定するところで、「グラフィック」タブから定義ファイルを指定してください。
もしくはオプション → グラフィック定義 から変更することができます。
## 変換用スクリプト
雑に作ってあるコードなのでアレですが、一応一緒に置いておきます。
要ImageMagick(convert/mogrify)
### 使い方
1. [AWS麻雀アイコンセット](http://aws-cloud.s3.amazonaws.com/mahjong/icon.zip)をダウンロードし、展開します。
2. 展開したディレクトリにawsmaujan.shを移動します。
3. 展開したディレクトリで./awsmaujan.shを実行
4. /tmpにaws_bx.bmp aws_by.bmp aws_sx.bmp aws_sy.bmpが生成されるので、同梱の「aws.gsf」と同じディレクトリに置いてください。
### 動作検証環境
* まうじゃん 1.023 + Wine 1.6.2 on Linux mint 17
### ライセンス?
* awsmaujan.shはパブリックドメインとします。
<file_sep>/awsmaujan.sh
#!/bin/sh
# Resize
WD=$PWD
# 大きいサイズ用
SIZE=25x35
convert -resize $SIZE Back.png /tmp/Back.bmp
convert -resize $SIZE C1.png /tmp/C1.bmp
convert -resize $SIZE C2.png /tmp/C2.bmp
convert -resize $SIZE C3.png /tmp/C3.bmp
convert -resize $SIZE C4.png /tmp/C4.bmp
convert -resize $SIZE C5.png /tmp/C5.bmp
convert -resize $SIZE C6.png /tmp/C6.bmp
convert -resize $SIZE C7.png /tmp/C7.bmp
convert -resize $SIZE C8.png /tmp/C8.bmp
convert -resize $SIZE C9.png /tmp/C9.bmp
convert -resize $SIZE D1.png /tmp/D1.bmp
convert -resize $SIZE D2.png /tmp/D2.bmp
convert -resize $SIZE D3.png /tmp/D3.bmp
convert -resize $SIZE D4.png /tmp/D4.bmp
convert -resize $SIZE D5.png /tmp/D5.bmp
convert -resize $SIZE D6.png /tmp/D6.bmp
convert -resize $SIZE D7.png /tmp/D7.bmp
convert -resize $SIZE D8.png /tmp/D8.bmp
convert -resize $SIZE D9.png /tmp/D9.bmp
convert -resize $SIZE H1.png /tmp/H1.bmp
convert -resize $SIZE H2.png /tmp/H2.bmp
convert -resize $SIZE H3.png /tmp/H3.bmp
convert -resize $SIZE H4.png /tmp/H4.bmp
convert -resize $SIZE N1.png /tmp/N1.bmp
convert -resize $SIZE N2.png /tmp/N2.bmp
convert -resize $SIZE N3.png /tmp/N3.bmp
convert -resize $SIZE N4.png /tmp/N4.bmp
convert -resize $SIZE N5.png /tmp/N5.bmp
convert -resize $SIZE N6.png /tmp/N6.bmp
convert -resize $SIZE N7.png /tmp/N7.bmp
convert -resize $SIZE N8.png /tmp/N8.bmp
convert -resize $SIZE N9.png /tmp/N9.bmp
convert -resize $SIZE R1.png /tmp/R1.bmp
convert -resize $SIZE R2.png /tmp/R2.bmp
convert -resize $SIZE R3.png /tmp/R3.bmp
convert -resize $SIZE R4.png /tmp/R4.bmp
convert -resize $SIZE S1.png /tmp/S1.bmp
convert -resize $SIZE S2.png /tmp/S2.bmp
convert -resize $SIZE S3.png /tmp/S3.bmp
convert -resize $SIZE S4.png /tmp/S4.bmp
convert -resize $SIZE W1.png /tmp/W1.bmp
convert -resize $SIZE W2.png /tmp/W2.bmp
convert -resize $SIZE W3.png /tmp/W3.bmp
convert -resize $SIZE W4.png /tmp/W4.bmp
convert -colorize 0/30/30 /tmp/C5.bmp /tmp/C5-Red.bmp
convert -colorize 0/30/30 /tmp/D5.bmp /tmp/D5-Red.bmp
convert -colorize 0/30/30 /tmp/N5.bmp /tmp/N5-Red.bmp
# 正面向き
cd /tmp
convert -append C[1-9].bmp D[1-9].bmp N[1-9].bmp R1.bmp R4.bmp R2.bmp R3.bmp W1.bmp H1.bmp S1.bmp C5-Red.bmp D5-Red.bmp N5-Red.bmp front.bmp
# 対面
mogrify -rotate 180 [A-Z]*.bmp
convert -append C[1-9].bmp D[1-9].bmp N[1-9].bmp R1.bmp R4.bmp R2.bmp R3.bmp W1.bmp H1.bmp S1.bmp C5-Red.bmp D5-Red.bmp N5-Red.bmp toimen.bmp
# Merge
convert +append front.bmp toimen.bmp aws_by.bmp
# 横向きの奴
mogrify -rotate 90 [A-Z]*.bmp
convert +append C[1-9].bmp D[1-9].bmp N[1-9].bmp R1.bmp R4.bmp R2.bmp R3.bmp W1.bmp H1.bmp S1.bmp C5-Red.bmp D5-Red.bmp N5-Red.bmp right.bmp
mogrify -rotate 180 [A-Z]*.bmp
convert +append C[1-9].bmp D[1-9].bmp N[1-9].bmp R1.bmp R4.bmp R2.bmp R3.bmp W1.bmp H1.bmp S1.bmp C5-Red.bmp D5-Red.bmp N5-Red.bmp left.bmp
convert -append right.bmp left.bmp aws_bx.bmp
rm -fr /tmp/[A-Z]*.bmp /tmp/right.bmp /tmp/left.bmp /tmp/toimen.bmp /tmp/front.bmp
cd $WD
# 小さいサイズ用
SIZE=20x28
convert -resize $SIZE Back.png /tmp/Back.bmp
convert -resize $SIZE C1.png /tmp/C1.bmp
convert -resize $SIZE C2.png /tmp/C2.bmp
convert -resize $SIZE C3.png /tmp/C3.bmp
convert -resize $SIZE C4.png /tmp/C4.bmp
convert -resize $SIZE C5.png /tmp/C5.bmp
convert -resize $SIZE C6.png /tmp/C6.bmp
convert -resize $SIZE C7.png /tmp/C7.bmp
convert -resize $SIZE C8.png /tmp/C8.bmp
convert -resize $SIZE C9.png /tmp/C9.bmp
convert -resize $SIZE D1.png /tmp/D1.bmp
convert -resize $SIZE D2.png /tmp/D2.bmp
convert -resize $SIZE D3.png /tmp/D3.bmp
convert -resize $SIZE D4.png /tmp/D4.bmp
convert -resize $SIZE D5.png /tmp/D5.bmp
convert -resize $SIZE D6.png /tmp/D6.bmp
convert -resize $SIZE D7.png /tmp/D7.bmp
convert -resize $SIZE D8.png /tmp/D8.bmp
convert -resize $SIZE D9.png /tmp/D9.bmp
convert -resize $SIZE H1.png /tmp/H1.bmp
convert -resize $SIZE H2.png /tmp/H2.bmp
convert -resize $SIZE H3.png /tmp/H3.bmp
convert -resize $SIZE H4.png /tmp/H4.bmp
convert -resize $SIZE N1.png /tmp/N1.bmp
convert -resize $SIZE N2.png /tmp/N2.bmp
convert -resize $SIZE N3.png /tmp/N3.bmp
convert -resize $SIZE N4.png /tmp/N4.bmp
convert -resize $SIZE N5.png /tmp/N5.bmp
convert -resize $SIZE N6.png /tmp/N6.bmp
convert -resize $SIZE N7.png /tmp/N7.bmp
convert -resize $SIZE N8.png /tmp/N8.bmp
convert -resize $SIZE N9.png /tmp/N9.bmp
convert -resize $SIZE R1.png /tmp/R1.bmp
convert -resize $SIZE R2.png /tmp/R2.bmp
convert -resize $SIZE R3.png /tmp/R3.bmp
convert -resize $SIZE R4.png /tmp/R4.bmp
convert -resize $SIZE S1.png /tmp/S1.bmp
convert -resize $SIZE S2.png /tmp/S2.bmp
convert -resize $SIZE S3.png /tmp/S3.bmp
convert -resize $SIZE S4.png /tmp/S4.bmp
convert -resize $SIZE W1.png /tmp/W1.bmp
convert -resize $SIZE W2.png /tmp/W2.bmp
convert -resize $SIZE W3.png /tmp/W3.bmp
convert -resize $SIZE W4.png /tmp/W4.bmp
convert -colorize 0/30/30 /tmp/C5.bmp /tmp/C5-Red.bmp
convert -colorize 0/30/30 /tmp/D5.bmp /tmp/D5-Red.bmp
convert -colorize 0/30/30 /tmp/N5.bmp /tmp/N5-Red.bmp
# 正面向き
cd /tmp
convert -append C[1-9].bmp D[1-9].bmp N[1-9].bmp R1.bmp R4.bmp R2.bmp R3.bmp W1.bmp H1.bmp S1.bmp C5-Red.bmp D5-Red.bmp N5-Red.bmp front.bmp
# 対面
mogrify -rotate 180 [A-Z]*.bmp
convert -append C[1-9].bmp D[1-9].bmp N[1-9].bmp R1.bmp R4.bmp R2.bmp R3.bmp W1.bmp H1.bmp S1.bmp C5-Red.bmp D5-Red.bmp N5-Red.bmp toimen.bmp
# Merge
convert +append front.bmp toimen.bmp aws_sy.bmp
# 横向きの奴
mogrify -rotate 90 [A-Z]*.bmp
convert +append C[1-9].bmp D[1-9].bmp N[1-9].bmp R1.bmp R4.bmp R2.bmp R3.bmp W1.bmp H1.bmp S1.bmp C5-Red.bmp D5-Red.bmp N5-Red.bmp right.bmp
mogrify -rotate 180 [A-Z]*.bmp
convert +append C[1-9].bmp D[1-9].bmp N[1-9].bmp R1.bmp R4.bmp R2.bmp R3.bmp W1.bmp H1.bmp S1.bmp C5-Red.bmp D5-Red.bmp N5-Red.bmp left.bmp
convert -append right.bmp left.bmp aws_sx.bmp
rm -fr /tmp/[A-Z]*.bmp /tmp/right.bmp /tmp/left.bmp /tmp/toimen.bmp /tmp/front.bmp
| cbb9a1ca13acb96cb8c81790500a8d5f5a0ae8a2 | [
"Markdown",
"Shell"
]
| 2 | Markdown | cloneko/awsmaujan | 9a4d551560827538212744fbc346fba8c873dd98 | aed5c3ebe384018968d7908566344a34a8c2e73a |
refs/heads/master | <file_sep>package com.recipe.demo.model;
public class Diffuculty {
enum level{
EASY, MODERATE, HARD
}
}
| fa56dbe7555fa2b83e5b7491de6fc778cb9609eb | [
"Java"
]
| 1 | Java | OzlemDoganGit/recipe | 94623fe384cb4b051741b47e9730fcc87fd9ebd2 | 33dc976a3637e8503662ccf664a20d82b969b26a |
refs/heads/master | <file_sep># import the necessary packages
import numpy as np
import cv2
# define file path
yolo_path = "yolo-coco/"
image_path = "images/"
# load the COCO class labels
labels_path = yolo_path + "coco.names"
labels = open(labels_path).read().strip().split("\n")
weights_path = yolo_path + "yolov3.weights"
config_path = yolo_path + "yolov3.cfg"
net = cv2.dnn.readNetFromDarknet(config_path, weights_path)
ln = net.getLayerNames()
ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
vs = cv2.VideoCapture("videos/object_detection_test.mp4")
H, W = (None, None)
fps = 30
vout = None
while(True):
(grabbed, frame) = vs.read()
if not grabbed:
break
if W is None or H is None:
H,W = frame.shape[:2]
blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
layerOutputs = net.forward(ln)
boxes = []
confidences = []
classIDs = []
for output in layerOutputs:
for detection in output:
scores = detection[5:]
classID = np.argmax(scores)
confidence = scores[classID]
if confidence > 0.50:
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
x = centerX - (width/2)
y = centerY - (height/2)
boxes.append([int(x), int(y), int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.50, 0.30)
if len(idxs) > 0:
for i in idxs.flatten():
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
cv2.rectangle(frame, (x, y), (x + w, y + h), (0,255,255), 2)
text = "{}: {:.2f}".format(labels[classIDs[i]], confidences[i])
cv2.putText(frame, text, (x, y - 7), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (0,255,255), 2)
if vout is None:
sz = (frame.shape[1], frame.shape[0])
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
vout = cv2.VideoWriter()
vout.open('output.avi',fourcc,fps,sz,True)
vout.write(frame)
# cv2.imshow('Output',frame)
# if cv2.waitKey(fps) & 0xFF == ord('q'):
# break
vs.release()
cv2.destroyAllWindows()<file_sep># import the necessary packages
import numpy as np
import cv2
# define file path
yolo_path = "yolo-coco/"
image_path = "images/"
# load the COCO class labels
labels_path = yolo_path + "coco.names"
labels = open(labels_path).read().strip().split("\n")
weights_path = yolo_path + "yolov3.weights"
config_path = yolo_path + "yolov3.cfg"
net = cv2.dnn.readNetFromDarknet(config_path, weights_path)
ln = net.getLayerNames()
ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
image = cv2.imread("images/football.jpg")
(H, W) = image.shape[:2]
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
layerOutputs = net.forward(ln)
boxes = []
confidences = []
classIDs = []
for output in layerOutputs:
for detection in output:
scores = detection[5:]
classID = np.argmax(scores)
confidence = scores[classID]
if confidence > 0.50:
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.3)
if len(idxs) > 0:
for i in idxs.flatten():
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
cv2.rectangle(image, (x, y), (x + w, y + h), (0,255,255), 2)
text = "{}: {:.2f}".format(labels[classIDs[i]], confidences[i])
cv2.putText(image, text, (x, y - 7), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (0,255,255), 2)
cv2.imshow("Output", image)
<file_sep># Object-Detection-with-YOLO
Object detection with YOLO
| f28cbdcb2995c4298476e5dcf92a1391872c81a2 | [
"Markdown",
"Python"
]
| 3 | Python | Furkan-Gulsen/Object-Detection-with-YOLO | cd0339f95809b8bca320d59381d870cef8d0fcbb | 05fa82c5921a8096966db2090fd00ca3b0f301e7 |
refs/heads/master | <file_sep>package com.abhilasha.jdbc.model;
public class Child {
private int id;
private String name;
private String admissionNumber;
private String dob;
private int age;
private int sex ;
private String std;
private String fatherName;
private String fatherEducation;
private String fatherEmployment;
private String motherName;
private String motherEducation;
private String motherEmployment;
private String familyHistory;
private String address;
private int familyIncome;
private String category;//orphan/semi-orphan/poor family
private int hivInfection;
private int parentsHadhiv;
private String conduct;
private String academicPerformance;
private String dream;
private String schoolImpact;
public Child(String name,
String admissionNumber,
String dob,
int age,
int sex ,
String std,
String fatherName,
String fatherEducation,
String fatherEmployment,
String motherName,
String motherEducation,
String motherEmployment,
String familyHistory,
String addess,
int familyIncome,
String category,
int hivInfection,
int parentsHadhiv,
String conduct,
String academicPerformance,
String dream,
String schoolImpact) {
this.name = name;
this.admissionNumber = admissionNumber;
this.dob = dob;
this.age = age;
this.sex = sex ;
this.std = std;
this.fatherName = fatherName;
this.fatherEducation = fatherEducation;
this.fatherEmployment = fatherEmployment;
this.motherName = motherName;
this.motherEducation = motherEducation;
this.motherEmployment = motherEmployment;
this.familyHistory = familyHistory;
this.address = addess;
this.familyIncome = familyIncome;
this.category = category;
this.hivInfection = hivInfection;
this.parentsHadhiv = parentsHadhiv;
this.conduct = conduct;
this.academicPerformance = academicPerformance;
this.dream = dream;
this.schoolImpact = schoolImpact;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdmissionNumber() {
return admissionNumber;
}
public void setAdmissionNumber(String admissionNumber) {
this.admissionNumber = admissionNumber;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getStd() {
return std;
}
public void setStd(String std) {
this.std = std;
}
public String getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
public String getFatherEducation() {
return fatherEducation;
}
public void setFatherEducation(String fatherEducation) {
this.fatherEducation = fatherEducation;
}
public String getFatherEmployment() {
return fatherEmployment;
}
public void setFatherEmployment(String fatherEmployment) {
this.fatherEmployment = fatherEmployment;
}
public String getMotherName() {
return motherName;
}
public void setMotherName(String motherName) {
this.motherName = motherName;
}
public String getMotherEducation() {
return motherEducation;
}
public void setMotherEducation(String motherEducation) {
this.motherEducation = motherEducation;
}
public String getMotherEmployment() {
return motherEmployment;
}
public void setMotherEmployment(String motherEmployment) {
this.motherEmployment = motherEmployment;
}
public String getFamilyHistory() {
return familyHistory;
}
public void setFamilyHistory(String familyHistory) {
this.familyHistory = familyHistory;
}
public String getAddress() {
return address;
}
public void setAddress(String addess) {
this.address = addess;
}
public int getFamilyIncome() {
return familyIncome;
}
public void setFamilyIncome(int familyIncome) {
this.familyIncome = familyIncome;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getHivInfection() {
return hivInfection;
}
public void setHivInfection(int hivInfection) {
this.hivInfection = hivInfection;
}
public int getParentsHadhiv() {
return parentsHadhiv;
}
public void setParentsHadhiv(int parentsHadhiv) {
this.parentsHadhiv = parentsHadhiv;
}
public String getConduct() {
return conduct;
}
public void setConduct(String conduct) {
this.conduct = conduct;
}
public String getAcademicPerformance() {
return academicPerformance;
}
public void setAcademicPerformance(String academicPerformance) {
this.academicPerformance = academicPerformance;
}
public String getDream() {
return dream;
}
public void setDream(String dream) {
this.dream = dream;
}
public String getSchoolImpact() {
return schoolImpact;
}
public void setSchoolImpact(String schoolImpact) {
this.schoolImpact = schoolImpact;
}
}
<file_sep>package com.abhilasha.jdbc.dao;
import com.abhilasha.jdbc.model.ChildNeed;
public interface ChildNeedDAO {
public ChildNeed findNeedByChildId(int childId);
public ChildNeed save(ChildNeed childNeed);
}
<file_sep>package com.abhilasha.jdbc.model;
import java.util.ArrayList;
public class ChildNeed {
private int id;
private int childid;
private ArrayList<Integer> needid;
public ChildNeed (int childid) {
this.childid = childid;
}
public ChildNeed(int childId, ArrayList<Integer> needid) {
this.childid = childId;
this.needid = needid;
}
public int getChildid() {
return childid;
}
public void setChildid(int childid) {
this.childid = childid;
}
public ArrayList<Integer> getNeedid() {
return needid;
}
public void setNeedid(ArrayList<Integer> needid) {
this.needid = needid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
<file_sep>package com.abhilasha.bo;
public class DonorBO {
}
<file_sep>package com.abhilasha.jdbc.dao;
import java.util.ArrayList;
import com.abhilasha.jdbc.model.Donor;
public interface DonorDAO {
public Donor findDonarByName(String name);
public Donor findDonarById(int id);
public Donor save(Donor donor);
public ArrayList<Donor> getAllDonors();
}
<file_sep>package com.abhilasha.jdbc.dao;
import com.abhilasha.jdbc.model.Wish;
public interface WishDAO {
public Wish save(Wish wish);
public Wish findWishByChildId(int childId);
}
<file_sep>package com.abhilasha.pojo;
public class ChildNeedPojo {
private int childId;
private int needId;
private int totalAmount;
private int requiredAmount;
private int amountDonated;
public ChildNeedPojo(int childId, int needId, int total, int donated, int required) {
this.childId = childId;
this.needId = needId;
this.totalAmount = total;
this.amountDonated = donated;
this.requiredAmount = required;
}
public int getChildId() {
return childId;
}
public void setChildId(int childId) {
this.childId = childId;
}
public int getNeedId() {
return needId;
}
public void setNeedId(int needId) {
this.needId = needId;
}
public int getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(int totalAmount) {
this.totalAmount = totalAmount;
}
public int getRequiredAmount() {
return requiredAmount;
}
public void setRequiredAmount(int requiredAmount) {
this.requiredAmount = requiredAmount;
}
public int getAmountDonated() {
return amountDonated;
}
public void setAmountDonated(int amountDonated) {
this.amountDonated = amountDonated;
}
public String getNeedType() {
if (needId == 1) return "Food";
if (needId == 2) return "Education";
if (needId == 3) return "Medical";
if (needId == 4) return "Clothing";
return "";
}
}
<file_sep>package com.abhilasha.jdbc.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;
import com.abhilasha.jdbc.dao.DonationDAO;
import com.abhilasha.jdbc.model.Donation;
@Component
public class DonationDAOImpl implements DonationDAO{
@Autowired
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public JdbcTemplate getJdbcTemplate() {
return new JdbcTemplate(dataSource);
}
@Override
public Donation save(final Donation donation) {
final String query = "INSERT INTO donor_child_need(donorid, childid, needid, date, amountdonated) values(?, ?, ?, ?, ?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
getJdbcTemplate().update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, donation.getDonorid());
ps.setInt(2, donation.getChildid());
ps.setInt(3, donation.getNeedid());
ps.setString(4, donation.getDate());
ps.setInt(5, donation.getAmountdonated());
return ps;
}
}, keyHolder);
donation.setId(keyHolder.getKey().intValue());
return donation;
}
}
<file_sep>package com.abhilasha.jdbc.model;
public class Donation {
private int id;
private int donorid;
private int childid;
private int needid;
private String date;
private int amountdonated;
public Donation(int donorid, int childid, int needid, String date, int amountdonated) {
this.donorid = donorid;
this.childid = childid;
this.needid = needid;
this.date = date;
this.amountdonated = amountdonated;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getDonorid() {
return donorid;
}
public void setDonorid(int donorid) {
this.donorid = donorid;
}
public int getChildid() {
return childid;
}
public void setChildid(int childid) {
this.childid = childid;
}
public int getNeedid() {
return needid;
}
public void setNeedid(int needid) {
this.needid = needid;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getAmountdonated() {
return amountdonated;
}
public void setAmountdonated(int amountdonated) {
this.amountdonated = amountdonated;
}
}
| 471a41334c12d29e1ca864b0efb37fd5201d27d4 | [
"Java"
]
| 9 | Java | chandragauravsharma/Hope_Foundation | 0cc787efa72dd77ca251c66d180715c2a7ca2227 | 4f5862182224627d07ca06bc27adb78031e83d03 |
refs/heads/master | <repo_name>Bradysm/daily_coding_problems<file_sep>/cakeTheif.py
# You are a renowned thief who has recently switched from stealing precious metals to
# stealing cakes because of the insane profit margins. You end up hitting the jackpot,
# breaking into the world's largest privately owned stock of cakes—the vault of the Queen of England.
#
# While Queen Elizabeth has a limited number of types of cake, she has an unlimited supply of each type.
#
# Each type of cake has a weight and a value, stored in a tuple with two indices:
#
# An integer representing the weight of the cake in kilograms
# An integer representing the monetary value of the cake in British shillings
# For example:
#
# # Weighs 7 kilograms and has a value of 160 shillings
# (7, 160)
#
# # Weighs 3 kilograms and has a value of 90 shillings
# (3, 90)
#
# You brought a duffel bag that can hold limited weight, and you want to make off with the most valuable haul possible.
#
# Write a function max_duffel_bag_value() that takes a list of cake type tuples and a weight capacity,
# and returns the maximum monetary value the duffel bag can hold.
# when I first looked at this problem, I was immediately curious with the numbers that were provided.
# why is the weight important? How do I choose a cake based on the weight and price?
# immediately I started thinking about ratios. To get the most out of the cake, we want to take the
# greatest ratio of price/cake. If we take the greatest price first and fill our bag with
# as much of this as possible, we can then move down the line to the next most expensive
# cake and start filling our bag with the next cake. Another way that this can be done
# is to create an array of size capacity O(cap), and have each index represent the max value
# of cakes that can be taken for that capacity. Although I do not solve it this way, I encourage
# you to try the DP solution out for yourselves
# to solve this problem, I sort the list in descending order based on the price/weight ratio
# to avoid divide by zero errors, I use a lambda that checks to see if the weight is zero
# and uses maxsize as the comparator instead, because these cakes will have infinite worth
# Note that the sort is in descending order, because we want to iterate through the
# greatest price/weight ratio cakes first. Next, I iterate through each cake in the list.
# I then try to add the cake to the bag if there is enough room. If there is enough room
# I add the cake price to my current running price and then to my current sack weight as well
# What happens if I can add this cake again? To take care of this, a while loop is used
# to ensure that we can put more than one of the same cake in the bag if possible.
# Lastly, the price is returned to the user. This will run in O(nlogn) time where n
# represents the number of cakes in the bakery (this time comes from sorting which is more expensive than the
# last iteration through the list)
import sys
def max_duffel_bag_value(cakes, capacity):
"""
Takes a list of cakes and a capacity and then
returns the maximum value that can be stolen
:param cakes: list of (weight, price) tuples
:param capacity: max capacity for duffel bag
:return: integer representing the max price
"""
curr_w = 0 # current weight of the bag
price = 0
cakes.sort(reverse=True, key=lambda c: c[1]/c[0] if c[0] else sys.maxsize)
for cake in cakes:
if cake[0] == 0: return sys.maxsize # infinite number of cakes can be taken
while (curr_w + cake[0]) <= capacity:
curr_w += cake[0]
price += cake[1]
return price
# possible cake lists
laCakes = [(7, 160), (3, 90), (2, 15)]
zeroWeight = [(0, 5), (8, 100), (1, 20)]
print(max_duffel_bag_value(laCakes, 20)) # example problem
print(max_duffel_bag_value(zeroWeight, 1)) # showing zero weight cakes have inf wealth
<file_sep>/wordsInOrder.py
#Hi, here's your problem today. This problem was recently asked by Apple:
#Given a list of words, and an arbitrary alphabetical order, verify that the words are in order of the alphabetical order.
#Example:
#Input:
#words = ["abcd", "efgh"], order="<KEY>"
#Output: False
#Explanation: 'e' comes before 'a' so 'efgh' should come before 'abcd'
#Example 2:
#Input:
#words = ["zyx", "zyxw", "zyxwy"],
#rder="<KEY>"
#Output: True
#Explanation: The words are in increasing alphabetical order
# sorry that I'm getting lazy with the explinations. I just signed with Capital One and haven't had
# the motivation to write as much in the comments. Im going to slowly come back to doing interview problems
# I was taking a break because it's so stressful and I just wanted some time to clear my head
# O(n*s) time and O(1) space (this is assuming the character set is constant so the dictionary will always be constant space)
def words_in_order(words: list , order: str) -> list:
letter_order = {order[i]: i for i in range(len(order))} # create the mapping of the letters to the order they're in
for word_i in range(1, len(words)):
word1 = words[word_i-1] # word before
word2 = words[word_i] # word after
word1_i = word2_i = 0
while word1_i < len(word1) and word2_i < len(word2):
c1_order = letter_order[word1[word1_i]]
c2_order = letter_order[word2[word2_i]]
# check if the letter in the second word comes before the first word letter
if c2_order < c1_order: return False
# move to the next letter
word1_i += 1
word2_i += 1
return True
print(words_in_order(["abcd", "efgh"], "<KEY>"))
print(words_in_order(["zyx", "zyxw", "zyxwy"], "<KEY>"))
<file_sep>/longestIncSubSeq.py
# given a list of numbers, return the length of the longest increasing subsequence
# the way that I like to think about these problems is to think of bellman equations
# With these equations, you choose your current step based on fact that all previous
# steps were optimal, thus choosing the optimal step at the current step will ensure
# that your current path is acting optimally. You see this alot in Value iteration
# for AI (fun reading and I highly recommend you look into those topics)
# anyways, to start of this problem, I will be using just a simple
# bellman like equation that has you act opitmally based on the previous
# calculated values. So we will keep stepping down the array recurisvely,
# and then build the values back from teh bottom up. This is more a naive
# solution and it will have a runtime of around O(2^n). The reason why
# it is roughly O(2^n) is because not every index in the array will
# have a branching of 2. If the current index is not greater than
# the previous value, then there is only one branch that is taken.
# there is also a O(n^2) solution that can be created using a bottom
# up appraoch. I will detail this at the bottom of the script
# for this solution, the best way to think about it is that you either
# choose to include the value if it's greater than the prev, and then
# you also choose to not inlcude it to see if that could produce a more
# optimal solution. If that doesnt make sense to you, think of [1, 100, 5, 6, 7]
# If you always choose to only add the value if it's increasing and never choose
# to not add it, you will get 2 instead of 4 for this test case. So it's important
# to almost think of it like a powerset and to choose to include it or not.
# notice for this solution we do not carry the whole sequence. For the next
# solution I will show why carrying the whole sequence might be a good idea for
# certain problems. For this problem, adding the ith number only relies on
# the i-1 value, thus we just need to maintain the i-1 value and not
# the whole sequence.
import sys
def longest_inc_sub(nums):
if nums is None: return 0 # check for when the list is empty or null
return lic_help(nums, -sys.maxsize, 0)
def lic_help(nums, prev, i):
"""
nums: list of numbers
prev: previous number added to the subsequence
i: current index within the list
"""
# check to see if we're at the end of the array
if i == len(nums): return 0
# take the longest of including the value and not including the value
longest = -sys.maxsize if nums[i] <= prev else 1 + lic_help(nums, nums[i], i+1)
return max(longest, lic_help(nums, prev, i+1))
# test to make sure it works
print('first test:')
t = [10, 22, 9, 33, 21, 50, 41, 60, 80]
print(longest_inc_sub(t))
t = [1, 5, 2, 80, 6, 90, 10, 11]
print(longest_inc_sub(t))
t = [1, 100, 5, 6, 7]
print(longest_inc_sub(t))
# here is another interesting implementation
# for this problem, there is only n recursive calls
# but for each recursive call, there is a deep copy
# of all of the lists that were created up to that point
# in the worst case there are 2^n lists, and for each list
# of size k, there will be an O(k) deep copy thus making
# the time complexity O(n + 2^n*k). Although the time does
# not sound great at all, this would be a better algorithm
# for a problem that asked you to print out all the increasing
# subsequences within the given array.
from copy import deepcopy
def lis(nums):
return len(max(lis_h(nums, 0), key=lambda x: len(x)))
def lis_h(nums, i):
if i == len(nums): return [[]]
arr = []
for seq in lis_h(nums, i+1):
t = deepcopy(seq)
arr.append(t)
if len(seq) == 0 or (len(seq) > 0 and nums[i] < seq[-1]): # check to see if it's less than the last one
seq.append(nums[i])
arr.append(seq)
return arr
print("\nsecond test:")
t = [10, 22, 9, 33, 21, 50, 41, 60, 80]
print(lis(t))
t = [1, 5, 2, 80, 6, 90, 10, 11]
print(lis(t))
t = [1, 100, 5, 6, 7]
print(lis(t))
# here is the O(n^2) solutuon. This will used cached sequence value to "build" the solution
# The whole premise of this problem is that we will build the solution up from subproblems
# lets think about the problem, so if we're at index i, the only subsequence that metters to index
# i is the sequence from 0 - (i-1). Thus, from every j in that range, if the value at nums[j] is < nums[i]
# then we know that this is a potential for a new greater subsequence. We then take the max of lis[j]+1 and lis[i]
# and place that into lis[i]. We add one to lis[j] because it's like were adding nums[i] to the sequence
# that gave us the value lis[j]
# this will run in O(n^2) time and will take O(n) extra space for the array
def lis2(nums):
lis = [1] * len(nums) # this will contain the lis for every index. Technically the LIS is one ATM
# go through each index less than the current one, and if the number is less
for i in range(len(nums)):
for j in range(i):
if nums[j] < nums[i]: lis[i] = max(lis[i], lis[j] + 1)
return max(lis)
print("\nThird test:")
t = [10, 22, 9, 33, 21, 50, 41, 60, 80]
print(lis2(t))
t = [1, 5, 2, 80, 6, 90, 10, 11]
print(lis2(t))
t = [1, 100, 5, 6, 7]
print(lis2(t))<file_sep>/random7.py
# Good morning! Here's your coding interview problem for today.
#
# This problem was asked by Two Sigma.
#
# Using a function rand7() that returns an integer from 1 to 7 (inclusive) with uniform probability,
# implement a function rand5() that returns an integer from 1 to 5 (inclusive)
# this problem is not very challenging because they give us a range that is greater
# than the range that we are trying to land within.
# we simply need to generate a number, using rand7, this will give us a number between
# 1-7, if the number is greater than 5, then we will simply discard the value
# and try again. Technically in the worst case this will never happen, but the probability
# of hitting 6 or 7 consistently forever is almost zero. This acts like rejection sampling
# in AI. I have provided a test that you can run. The numbers fluctuate ~ +/-15 from 200.
# thus empirically proving the uniform distribution.
import random
from collections import Counter
def rand7():
return random.randint(1, 7)
def rand5(rand7):
num = rand7()
while num > 5:
num = rand7()
return num
# test to make sure it's working
c = Counter()
for n in range(1000):
c[rand5(rand7)] += 1
# print the number of times the number showed
for k, v in c.items():
print(k, v)
<file_sep>/mergeSort.py
# Todays problem was to implement a simple merge sort algorithm
# qucik explination, we want to implement an efficient sort that
# will have a consistent O(nlogn) complexity for best, worst, and average cases
# if you don't know what that is yet, I would go look into algorithm analysis before proceeding
# to gain nlogn complexity, we want to think of splitting the array in half
# and then sorting that half, and then merging the halves together
# we will continutally break the array in half until the array size is 1
# WHAT IS THE NEGATIVE: the negative for this sort is that we need another array
# to implement this sort. It's very challenging to sort them in place, so we
# will create another array of size n to do this
# since we're going to be implementing a divide and conquer technique, it makes
# sense to use recursion
def mergesort(arr):
"""main fucntion for merge sort
arr - array of unsorted numbers"""
mergesort_h(arr, ([0] * len(arr)), 0, len(arr)-1)
def mergesort_h(arr, temp, lStart, rEnd):
"""helper function for mergesort
arr - array of unsorted numbers
temp - array used for merging
lStart - start of the current section to be sorted in the array
rEnd - end of the current section of array to be sorted
"""
if lStart >= rEnd: return # current array is of size 1 or less
mid = (lStart + rEnd) / 2 # calculates the mid of the current array
mergesort_h(arr, temp, lStart, mid) # sort the left half
mergesort_h(arr, temp, mid+1, rEnd) # sort the right half
merge(arr, temp, lStart, rEnd) # merge the left and right halves
def merge(arr, temp, lStart, rEnd):
"""function to merge the left and right halfs of the sorted array
arr - array of unsorted numbers
temp - array used for merging
lStart - start of the current section to be sorted in the array
rEnd - end of the current section of array to be sorted
"""
lEnd = (lStart + rEnd) / 2
rStart = lEnd + 1 # start of the right
left = lStart # runner for left
right = rStart # runner for right
tempI = lStart # stores the current used index in temp
# merge until one array becomes empty
while left <= lEnd and right <= rEnd:
if arr[left] <= arr[right]:
temp[tempI] = arr[left]
left += 1
else:
temp[tempI] = arr[right]
right += 1
tempI += 1 # increment the temp index
while left <= lEnd: # copy what's left in left array
temp[tempI] = arr[left]
left += 1
tempI += 1
while right <= rEnd: # copy what's left in right array
temp[tempI] = arr[right]
right += 1
tempI += 1
# copy over the array
while lStart <= rEnd:
arr[lStart] = temp[lStart]
lStart += 1
# prove that it works
nums = [1, 6, 7, 88, 3, 45, 89, 100, 2, 5, 6]
nums2 = []
nums3 = [1]
nums4 = [1, 5, 3, 4]
mergesort(nums)
mergesort(nums2)
mergesort(nums3)
mergesort(nums4)
print nums
print nums2
print nums3
print nums4
<file_sep>/card_shuffle.py
# This problem was asked by Facebook.
# Given a function that generates perfectly random numbers between 1 and k (inclusive),
# where k is an input, write a function that shuffles a deck of cards represented as an array using only swaps.
# It should run in O(N) time.
# Hint: Make sure each one of the 52! permutations of the deck is equally likely.
# For this problem, we need to break down the two most important facts
# first is that we're only allowed to swap elements
# the second is that we need to rely on the random function for something
# to randomly shuffle the cards
# lastly, we need to remember that the input for the function is an array of cards
# we can think of this as an array of numbers 1-52, and each number will represent
# a number in the deck of cards
# so when I first start thinking of the problem, I am very curious of what I am going
# to use the random function for. Immediately I think of generating a number and this
# will represent the card that we use for the swap. So we need to think of where we want
# to swap the card, and how we can ensure that the card doesn't get swapped again
# to ensure that the function is O(n). To do this, we can generate a random number 1-k
# k will be determined by the number of NON-SWAPPED ELEMENTS. To ensure this we will
# generate the number and then swap to the end of the array. When we swap to the end of the
# array, we will decrement k to ensure that we don't swap it again. We will keep doing this
# until k is equal to 1, and now the array is SHUFFLED. This is very similar to heap sort
# (if you've learned about it you can think of the decrementing of the non-sorted array
# as the decrementing of the non-shuffled array). All you need to do is implement it now
# and WE'RE DONE
# lastly, to prove that every permutation is equally as likely, we can think of it as choices
# we can think of it as we're filling spots as we go down the line, so there is initially len(n)
# choices, then len(n-1), len(n-2), and as we keep filling spots we get down to 1. Using the multiplication
# rule, we then multiply all of the choices up and get n!. Ensuring that there is an equal opportunity
# for all n! sequences.
import random
def card_shuffle(cards):
"""
Shuffles a deck of cards that is represented by an array
:param cards: array with cards
:return: shuffled deck of cards
"""
unshuffled = len(cards) # number of cards that are still unshuffled
while unshuffled > 1:
shuffle_i = random.randint(0, unshuffled)
unshuffled -= 1
swap(cards, unshuffled, shuffle_i)
return cards
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
# test to make sure it's working
c = [x for x in range(52)]
card_shuffle(c)
print(c)
<file_sep>/buddyString.py
# Hi, here's your problem today. This problem was recently asked by AirBNB:
#Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.
#Example 1:
#Input: A = "ab", B = "ba"
#Output: true
#Example 2:
#input: A = "ab", B = "ab"
#Output: false
#Example 3:
#Input: A = "aa", B = "aa"
#Output: true
#Example 4:
#Input: A = "aaaaaaabc", B = "aaaaaaacb"
#Output: true
#Example 5:
#Input: A = "", B = "aa"
#Output: false
from collections import Counter
def buddy_string(s1, s2):
# if they aren't the same length then it's not possible
if not len(s1) == len(s2) or len(s1) < 2 or len(s2) < 2:
return False
# not the same number of characters O(1) space because fixed size alphabet
if not Counter(s1) == Counter(s2):
return False
# fille up a character index map
s1_map = {c:[] for c in s1}
for i in range(len(s1)):
s1_map[s1[i]].append(i)
# for every O(n*f) where n is the number of characters and f is the frequency of repeats of those characters
for j, c in enumerate(s2):
for i in s1_map[c]: # get the list of indexes from s2:
if i is not j and swapable(s1, s2, i, j):
return True
return False
def swapable(s1, s2, i, j):
return True if s1[i] == s2[j] and s1[j] == s2[i] else False
print(buddy_string("aaaaaaabc", "aaaaaaacb"))
print(buddy_string("ab", "ab"))
print(buddy_string("", "ab"))
print(buddy_string("aa", "aa"))
print(buddy_string("ab", "cb"))<file_sep>/addingNums.py
# adding two linked lists together that represent numbers
# if we were given 99 and 25
# 9 -> 9
# 5 -> 2
# return 1 -> 2 -> 4
from Node import Node
"""
Below is my original solution. This will run in O(max(m,n)) time
but will take two passes through the list to complete. The first pass
returns the pointer to the longest list, and the second pass
performs the actual addition of the numbers. The reson I first found
the longest list is because it saved from a lot of edge cases revolving
around adding to the end of the list and expanding.
We could've also done this by breaking down the problem node by
node and then recursively solving it. The second implementation
is provided below. The second implementation only requires one
pass.
"""
def longest(l1, l2):
l1curr = l1
l2curr = l2
while l1 is not None and l2 is not None:
l1 = l1.next
l2 = l2.next
return (l2curr, l1curr) if l1 is None else (l1curr, l2curr)
def add_numbers(num1, num2):
"""
Adds two numbers together
:param num1: number created with a linked list
:param num2: number created with a linked list
:return: linked list representing a new number
"""
num1, num2 = longest(num1, num2)
new_num = num1
# check to see if we're on the last node
while num1 is not None and num2 is not None:
num1.data = num1.data + num2.data
if num1.data > 9:
tens = num1.data / 10
num1.data = num1.data % 10
num1.next = Node(tens+num1.next.data, num1.next.next) if num1.next else Node(tens)
# move to next digit
num1 = num1.next
num2 = num2.next
return new_num
def add(node1, node2, carry=0):
"""
returns a list comprised of the linked lists
:param node1: head of list 1
:param node2: head of list 2
:param carry: carry digit
:return: ll containing number
"""
if not node1 and not node2 and not carry:
return None
# get the digits
dig1 = node1.data if node1 else 0
dig2 = node2.data if node2 else 0
total = dig1 + dig2 + carry
# move down the list of possible
node2 = node2.next if node2 else None
node1 = node1.next if node1 else None
return Node(total % 10, add(node1, node2, total / 10))
def print_num(node):
if not node: return
print_num(node.next)
print(node.data)
# testing for first method
number1 = Node(9, Node(9, Node(1)))
number2 = Node(5, Node(8, Node(3)))
print_num(add_numbers(number1, number2))
print("\nnextNumber:\n")
number1 = Node(9, Node(9, Node(1)))
number2 = Node(5, Node(8, Node(3)))
print_num(add(number1, number2))
<file_sep>/anagramWords.py
# Given a list of words, group the words that are anagrams of each other. (An anagram are words made up of the same letters).
# Example:
# Input: ['abc', 'bcd', 'cba', 'cbd', 'efg']
# Output: [['abc', 'cba'], ['bcd', 'cbd'], ['efg']]
# O(n*a) time complexity and O(n) space
from collections import Counter
def anagram_words(words: list) -> list:
anagram_dict = dict()
for word in words: # O(N)
found = False
for key in anagram_dict.keys(): # O(a) where a is the number of anagrams
if Counter(word) == Counter(key): # assuming we have a fixed character set, this is O(1)
anagram_dict[key].append(word)
found = True
# check to see if we didn't find an anagram
if not found: anagram_dict[word] = [word]
# concatinate all of the keys into a list
return [lst for lst in anagram_dict.values()]
print(anagram_words(['abc', 'bcd', 'cba', 'cbd', 'cab', 'efg']))
<file_sep>/circularMaxSubarray.py
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Facebook.
Given a circular array, compute its maximum subarray sum in O(n) time.
A subarray can be empty, and in this case the sum is 0.
For example, given [8, -1, 3, 4], return 15 as we choose the numbers 3, 4, and 8 where the 8 is obtained from wrapping around.
Given [-4, 5, 1, 0], return 6 as we choose the numbers 5 and 1.
Okay, so i've seen the problem where you have to find the max subarray, and that problem
you simply decide whether it will be more beneficial for me to take the current number and
add it to my running sum, or if we should move on and start back at 0 and start a new sum.
For this you simply walk down the array, take the max of adding the number to our running
sum and 0. The reason we choose zero, is that at any point if we dip below zero in the sum,
it's no longer beneficial for us to include that previous subsequence. For this problem, I ran into
that issue.
So for this problem, I saw it almost as the inverse of the previous problem. The reason being, is that in
the circular array you can start at any point and wrap around to that point. That's not the issue. The issue
is when do we want to stop wrapping around. Where exactly do I cut off the sequence to say that I don't want
to add any more numbers. For this, I started looking more into the problem. I realized that we really are looking
to remove the most negative subsequence from the total sum. The reason being that we take the total sum is
that the array is circular, so we can start at any point and rotate back to the front, but we want to remove
the MOST NEGATIVE SEQUENCE to give us the max positive sequence of numbers from the array. If there are no negative
numbers, then we just subtract 0 from the total, otherwise, we simply remove the most negative sequence. This allows
us to tackle the issue that we found before where we might actually want to inlcude a negative number in our sequence
because it might lead to a future reward that will negate the small negative charge currently.
This algorithm will make two passes so it will perform in O(n) time
- one pass to create the total sum, one pass to find the most negative subsequence and remove it from the sum
"""
def circular_max_subarray(nums) -> int:
total_sum = sum(nums)
# max of the negative subarray
# find the maximum negative subarray
left = 0
right = 0
max_negative_subarray = 0
curr_negative_subarray = nums[left] if nums else 0
while left < len(nums):
# check to see if right is less than left
if right < left:
right = left - 1
curr_negative_subarray = 0
# check to see if we should add the next number
next_num = nums[(right + 1) % len(nums)]
if curr_negative_subarray + next_num < 0:
curr_negative_subarray += next_num
right += 1
else: # we shouldn't add it, move left up
curr_negative_subarray -= nums[left]
left += 1
max_negative_subarray = min(max_negative_subarray, curr_negative_subarray)
"""
for i, num in enumerate(nums):
# decide if we should add the current number
curr_negative_subarray = min(0, num + curr_negative_subarray)
max_negative_subarray = min(max_negative_subarray, curr_negative_subarray)
15
6
23
13
15
5
"""
# subtract the max negative subarray from the total sum
return total_sum - max_negative_subarray
print(circular_max_subarray([8, -1, 3, 4]))
print(circular_max_subarray([-4, 5, 1, 0]))
print(circular_max_subarray([10, -4, -8, 5, 8, 1, 0, -1]))
print(circular_max_subarray([-11, 10, -4, -8, 5, 8, 1, 0, -1])) # should return 13, because adding 10 is no longer beneficial
print(circular_max_subarray([10, -4, -8, 5, 8, -8, 1, 0, -1])) # should return 15, because we start at five and wrap to 10
print(circular_max_subarray([-11, 10, -4, -8, 5, 8, -8, 1, 0, -1])) # should return 15, because we start at five and wrap to 10
<file_sep>/anagramIndices.py
"""
Given a word w and a string s, find all indices n s which are the starting
locations of anagrams of w. For example, given w = ab and s = abxaba, return [0, 3, 4]
So the first thing to think about is what an anagram is? A string is an anagram
if it contains the same number of distinct letters. So for the case in the
example above, the anagram would be if there was 1 a and 1 b in the substring
starting at index i and ending at i+1
What does counting for us? Well we can think of counting with a dictionary,
this would allow us to pass through in O(k) time but would take O(k) space
where k = len(w). Another approach is to sort the strings and then compare the
strings, this would take klogk time (assuming you use qsort or another sort
with this time complexity). The trade-off of time and space will have to be
decided based on the function that you're designing. I will choose to use
the counter version
"""
# import a counter dictionary
from collections import Counter
def is_anagram(s1, s2):
"""
This function will decide whether the two strings
are anagrams of eachother
:param s1: string 1
:param s2: string 2
:return: true if they're anagrams of eachother
"""
if len(s1) is not len(s2): return False
return Counter(s1) == Counter(s2)
def ana_indices(w, s):
"""
Function returns a list containing the indices that are
an anagram of w.
:param w: word that is used for anagram
:param s: string containing letters that will be indexed
:return: list containing indexes that are
"""
indices = []
# iterate through indices that will allow len(w)-1 strings from there
for i in range(len(s) - (len(w)-1)):
# create the substring
sub = s[i:i+len(w)]
if is_anagram(sub, w):
indices.append(i)
return indices
# testing
print(ana_indices("ab", "abxaba"))
print(ana_indices("he","helloeh"))
print(ana_indices("", "world")) # every index is an anagram
print(ana_indices("word", "")) # test on an empty string
<file_sep>/read7.py
# This problem was asked Microsoft.
# Using a read7() method that returns 7 characters from a file, implement readN(n) which reads n characters.
# For example, given a file with the content “Hello world”, three read7() returns “Hello w”, “orld” and then “”.
# from what it looks like read7 handles there being nothing left to read in a file. So let's not worry
# too much about that and focus on what is going on with the reading
# Lets first look at how many reads we need for the number n. let's assume n > 7 initailly. So for n > 7
# there will be n/7 reads where we use the whole output from read7. Then there will be one last read (assuming n%7 != 0)
# where we only partially use the string that is returnned from read7. More specifically, we will use n%7 characters from it
# if n is < 7, then we will perform n/7 full reads (or zero) and use n characters from read7.
# So, we know how to throw this function together
def readN(n: int, read7) -> str:
result = ""
full_reads = n/7 # number of full reads
while full_reads > 0:
result += read7() # read 7 characters
# add the last characters
return (result + read7()[:n%7]) # concatinate and return<file_sep>/maxStockProfit.py
# If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
#
# Note that you cannot sell a stock before you buy one.
#
# Example 1:
#
# Input: [7,1,5,3,6,4]
# Output: 5
# Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
# Not 7-1 = 6, as selling price needs to be larger than buying price.
# Example 2:
#
# Input: [7,6,4,3,1]
# Output: 0
# Explanation: In this case, no transaction is done, i.e. max profit = 0.
# If you think intuitively of this problem, at every index i, we want to subtract
# from that index, the smallest price before that number. This will be a running
# min that we will calculate. We then subtract that min from the current val
# and then update max_profit using the max function. Pretty simple, just need
# to see the concept and you'll get it.
# Ranked in the top 100 interview questions
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_profit = 0
min_val = 0 if len(prices) == 0 else prices[0] # gets the min val
for price in prices:
min_val = min(min_val, price)
max_profit = max(max_profit, price - min_val)
return max_profit<file_sep>/levenshtein.py
def levenshteinDistance(str1, str2):
if str1 == "" and str2 == "": return 0 # we made it to the bottom
if str1 == "": return len(str2) # string 1 is empty
if str2 == "": return len(str1) # string 2 is empty
if str1[-1] == str2[-1]:
return levenshteinDistance(str1[:-1], str2[:-1])
remove = 1 + levenshteinDistance(str1[:-1], str2)
insert = 1 + levenshteinDistance(str1, str2[:-1])
sub = 1 + levenshteinDistance(str1[:-1], str2[:-1])
return min(remove, min(sub, insert))
import sys
def edit_distance(str1, str2):
if str1 == "" and str2 == "": return 0 # we made it to the bottom
if str1 == "": return len(str2) # string 1 is empty
if str2 == "": return len(str1) # string 2 is empty
# create the table to be used, 0 index will be empty subtring
table = [[0 for _ in range(len(str2)+1)] for _ in range(len(str1)+1)]
for str1_i in range(len(table)): # iterate through the string1 characters
for str2_i in range(len(table[0])): # iterate through the string2 characters
if str1_i == 0 and str2_i == 0: continue
# get the characters and check for equality
same = sys.maxsize # set it to the max size
if str1_i > 0 and str2_i > 0:
# get the two characters
c1 = str1[str1_i-1]
c2 = str2[str2_i-1]
if c1 == c2: same = table[str1_i-1][str1_i-1]
remove = sys.maxsize if str1_i - 1 < 0 else table[str1_i-1][str2_i]
insert = sys.maxsize if str2_i - 1 < 0 else table[str1_i][str2_i-1]
replace = sys.maxsize if str1_i - 1 < 0 or str1_i - 1 < 0 else table[str1_i-1][str2_i-1]
# find the min move and add one to it
min_move = min(remove, min(insert, min(replace, same)))
table[str1_i][str2_i] = min_move + 1
print("str1_i: {x} str2_i: {y} distance {dist}".format(x=str1_i, y=str2_i, dist=table[str1_i][str2_i]))
return table[len(table)-1][len(table[0])-1]
print(edit_distance("y", "ay"))<file_sep>/climbStairs.py
"""
Hi, here's your problem today. This problem was recently asked by LinkedIn:
You are given a positive integer N which represents the number of steps in a staircase.
You can either climb 1 or 2 steps at a time. Write a function that returns the number of unique ways to climb the stairs.
def staircase(n):
# Fill this in.
print staircase(4)
# 5
print staircase(5)
# 8
Can you find a solution in O(n) time?
So this is A CLASSIC
Let's first solve this recursively and then get to the O(n) time. This is very similar to the fib
problem. If not, exactly like it.
So, here we can think we start at the nth stair, and the ways to get to the nth stair are the ways
to get to the n-2 stair and n-1 stair. We can then see that there are two base cases. When n=1, there
is one way to get up that stair and when n=2, there are two ways to get up teh stair.
Once we have that, we can see that we can actually start form the bottom and build up the solution
because we need the n-1 and n-2 number to get the nth number, just like fib right. So start at the
1 and 2 and then build up from there! Let's do it!
O(n) time and space
"""
def recursive_stair(n) -> int:
# base cases
if n <= 0: return 0
if n == 1: return 1
if n == 2: return 2
return recursive_stair(n-2) + recursive_stair(n-1)
print("5 steps", recursive_stair(5))
print("4 steps", recursive_stair(4))
print("27 steps", recursive_stair(27))
def iterative_stair(n) -> int:
if n <= 0: return 0
# build an array to hold the numbers
ways_to_climb = [0 for i in range(n+1)] # note that we have to do n+1 to make sure we can store the nth value
ways_to_climb[1] = 1 # set the base cases to build up the soltion
ways_to_climb[2] = 2
for stair in range(3, n+1):
ways_to_climb[stair] = ways_to_climb[stair-2] + ways_to_climb[stair-1]
return ways_to_climb[n]
print("5 steps", iterative_stair(5))
print("4 steps", iterative_stair(4))
print("27 steps", iterative_stair(27))
"""
We can then see that we can just use two variables to store the
values instead of using an array to store the values
O(n) time O(1) space
"""
def iterative_stair_no_space(n) -> int:
if n <= 0: return 0
if n == 1: return 1
if n == 2: return 2
one_lower = 2 # act like this is the second stair
two_lower = 1 # act like this is the first stair
for stiar in range(3, n):
ways_to_climb_stair = one_lower + two_lower
# update the variables
two_lower = one_lower
one_lower = ways_to_climb_stair
return two_lower + one_lower
print("5 steps", iterative_stair_no_space(5))
print("4 steps", iterative_stair_no_space(4))
print("27 steps", iterative_stair_no_space(27))<file_sep>/removeKthelement.py
# This problem was asked by Google.
# Given a singly linked list and an integer k, remove the kth last element from the list.
# k is guaranteed to be smaller than the length of the list.
# The list is very long, so making more than one pass is prohibitively expensive.
# Do this in constant space and in one pass.
"""
Immediately when I see a linked list problem that requires one pass, I automatically
think about using "runners". I define runners as pointers that move down the
list and point to nodes that are needed. As you move down the list, they "run" down
the list with you. So, let's first look at this problem as if we were removing the
kth element from the list, that is simple, we move a runner down to the kth node
and remove that from the list. Okay, that was easy! Now we need to remove the kth
element from the END of the list. So, we just created a distance k from the front
of the list to remove the kth element from the front, if we can maintain that
distance k from the back of the list, then we can remove the kth from the back.
This is where runners come into play. We want to have two runners, the first runner
will go a distance k from the front of the list and then stop. The second runner
will start once the first runner gets to k. they will then move one step at a time
in sychrony until the first runner reaches the end of the list. Since the two runners
were a distance k apart from eachother, this distance will be maintained and now
the SECOND runner will be a distance K from the end of the list. We can then remove
the node from the list and BAMMMM. You've just removed the kth node from the end of the LL.
"""
class Node:
"""
node class used to create a linked list
"""
def __init__(self, val=0, n=None):
self.val = val
self.n = n
def g_n(self):
return self.n
def g_val(self):
return self.val
def set_n(self, node):
self.n = node
def set_val(self, val):
self.val = val
def remove_k_end(head, k):
"""
Removes the kth node from the linked list
:param head: linked list
:param k: position to remove from the ll
"""
rem = head
kth = head
# get to the kth pos
while k > 0:
kth = kth.g_n()
k -= 1
while kth.g_n() is not None:
kth = kth.g_n()
rem = rem.g_n()
# remove it, and return head
rem.set_n(rem.g_n().g_n())
return head
# testing to make sure it works
# create the ll
ll = Node(0, Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, None)))))))
curr = remove_k_end(ll, 2)
while curr is not None:
print(curr.g_val())
curr = curr.g_n()
<file_sep>/reversebits.cpp
/*
Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596,
so return 964176192 which its binary representation is 00111001011110000010100101000000.
This is another problem that I chose to use C++ because I prefer it for bit manipulation.
For this problem, it's really no different than reversing a strinng.
You maintain a "bit-pointer" that is used to move down the bits of the numbers and selects the bits
Then you take the bit and place that into the bit location that would be the reveresed location
for that bit. Really, the only thing different than this and reversing a string is understanding the
masks and bit-wise operations. I'll explain what I did with the mask and bitwise operations below
num: this variable that I created is a 32 bit integer that is filled with all zeros; I used hex because I'm cool
bit_selecet: this is used as a the "bit-pointer" that will "select" bits as it moves down the original number
So the whole premice of this algorithm is to move the bit pointer down using a left shift, select the digit
from n using the and operator (we do this because bit select is a 1 and we want to know if that shift'th bit is a one)
I then right shift it because I prefer to deal with shifting from the 0th place (you can do the math and not do this)
I then or this with num after I shift it 31-shift to the left. The reason we do a minus is that we want it shift away
from the last left digit when we are reversing a bit that is shift away from the rightmost digit. We then do this
for every digit in the number and BOOM. You have the answer, which by the way is 100% faster than all other solutions
on leetcode...
Please like this repo and follow it if you're enjoying the content! I really appreciate all the support
- cheers, Brady
*/
#include <cstdint>
uint32_t reverseBits(uint32_t n) {
uint32_t num = 0x0; // start it with 0;
uint32_t bit_select = 0x1; // used to select bits
for(int shift = 0; shift < 32; ++shift){
uint32_t bit = (n & (bit_select << shift)) >> shift; // get the bit
num = num | (bit << 31-shift); // reverse it
}
return num;
}
<file_sep>/symmetric_nary.py
class Node:
def __init__(self, value, children=[]):
self.value = value
self.children = children
def is_symmetric(root):
stack = create_stack(root)
symmetric = check_roots_symmertric(root)
while stack and symmetric:
# do something
node1, node2 = stack.pop()
symmetric = check_roots_symmertric(node1, node2)
stack += create_stack(node1, node2)
return symmetric
def check_roots_symmertric(root1, root2=None):
root1_children = root1.children
# check to see if it's the center of a a new tree
root2_children = root2.children if root2 else root1_children
# has to be done because zip will only create an iterator
# up to the length of the shortest, so there could be an
# outlier when there is an extra element but everything else is symmetric
symmetric = True if len(root2_children) == len(root1_children) else False
# check to see if the children are symmetric
for node1, node2 in zip(reversed(root1_children), root2_children):
if node1.value is not node2.value:
symmetric = False
break
return symmetric
def create_stack(root, root2=None):
stack = []
# create iteration
children1 = root.children
children2 = reversed(root2.children if root2 else root.children)
# create tuple children up to the middle (middle)
for child1, child2 in zip(children1, children2):
stack.append((child1, child2))
return stack
tree = Node(4)
tree.children = [Node(3), Node(3)]
tree.children[0].children = [Node(9), Node(4), Node(1, children=[Node(2)])]
tree.children[1].children = [Node(1, children=[Node(2)]), Node(4), Node(9)]
# true
print(is_symmetric(tree))
# add an extra node, should be false
tree.children[0].children = [Node(9), Node(4), Node(1, children=[Node(2), Node(3)])]
print(is_symmetric(tree))<file_sep>/topToBottomRight.py
# Good morning! Here's your coding interview problem for today.
#
# This problem was asked by Facebook.
#
# There is an N by M matrix of zeroes.
# Given N and M, write a function to count the number of ways of starting at the top-left corner
# and getting to the bottom-right corner. You can only move right or down.
#
# For example, given a 2 by 2 matrix, you should return 2, since there are two ways to get to the bottom-right:
# Right, then down
# Down, then right
# Given a 5 by 5 matrix, there are 70 ways to get to the bottom-right.
# here is a simple brute force solution. I was a little confused if we were actually given the array
# of not, so I simply used the nxm matrix lengths that were given. Keep in mind that n is the number
# of rows in the matrix and m is the number of columns in the matrix. this will have an O(2^(mxn)) complexity
# obviously we can make this better, so present this general brute force solution to the interviewer and then
# get thinking again because we CAN AND WILL DO BETTER!
def calculate_paths(arr):
"""
calculates the number of paths from the top left of a matrix to the bottom right
:param n: rows in the matrix
:param m: columns in the matrix
:return: int representing the number of paths to the bottom right
"""
return _c_p_help((0, 0), len(arr)-1, len(arr[0])-1)
def _c_p_help(pos, row, col):
if pos[0] > col or pos[1] > row: return 0 # there is no more moves
if pos == (col, row): return 1 # formulates one path
return _c_p_help((pos[0] + 1, pos[1]), row, col) + _c_p_help((pos[0], pos[1] + 1), row, col)
def matrix(n, m):
return [[0 for i in range(m)] for y in range(n)]
print(calculate_paths(matrix(2, 2))) # should be 2
print(calculate_paths(matrix(5, 5))) # should be 70
# since I was a little confused on whether or not the array was actually provided or not,
# I am going to use the array in this solution. For this solution, we will do some pruning
# by utilizing the integers within array to store data. Think of the sub problem as each
# element within the array will act as the top left of a sub matrix. So if we can
# store the number of paths from there to the bottom right, then we don't have to do
# that calculation again.
def calculate_paths2(arr):
return
<file_sep>/squareRootFinder.py
# Good morning! Here's your coding interview problem for today.
# Given a real number n, find the square root of n. For example, given n = 9, return 3.
# Okay, so before we tackle this problem, let's first understand what is going on
# we're asked to give the square root of some number n. Now, there are built in libraries
# to do something like this, but I don't think that's what they're looking for. So,
# instead, let's look at what a square root of a number n is.
# so if we start with some number n the square root of the number n is some real number a such that
# a*a = n. So, if we then move this around, it's also valid to say that a = n/a. We can then
# change it to say as well that c is a square root of n if there is some number b that divides
# n such that c == b. We then can undertand that the range of possibilities for the square root
# of sum real number n, is between 0 and n. So, naively we can go through zero -> and increment
# the counter until we get to n. This will work great for square roots that are integers,
# but what if they're floating point values?!?! There are infinity floating point numbers
# between 0 -> 1, oh lord, we're in for one brady.
# well fear not, we can still do this and ill show you how. Lets say we pick a number b that
# is between 0 and n, let's just say it's n/2 for now. We then divide n by b and get some
# number c. Knowing what we said before, if b is < c, then that means that the potential
# square root that we chose is too small, because the quotient is actually larger than
# the number that we chose. If b > c then that means that we chose a number too large.
# so knowing this, we can then discard all numbers greater than or equal to b, because
# they too will be too large (and vice versa for the previous example). We then
# cut our search range in half, and then continue doing this cut in half until we find
# a b that is equal to c.
# okay, that is great and all Brady, but how do we do the comparisons for floating points?
# So, we can subtract the two numbers and then check to see if the absolute difference betweeen
# the two numbers is less than some epsilon that we define. We can then set this epsilon
# to a very tiny number, meaning the two doubles must be extremly close to eachother in value.
# BOOM, we've just moved from an O(n) solution to an O(logn) solution. Fantastic!
# Until next time!
# Cheers, Brady
def find_sqrt(n):
epsilon = 0.0000001
left = 0
right = n
# continue if left is less than or equal to right
while left < right or abs(left-right) < epsilon:
sqrt = left + (right - left) / 2
quotient = n if not sqrt else n / sqrt
if abs(sqrt-quotient) < epsilon:
# return the value rounded to the fourth digit
return round(sqrt, 4)
elif sqrt < quotient:
left = sqrt + epsilon
else: # sqrt is greater than quotient
right = sqrt - epsilon
return -1
print('finding the sqrt of 9: {x}'.format(x= find_sqrt(9)))
print('finding the sqrt of 1: {x}'.format(x= find_sqrt(1)))
print('finding the sqrt of 7: {x}'.format(x= find_sqrt(7)))<file_sep>/permutationPalindrome.py
# Good morning! Here's your coding interview problem for today.
#This problem was asked by Amazon.
#Given a string, determine whether any permutation of it is a palindrome.
#For example, carrace should return true, since it can be rearranged to form racecar, which is a palindrome.
# daily should return false, since there's no rearrangement that can form a palindrome.
# This problem has the ability to become hard because people overthink the problem. When they see it,
# they immediately think of the permutation problem and try to generate all possible permutations and
# then check to see if that permutation is a palindrome. This is extremly niave and will create
# a factorial time complexity which makes any serious software engineer want to barf. We can
# reduce this time complexity to O(N) and O(1) space using something called a frequency counter.
# So when you look at all palindromes, they have a couple characteristics, but the one that
# we care about the most is that all valid palindromes have at most one character that has an odd
# frequency. So that means that there can only be one character that is contained in the string
# that occurs an odd number of times. Now lets look at how a frequency counter can help us. We can
# go through the string and increment the frequency of that character within the frequency counter.
# Since we assume a fixed sized alphabet, this will be O(1) space. You can then implement this with
# an array and map the ascii values of the character to an index within the array. I'm going
# to use a Counter object for simplicty purposes, but I encourage you to try it with an array as well
# Once we get all the characters frequencies, we then check to make sure there is only one character
# with an odd frequency. If there is more than one, then we return false, if there is one or less, then
# we return true
from collections import Counter
def permutation_palindrome(string):
return valid_odd_frequencies(Counter(string))
def valid_odd_frequencies(counter):
valid = True
seen_odd = False
for f in counter.values():
is_odd = True if f % 2 == 1 else False
if is_odd: # check if odd
if not seen_odd:
seen_odd = True
else: # seen odd already, not valid
valid = False
return valid
print(permutation_palindrome("carrace"))
print(permutation_palindrome("abbcad"))
print(permutation_palindrome("daily"))<file_sep>/wordDistance.py
# Good morning! Here's your coding interview problem for today.
# Find an efficient algorithm to find the smallest distance (measured in number of words) between any two given words in a string.
# For example, given words "hello", and "world" and a
# text content of "dog cat hello cat dog dog hello cat world",
# return 1 because there's only one word "cat" in between the two words.
# O(w) space where w is the number of words and the time complexity is O(w*s) where s is the longest word inputted from word1 and word2
# due to the comparisons of the words. Note that this uses the simple "two pointer" technique
import sys
def word_distance(string, word1, word2):
# split the string at the space
w1_i = w2_i = -1 # start them at -1 for not being seen
distance = sys.maxsize
for i, w in enumerate(string.split(' ')):
# update w1_i or w2_i if is the same
w1_i = i if w == word1 else w1_i # update the w1_i
w2_i = i if w == word2 else w2_i # update the w2_i
both_words_seen = True if w1_i is not -1 and w2_i is not -1 else False
if both_words_seen:
distance = min(distance, abs(w1_i - w2_i)-1)
return distance
print(word_distance("dog cat hello cat dog dog hello cat world", "hello", "world"))<file_sep>/riverSizes.py
# Here comes another graph problem!!!! WOOT WOOT MY FAVVVVVV
# given a NxM matrix containing 1's and 0's (0's representing land, and 1's representing water)
# return an array containing the sizes of rivers within the map
# A river consists of 1's that are adjacent to eachother (up, down, left, and right)
# what we want to do is simply utilize the techniques that we've done in the cloud and island
# problem. This will be running DFS on each graph node (this is simply and element in the matrix)
# and then counting it as an object we need or not, and then updating the node as visited
# When I initially wrote this algo, I had the visited too late and the recursive stack overflowed
# Make sure that when you're doing a graph problem, that when you initally touch a node, you
# mark it as visited or else you can easily run into problems where you loop forever because
# the node believes it's not visited. We're going to use a sneaky trick to mark it as visited
# by setting the graph index to -1. We will do this just for the water in this problem,
# but you can do it for anything on the graph it doesn't really matter. Okay, so when
# we get to a piece of water, we then want to call DFS on that graph node. We can then
# move forward from there and keep calling that in all directions until we've touched all
# connecting water. Whenever we touch a piece of water, we will add one to the water count
# This value will then be retuned by DFS and added to the river sizes array. Voila. Fun graph problem
# [[1 0 1 0]
# [1 1 1 0]
# [1 0 0 1]
# [0 1 0 0]
# [0 1 0 0]]
# this should return [6, 2, 1]
def dfs(land, row, col):
inRange = row in range(len(land)) and col in range(len(land[0]))
if not inRange: return 0 # went out of range
# get the topology and mark as visited
topology = land[row][col]
water = 0
if topology == 1: # check to see if we're at water
land[row][col] = -1
water += 1 # we're on water, add one
for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]: # explore graph in each direction
water += dfs(land, row+dr, col+dc)
return water
def river_size(land):
rivers = [] # array used to create the rivers
for row in range(len(land)):
for col in range(len(land[0])):
if land[row][col] == 1: # check to see if we're on water
river_size = dfs(land, row, col)
rivers.append(river_size)
return rivers
lmap = [[1, 0, 1, 0],
[1, 1, 1, 0],
[1, 0, 0, 1],
[0, 1, 0, 0],
[0, 1, 0, 0]]
print(river_size(lmap))<file_sep>/removeSortedDuplicates.py
# Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
#
# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
#
# Example 1:
#
# Given nums = [1,1,2],
#
# Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
#
# It doesn't matter what you leave beyond the returned length.
# Example 2:
#
# Given nums = [0,0,1,1,1,2,2,3,3,4],
#
# Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
#
# It doesn't matter what values are set beyond the returned length.
# the key to this problem is realizing that we can modify the array in place
# once we realize that we can do that, we can act like the array is split
# into two pieces. Everything from zero up to last is contained within
# the non-duplicate sorted array. What we can then do is start at position
# i and iterate over all of the numbers at each index to the right of that
# which are also equal to nums[i]. As we iterate over these numbers,
# We're indirectly getting rid of them because we never move the i ptr
# backwards. We then set the value of nums[last] = nums[i] to update the
# one copy that we needed into the non-duplicate array. We aren't worried
# about overwriting a value that we need because last is guaranteed to be <= i
# where the only values that are important to us from there on forward are
# >= i. At the end of this algo, last will contain the length of the sorted
# non-duplicate array because it's always set to store the next value,
# meaning it's one greater than the last stored index, or in other words,
# equal to the length.
def removeDuplicates(self, nums: List[int]) -> int:
last = i = 0 # assume the initial length is zero
len_nums = len(nums)
while i < len_nums:
nxt = i+ 1
# move over duplicates
while nxt < len_nums and nums[i] == nums[nxt]:
nxt += 1
# move the value to last
nums[last] = nums[i]
last += 1 # increment for next index
i = nxt
return last<file_sep>/subarraySort.py
# This is a problem that I absolutely love. It was defined as a hard problem on AlgoExpert, and I can't
# help but enjoy the math and cleverness behind the algorithm that I created.
# the question is:
# Write a function that takes in an array of integers of length at least 2.
# The function should return an array of the starting and ending indices of the smallest
# subarray in the input array that needs to be sorted in place in order for the entire input array to be sorted.
# If the input array is already sorted, the function should return [-1, -1].
# Sample input: [1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19]
# output: [3, 9]
# Okay, so let's first look at what it means to be sorted. For a number to be sorted, it must be greater
# than all of the numbers before it in the list, and less than all the numbers after it in the list. So I want you
# to notice two things: 1) if a number is unsorted, then there must be two numbers in the array that are unsorted
# 2) One number that is out of order could mean that it needs to be shifted far away from where it currently is, thus
# one number could create a large subarray that needs to be sorted i.e. [1, 3, 4, 5, -1], notice that the
# value returned for this array is [0, 4] because technically all of the numbers are not in sorted order due to
# not all the numbers before -1 being less than -1 and vice versa for all other numbers in the array.
# Okay, so how can we go about solving it?
# What we need to do is find the largest number that is unsorted and find it's sorted position, and then find
# the smallest number that is unsroted and get it's positon
# THere are a few ways that this can be done, but I chose to do it a bit of a sneaky way and I'll walk you through
# why and how it works.
# So, like I said the number in the array that we're currently at must be > the number than all the numbers to the left
# of it and it must be less than all the numbers to the right of it
# so, we can create a curr_max and iterate from left -> right through the array, if the current number is < the current
# max, that means that there is a number to the left of it that is greater than that number, so we update the leftbound
# index to that index and update curr_max by using <- max(curr_max, num). This will eventually find the rightmost index
# that the greatest number out of place needs to be placed in.
#
#
# We then do this from right to left, using a curr_min
# we check to see if the number in the iteration (from right to left in the array) is < curr_min. The reason
# we use current min is because we're using the current min of the max numbers. Just like finding the kth greatest
# number you would use a min heap .... (sorry went off on a tangent). Okay, so if the number is greater than current
# min, then there is a number to teh right of it that needs to be moved to that index or an index to the left of it.
# we then update the left range and make it equal to that index. curr_min <- min(curr_min, num). The left bound index
# continues to get updated to the index where the smallest number out of order will go. This is done by continueally
# checking if the smallest number before that number is less than the current number.
# okay, so, if we simply make two passes through this array, it will be O(n) time and O(1) space because we don't use an array
# (it will be helpful to create two arrays and follow the current_max and min from left to right and right to left respectively
# to get a greater understanding for how this works).
def subarraySort(array):
upper = find_upper(array)
lower = find_lower(array)
return [lower, upper]
def find_upper(nums):
# get the location of where the greatest unsorted number goes
upper_i = -1
curr_max = nums[0] # use a continuous max to find largest num out of order
for i in range(1, len(nums)):
num = nums[i] # get the current number and check to make sure in range
if curr_max > num:
upper_i = i
curr_max = max(curr_max, num)
return upper_i
def find_lower(nums):
lower_i = -1
curr_min = nums[len(nums)-1] # use continuous min to find smallest min out of order
for i in range(len(nums)-2, -1, -1):
num = nums[i]
if num > curr_min:
lower_i = i
curr_min = min(curr_min, num)
return lower_i
<file_sep>/validateBST.py
# problem: given root to binary tree, validate if BST
# This problem is more so understanding what is going on when you create a binary search tree.
# what really helped me create this, my I say BEAUTIFUL, peace of code is realizing that binary
# searches slowly cut the data down and create an INTERVAL that the value must land between
# this algorithm is no different. You start with the interval -inf - +inf, check the root
# against that and then split the tree in half. Okay, now the interval needs to change.
# the max anything can be to the left of the root is the value at the root, and all elements to
# the right of the root must be > then the root. This then means that When you recursively
# call the validate function, you're going to want to pass in the roots values to update the interval
# that you're validating against. This moving of information from the parent nodes to the children
# is very important and you must be able to do it both ways in interviews!!!
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
return self.validate(root, -sys.maxsize-1, sys.maxsize)
def validate(self, root: TreeNode, lrange: int, rrange:int) -> bool:
# check to see if node is within the defined interval
if root is None: return True
if not(root.val > lrange and root.val < rrange): return False
# check its subtrees
return self.validate(root.left, lrange, root.val) and self.validate(root.right, root.val, rrange)<file_sep>/balanced.py
class Tree:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_leaf(self) -> bool:
return False if self.left or self.right else True
"""
This problem was asked by PayPal.
Given a binary tree, determine whether or not it is height-balanced.
A height-balanced binary tree can be defined as one in which the heights
of the two subtrees of any node never differ by more than one.
THought process: go as far down the tree and then build up the solution
using recursion. At each node, we need to check if the left and
right subtrees of that node is balanced, and then return the height
of that node so nodes above it can determine if their subtrees are balanced.
We then will create a recursive function that keeps getting called until
the tree node that we're at is a leaf. At this point we know the subtrees
are balanced becuase they're both null and we know that the height of the
leaf. People define this differently but for this problem, im just going
to define the height of a leaf as 0. It's perfectly fine to start at 1
if that's you kind of thing. We can then give the calling node enough
information to make it's judgement by giving it back the height of
our node and whether it's subtrees were balanced. Then the calling node
will take our two heights and see if they differ no more than 1, and will
also check to see if their subtrees were balacned below it, becuase
just becuase the current nodes height are not off by more than one. it's important
to consider the nodes below them and if they were off by more than one.
If both subtrees were balanced and their heights differed by no more than
1, then we can calculate the height of the current node and then
returning true for the current node being balanced. Otherwise, we can
calculate the height and return false to let the calling node know that
the subbtree below it, at some point, was not balance.
Cheers!
"""
def balanced_tree(root):
# empty tree, return true
height, balanced = balanced_recursive(root)
return balanced
# O(N) space and O(N) time
def balanced_recursive(root):
"""
Checks to see if the subtrees below a node are balanced
returns (node_height, balanced)
"""
if not root: return (-1, True)
if root.is_leaf(): return (0, True)
# get the height of the left subtree
height_left, balanced_left = balanced_recursive(root.left)
height_right, balanced_right = balanced_recursive(root.right)
# check to see if either the right or the left is not balanced
subtrees_balanced = True if balanced_left and balanced_right else False
node_height = max(height_left, height_right) + 1
balanced_tree = True if subtrees_balanced and (abs(height_left - height_right) < 2) else False
return (node_height, balanced_tree)
tree1 = Tree(val=1, left=Tree(2), right=Tree(3))
print(balanced_tree(tree1))
# still balanced
tree2 = Tree(val=1, left=Tree(2, left=Tree(4)), right=Tree(3))
print(balanced_tree(tree2))
#unbalanced
unbalanced = Tree(val=1, left=Tree(2, left=Tree(4, left=Tree(5))), right=Tree(3))
print(balanced_tree(unbalanced))<file_sep>/powerset.py
# this is a very common problem that is used in coding interviews.
# instead of asking this problem directly, they will add some twists into
# the question, but for the most part, the problems will involve you deciding
# whether to include something in a set or list, and then validating if that
# set fits within the valid sets
# the way to think of this problem is to start with an empty set, or empty list
# and then move down the array, and at each index, choose to either add the number
# into the set or to exclude it. We have then identified the sub problem within the problem
# which will allow us to create a recursive solution to the problem
from copy import deepcopy
def powerset(nums):
"""
returns the powerset of the set nums. Length of the powerset it 2^n
:param nums: numbers within the original set
:return: array containing arrays representing sets
"""
p = []
pset_help(nums, p, [], 0)
return p
def pset_help(nums, pset, currs, i):
"""
helper function used to generate the powerset
:param nums: list of original set
:param pset: list for powerset
:param currs: list containing the current set
:param i: current index
:return: None
"""
if i == len(nums):
pset.append(deepcopy(currs))
return # reached the end of the array
pset_help(nums, pset, deepcopy(currs), i+1) # dont include it
currs.append(nums[i])
pset_help(nums, pset, deepcopy(currs), i+1)
print(powerset([1,3,5]))
def d_pset(nums):
"""
creates the powerset using dynamic programming
This will work by working our way down to the end
of the array, and then working back up recursively
:param nums: current set of numbers
:return: list containing the powerset of nums
"""
return d_pset_help(nums, 0)
def d_pset_help(nums, i):
# check to
if i == len(nums):
return [[]] # creates a list containing an empty list
pset = []
for s in d_pset_help(nums, i+1):
pset.append(deepcopy(s))
s.append(nums[i])
pset.append(deepcopy(s))
return pset
print(d_pset([1,3,5]))
<file_sep>/lexi_numbers.py
# given a number n, return a list containing numbers 1 through n
# that is sorted lexiographically
# For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]
# this problem is question 389 on leetcode
# my solution is faster than 93% of the other soltions
# I first realize that we're creating a list of numbers from 1-n, so I immediately
# think of using the range function with an initializer list to generate the numbers
# once we have the list of numbers, we then need to sort the numbers, using their
# lexiographical value. We can do this by using the built in sort function
# that is included within the list datastructure. If we used the sort algorithm
# with no arguments, then the numbers would be sorted numerically. This is not what we want
# Instead, we want to treat them as if they were strings. To do this, we change the key for
# sorting to the string representation of the number using a lambda expression. This will
# then result in the values being sorted in a lexiographical fashion but will maintain
# their numerical identity.
# viola. There you go, a simple, but useful solution.
# lastly, note that range is not inclusive on the ending value, so n+1 is used
def lexicalOrder(n):
"""
:type n: int
:rtype: List[int]
"""
l = [x for x in range(1, n + 1)]
l.sort(key=lambda v: str(v))
return l
<file_sep>/largestThreeNumProduct.py
# Hi, here's your problem today. This problem was recently asked by Microsoft:
#You are given an array of integers. Return the largest product that can be made by multiplying any 3 integers in the array.
#Example:
#[-4, -4, 2, 8] should return 128 as the largest product can be made by multiplying -4 * -4 * 8 = 128.
# okay, so this problem has a little bit of trick that comes with it. Right away, you know you can
# do this in O(N^3) time. That's pretty simple. Just create three loops and find the greatest multiple
# great, but not great! Then, I was thinking to myself, since I've been doing so much DP
# why don't I create a matrix that has all the products of pairs of two numbers from the array
# then I can loop over this matrix and multiply these numbers by the numbers in the array again...
# wait that's N^3 as well... okay, let's keep thinking about this matrix, what numbers do I really
# want to try multiplying when I get to this product. I always want to check multiplying the greatest
# number and the smallest number in the array of numbers. The reason we check the smallest number
# is because of negatives. By including negative numbers, we have to take into account that the first
# two numbers that create a product might become negative, but that number can then be made
# postive by multiplying a very small (extremly negative) number to that product. So then I thought
# wait a minute, by using this idea of the matrix, I don't actually need to store all of the products
# anymore, I can keep the intuition that I'm using a matrix, but when I get the two sums, I check
# to see if I am using the index that contais the max_i position or the min_i position, I then
# multiply it through if I'm not using one of those and take the max with my current max product!!!
# we have now decreased the complexity to O(n^2) time and O(1) space!!!! But wait, can we do better...
def three_num_max_product(nums):
min_pos = nums.index(min(nums))
max_pos = nums.index(max(nums))
max_prod = 0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
two_product = nums[i] * nums[j]
if i is not max_pos and j is not max_pos: # we can inlcude max in the product
max_prod = max(max_prod, two_product * nums[max_pos])
if i is not min_pos and j is not min_pos: # we can include the min
max_prod = max(max_prod, two_product * nums[min_pos])
return max_prod
nums = [-4, -4, 2, 8]
nums2 = [-1, 10, -100, 5]
nums3 = [-1, 20, 100, 2, 5, -3, -10]
print(three_num_max_product(nums))
print(three_num_max_product(nums2))
print(three_num_max_product(nums3))
# but then wait, let's think about why we just stored the max and the mins of the number
# when we went through to get the greatest product? When we compute the max product,
# the max product will be the product of the THREE LARGEST numbers, or the largest number
# and the TWO SMALLEST numbers. The reason it's the two smallest and not the three smallest
# is because let's say we have three negative numbers, the product will now also be negative
# so this doesn't help us at all. But if we take the two smallest, and multiply the number
# by the largest in the array, then we get the largest product (of course taht being that)
# the two smallest's product is greatest than the second and third greatest. Okay, so what is
# the best way to keep track of these? We can use a max heap for the smallest numbers
# and a min heap for the largest numbers, We then get to a number and check to see if it's
# less than the greatst of the min numbers, if so, we replaces that number and reheapify.
# for the min heap, we check to see if the number is greater than the smallest number in the
# min heap, and we replace and heapify based on that. Okay, great. We can now take the
# product of the max heap and the largest number in the min heap and then we can max that
# with the product of the min heap. Let's do that! BTW this will be O(1) space and O(N) time
# because the heap size does not depend on the input. No matter how big the input grows,
# the heap size will always be 3 adn 2. If you don't understand that, then look at big O documentation
import heapq
def product(arr):
if len(arr) == 0 or not arr: return 0
result = arr[0]
for x in arr[1:]:
result *= x
return result
def max_triple_prod(nums):
smallest_heap = [] # max of the mins (we multiply by negative 1 to allow us to use min heap still)
largest_heap = [] # mins of the maxs
for num in nums:
if len(smallest_heap) < 2:
heapq.heappush(smallest_heap, (-1*num))
elif smallest_heap[0] < num*-1:
heapq.heappushpop(smallest_heap, (-1*num))
if len(largest_heap) < 3:
heapq.heappush(largest_heap, num)
elif largest_heap[0] < num:
heapq.heappushpop(largest_heap, num)
return max(product(largest_heap), product(smallest_heap) * max(largest_heap))
print('second style')
print(max_triple_prod(nums))
print(max_triple_prod(nums2))
print(max_triple_prod(nums3))
<file_sep>/contiguousSumToK.py
# Good morning! Here's your coding interview problem for today.
# This problem was asked by Lyft.
# Given a list of integers and a number K, return which contiguous elements of the list sum to K.
# For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4], since 2 + 3 + 4 = 9.
# When I first saw this problem, I immediately took the note that the numbers that we're summing must be contiguous
# So, knowing that they must be contiguous, we know that we are summing numbers consitently one after another.
# How can we utilize this? Well, we can use two pointers, one that stores the left most index that is in the sum,
# and a right pointer that stores the right most index that is in the sum (for this problem the right index I choose
# for it to be one after the index for splicing purposes. So if the right most is at i, the i-1 index is in the sum).
# we can then use these pointers to move down the array and collect sums within the array of numbers that we're given.
# First things first, how do we know if a number is included in the sum. Let's take a look at the example to see if
# we can create some cases and how to handle them. So we're at index 0 and we see 1, if we add one to our current
# sum of 0, we will get a total sum of 1 that is less than k, this is still a valid sum so we include it and move
# the right pointer down one. We keep doing this until we get the right pointer to index 3. At this point in tiume
# we will have a total contiguous sum of 6, and the current number in question is 4. If we add 4 to the current sum,
# we will get 10 > k, so this is not valid and we can't add it to our current sum. So what do we do now?
# Since we know the current sum is not valid, the current contiguous array cannot go any further and so we make a change
# to the current sum. To do this, we subtract the leftmost value from the current sum and increment the left pointer.
# not that we still havent added for to the sum, but have just mutated where the start of this contiguous sum starts.
# the contiguous sum is now 5, and we're still at the number 4. We see that adding 4 to it get's us a k of 9 which is what we want!
# Great. Now we still increment the right pointer, because we're using a splicing for my solution, but it's just as valid to
# use a queue and enqueue and dequeue instead. In fact, that will be a solution that I produce.
def contiguous_sum(nums, k):
queue = []
curr_sum = 0
i = 0
while i < len(nums) and not curr_sum == k:
if nums[i] + curr_sum <= k:
curr_sum += nums[i]
queue.append(nums[i])
i += 1
else: # adding the number will put curr_sum above k
if queue: # try removing if possible
num = queue.pop(0)
curr_sum -= num
else: # the current number is just too big
i += 1
return queue
print(contiguous_sum([1, 4, 3, 5, 2, 10, 9], 9))
print(contiguous_sum([1, 2, 3, 4, 5], 9))
<file_sep>/pathRootToLeafSum.py
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def is_leaf(self):
return False if self.left or self.right else True
"""
For this problem, since we're moving from the top to the tree to
the bottom, I immedietaly thought of using a DFS from the top to the
bottom. Then as we move through the nodes, we will keep track of the
sum up to that node. Then when we get to a leaf, we will check to see
if the sum is equal to the target sum. Once the stack is empty,
then we know that there is no possible way to create the sum so we
return False. This will happen in O(n) time where n is the number of
nodes because we need to check all possible paths from the root
to the leafs, and then the space will be
"""
def target_sum_bst(root, target):
stack = [] if not root else [(root, 0)] # (curr node, current sum)
while stack:
curr_node, curr_sum = stack.pop()
new_sum = curr_sum + curr_node.value
# if we're at a leaf and the current
if curr_node.is_leaf() and new_sum == target:
return True
if curr_node.left: stack.append((curr_node.left, new_sum))
if curr_node.right: stack.append((curr_node.right, new_sum))
return False
# 1
# / \
# 2 3
# \ \
# 6 4
n6 = Node(6)
n4 = Node(4)
n3 = Node(3, None, n4)
n2 = Node(2, None, n6)
n1 = Node(1, n2, n3)
print(target_sum_bst(n1, 9))
# True<file_sep>/ceilAndFloorBST.py
# given the root to a BST and a key k, find the ceil and floor of the BST corresponding to k
# The ceil of the BST for value k means the smallest number that is greater than or equal to k
# and the floor being the largest number that is less than or equal to k
# So when I get a problem with a BST, you know that you are making decisions based on the sorted order
# of the tree. FOr this problem, it means that we're making decisions based on the path that we will follow
# leading to k within the tree. What happens if k is in the tree? Well this would be simple, we would follow
# the path leading to k, by making deciions based on whether the current value at the node we're at is
# >= or < the value of k. Based on that, we then move in the correct direction and keep this moving.
# once we get to k, we make floor and ceil equal to the node with k and call it a day.
# what happens if k is not in the tree though? THis is a more challenging, yet not too complicated version
# of checking for a BST in my opinion. When you check to see if a BST is valid, you use a range that you pass
# down throughout the tree. When you pass ceil and floor down with the recurisve calls, you're indirectly
# passing this range down with the recursive call! So what do we do with the range? Well we want to converge
# the range onto the number k because we want the number that is closest to k on both sides of K! SO,
# if we're at a number > k and that is < ceil, then we make ceil point to that
# node because it makes the range tighter to K!!!!! See, that's not too bad. We then continue acting in the
# way that we're searching for K, and continue updating the range until we get to k, or until we get to a leaf in
# the tree. Once we get to a leaf in the tree, we return the value. We also know the ranges that we're generating
# are correct because the moevements in a BST move us CLOSER to the value k that we're looking for. So moving in the
# other direction will not give us a range closer to the value k (we're always acting opitmally)
from tree import Tree
# recursive implementation O(d) time and space
def floor_and_ceil(root: Tree, k: int, ceil: Tree, floor: Tree):
if root is None: return ceil, floor
if root.value == k: # we found
return root, root
elif root.value > k: # current value is greater than root
ceil = root if (ceil is None or root.value < ceil.value) else ceil
return floor_and_ceil(root.left, k, ceil, floor)
else: # current value is < root
floor = root if (floor is None or root.value > floor.value) else floor
return floor_and_ceil(root.right, k, ceil, floor)
tree = Tree(10, Tree(20, Tree(31), Tree(19)), Tree(4, Tree(7, Tree(9), Tree(5)), Tree(3, None, Tree(1))))
this_ceil, this_floor = floor_and_ceil(tree, 6, None, None)
print('ceil val:', this_ceil.value)
print('floor val:', this_floor.value)
# iterative implementation
# O(d) time d being the depth of the path searching for k, O(1) space
def iterative_floor_ceil(root: Tree, k: int):
floor = ceil = None
while root is not None:
if root.value == k: # we found k
return root, root
elif root.value > k: # current value is greater than root
ceil = root if (ceil is None or root.value < ceil.value) else ceil
root = root.left
else: # current value is < root
floor = root if (floor is None or root.value > floor.value) else floor
root = root.right
return ceil, floor
this_ceil, this_floor = iterative_floor_ceil(tree, 33)
print('Iterative solution: ')
print('ceil val:', this_ceil) # there is no ceiling only a floor
print('floor val:', this_floor.value)
<file_sep>/sum67.py
# this is a really trivial problem, although it's marked as a medium
# QUESTION
# Return the sum of the numbers in the array, except ignore sections of
# numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7).
# Return 0 for no numbers.
# you could also do this in 2 passes and initially sum the whole array and then go through and subtract
# but I assume that the person interviewing wouild prefer one pass since it can be done very easily
# simply check to see if we've seen a six before the number (once we hit a seven "we no longer have seen a six")
# if the number is a 6, then set seen_six to true because this is a new subsequence that is started by the six
# Then check to see if we've not seen a six, and add the number to the sum if that's the case. Lastly, we then
# check to see if the number is a 7 after checking if we've seen six becuase if we do this before and flip to not seen
# then we will end up adding seven to it after. You could also probably maneuver the logic around, but this just made
# sense to me.
# cheeers,
# Murphy
def sum67(nums):
total_sum = 0
seen_six = False
for n in nums:
if n is 6: seen_six = True # say that we've seen a six
if not seen_six: total_sum += n
if n is 7: seen_six = False # check after potentially adding whether it's a seven
return total_sum<file_sep>/h_number.py
"""
Hi, here's your problem today. This problem was recently asked by Amazon:
The h-index is a metric that attempts to measure the productivity and citation impact of the publication of a scholar.
The definition of the h-index is if a scholar has at least h of their papers cited h times.
Given a list of publications of the number of citations a scholar has, find their h-index.
Example:
Input: [3, 5, 0, 1, 3]
Output: 3
Explanation:
There are 3 publications with 3 or more citations, hence the h-index is 3.
Solution:
sort all of the papers based on their citations
Then we start from the beginning and check to see if the citation number is greater
than or equal to the total number of citations minus the citations before that current
publication (which is equal to the current index). We then do this up until the end,
and have achieved the h_index
"""
def calculate_h_index(citations) -> int:
# sort from least to greatest citations o(nlogn)
citations.sort()
# one liner, the extra space wouldn't matter if merge sort was used because there would be extra space needed for the merge
#return max([citation if (len(citations) - i) >= citation else 0 for i, citation in enumerate(citations.sorted())])
h_index = 0
num_publications = len(citations)
for i, citation in enumerate(citations):
h_index = citation if (num_publications - i) >= citation else h_index
return h_index
# test cases
print(calculate_h_index([3, 5, 0, 1, 3]))
print(calculate_h_index([3, 5, 0, 1, 3, 4, 4, 6]))
print(calculate_h_index([0, 1, 3, 1]))<file_sep>/leetCode998.py
# Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to 'z':
# a value of 0 represents 'a', a value of 1 represents 'b', and so on.
# Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root.
# (As a reminder, any shorter prefix of a string is lexicographically smaller: for example,
# "ab" is lexicographically smaller than "aba". A leaf of a node is a node that has no children.)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isLeaf(self, rt):
"""checks to see if a node is a leaf"""
if rt.left is None and rt.right is None:
return True
return False
def smallestFromLeaf(self, root):
"""
Run a DFS to get the path of the sequence, and then return the shortest
path lexiographically
:type root: TreeNode
:rtype: str
"""
stack = [(root, "")] # (current node, sequence path)
paths = [] # list of valid paths
while len(stack) > 0:
node, path = stack.pop()
path = chr(97 + node.val) + path
if self.isLeaf(node):
paths.append(path)
else:
if node.left is not None:
stack.append((node.left, path))
if node.right is not None:
stack.append((node.right, path))
return min(paths) # return the smallest path<file_sep>/longest_string_no_repeats.py
"""
Hi, here's your problem today. This problem was recently asked by Microsoft:
Given a string, find the length of the longest substring without repeating characters.
Here is an example solution in Python language. (Any language is OK to use in an interview,
though we'd recommend Python as a generalist language utilized by companies like Google, Facebook, Netflix, Dropbox, Pinterest, Uber, etc.,)
class Solution:
def lengthOfLongestSubstring(self, s):
# Fill this in.
print Solution().lengthOfLongestSubstring('abrkaabcdefghijjxxx')
# 10
Can you find a solution in linear time?
ANSWER:
This is a classic problem where the two pointer technique comes in. We will use two pointers
The left pointer will represent the last (or first letter closest to the beginning of the string)
that is within the current substring that we're looking at. We will then use the second pointer (the faster one)
to move down the substring and add characters into the substring that we're "looking at". As we add characters
into the substring that we're looking at, then we will add the character into the seen set. (Note that although
we are using space the upperbound of characters is finite and will not depend on the input so its O(1) space actually!)
Great! So we move down the string, and decide to add into the set. But what happens if it's in the set already?
Then what we do is remove the value in the set that the left pointer is pointing to and move it up one within
the string. Then to get the length we take the max of the current max substring length and the distance
between the left and the right pointer
"""
def length_of_longest_substring(s) -> int:
# empty string
if not s: return 0
left = right = 0
longest_substring = 1
seen = set(s[left])
# while the pointers are still in the range of the string
while right + 1 < len(s) and left < len(s):
# get the next character in question
next_character = s[right+1]
# check if the current character is in the seen set
if next_character not in seen:
# add the character to the seen set, and move right becuase it's included now
seen.add(next_character)
right += 1
else:
# remove the left most and move it up one
seen.remove(s[left])
left += 1
# update the longest substring
longest_substring = max(longest_substring, right - left + 1)
return longest_substring
test_string = "abrkaabcdefghijjxxx"
print(length_of_longest_substring(test_string))<file_sep>/safeNodes.py
def dfs(i, graph, visited):
# check to see if there are no children and if in visited
if len(graph[i]) == 0: return True
if i in visited: return False
# add the node to visite
visited.append(i)
for node in graph[i]:
res = dfs(node, graph, visited)
if res: return True
return False
def eventualSafeNodes(graph):
"""
:type graph: List[List[int]]
:rtype: List[int]
"""
safe = [] # contains the safe nodes
print(len(graph[5]))
if dfs(5, graph, []):
safe.append(5)
safe.sort()
return safe
# testing graph
g = [[1, 2], [2, 3], [5], [0], [5], [], []]
print(eventualSafeNodes(g))
<file_sep>/nProbabilities.py
"""
This problem was asked by Triplebyte.
You are given n numbers as well as n probabilities that sum up to 1.
Write a function to generate one of the numbers with its corresponding probability.
For example, given the numbers [1, 2, 3, 4] and probabilities [0.1, 0.5, 0.2, 0.2],
your function should return 1 10% of the time, 2 50% of the time, and 3 and 4 20% of the time.
You can generate random numbers between 0 and 1 uniformly.
Here is my thought process. Assume we have n numbers with n probabilities.
Let's say that we have a set of boxes, that represent the numbers and their
probabilites. That would mean that each number would have a proportional number
of boxes to the total number of boxes to assure that the probability of you choosing
that box is equal to the probability of that number. I then took this idea and assumed
that we could have 100 boxes. Then, based on the probability of the numbers. I would
then assign each number their respective box count. So if 1 had a probability of 0.1,
then it would take up 10 boxes. I then did this for each of the numbers to get the
total probability of 1, or 100 boxes. Then, I used the fact that we could generate
a random number from 0-1 to get the index of the number that we chose. We would then
multiply the random number by 100 and reach into the box and return that number (or
simply look into the array and return the number that is stored at that index).
This takes O(1) space since the array does not depend on the size of input, and
takes O(n) time becuase we need to go through each of the numbers in the input.
"""
from random import seed, random
from collections import Counter
def n_number_probability_generator(nums, probabilities) -> int:
"""
Takes the numbers and their respective probabilities and returns
the numbers
"""
prob_array = [nums[0]] * 100
curr_index = 0
for num, prob in zip(nums, probabilities):
# calculate the number of array indexes to give the number
number_of_slots = int(prob * 100)
# update slots in probability array
for i in range(curr_index, curr_index+number_of_slots):
if i < len(prob_array): prob_array[i] = num
# update where we are in the probability array
curr_index = curr_index + number_of_slots
# pick a random index
random_index = int(100 * random())
return prob_array[random_index]
# test script
test_nums = [1, 2, 3, 4]
test_probabilities = [0.1, 0.5, 0.2, 0.2]
test_runs = 10_000
counter = Counter()
for iteration in range(test_runs):
counter[n_number_probability_generator(test_nums, test_probabilities)] += 1
for num, count in counter.items():
print("{num}: {prob}".format(num=num, prob= count / test_runs))
"""
My results:
1: 0.1032
4: 0.1995
2: 0.4971
3: 0.2002
"""<file_sep>/longestSubWithoutDups.py
# Given a string s. Return an integer that represents the longest substring
# that does not have repeating characters
# need to talk about how I completed this problem
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
c_set = set()
curr_max = left = right = 0 # will be used to iterate through the string
while left < len(s) and right < len(s):
if s[right] not in c_set: # this will use hash
c_set.add(s[right])
right += 1
curr_max = max(curr_max, right -left)
else: # currently in the set, might not remove, but eventually will
c_set.remove(s[left])
left += 1
return curr_max
<file_sep>/simplifypath.py
# this problem was asked by microsoft and facebook
# Given an absolute file path (Unix-style), shorten it to the format /<dir1>/<dir2>/<dir3>/....
#
# Here is some info on Unix file system paths:
#
# / is the root directory; the path should always start with it even if it isn't there in the given path;
# / is also used as a directory separator; for example,
# /code/fights denotes a fights subfolder in the code folder in the root directory;
# this also means that // stands for "change the current directory to the current directory"
# . is used to mark the current directory;
# .. is used to mark the parent directory; if the current directory is root already, .. does nothing.
# when I first encountered this problem, I realized that we want to focus on what's between the dashes
# and not the dashes themselves, so I focused on what was inside of the parentheses. I then thought of
# how we could keep track of where we were in the file system in an easy way. Since we will really
# just be focusing on the elements that were just put into the datastructure, you could think of using a
# stack, which will work, it will just require some difference with how you choose to reassemble the information
# because python does everything with lists and you can treat them like a deque, I decided to use a list
# because it will allow me to push and pop, as well as allow me to iterate in the direction that will
# be easy to concatinate all of the strings together.
# the last step to this problem is realizing that we can push and pop on and off of this datastructure
# with very simple rules. First, we must split the string at '/' and iterate over all of the strings
# Next, we must make the conditions for the strings we encounter. If we encounter a '..', we must pop
# off the current director IF THERE IS ONE IN THE DS. If the current directory is 'root' (we will assume
# this is when the list is empty) then you do not pop. Next, if we encounter '.' or '', we want to do nothing
# well, this is really trivial to take care of so I will leave that alone. Lastly, we want to append
# the directory if it's anything. So to do this, we will use if/elif statements. The one trick that I use
# is in the second elif statement, I check to see if the directory is not '.' or '', meaning it must
# be anything else within the set of possibilities. Awesome! We did it
def simplifyPath(path):
npath = []
for d in path.split('/'):
if d == '..':
if npath: npath.pop()
elif not(d == '' or d == '.'):
npath.append(d)
return '/' + '/'.join(npath)
# test
p = '/home/a/./x/../b//c/'
print(simplifyPath(p))<file_sep>/queue_with_stacks.py
# This problem was asked by Apple.
# Implement a queue using two stacks.
# Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods:
# enqueue, which inserts an element into the queue, and dequeue, which removes it.
# there are three cases, the stacks are empty, stack 1 has the front, or stack 2 has the front
# the way that I am thinking about this problem is that when we enqueue, we add to the stack
# that does not contain the element at the front of the queue. So this will then place all
# of the elements in the second stack in reverse order from how we want them. When we dequeue,
# we will remove from the stack that has one element and then move all of the elements from
# the second queue over to the queue that just had the top, EXCEPT WE LEAVE ONE ELEMENT. This
# element will now be the front of the queue.
class Queue:
def __init__(self):
"""
Initializes the queue using two stacks
s1: stack 1
s2: stack 2
empty: defines if the queue is empty (could check instead of using this space)
"""
self.s1 = list()
self.s2 = list()
self.s1Top = True
def enqueue(self, obj):
"""
enqueues the obj into the back of the queue
:param obj: object to be enqueued
"""
# both are empty or s2 is top, set s1 to top incase empty
if self.empty():
self.s1Top = True
self.s1.append(obj)
elif self.s1Top:
self.s2.append(obj)
else:
self.s1.append(obj)
def dequeue(self):
"""
dequeues the next element from the queue. If the queue is empty,
then None is returned, else, the front element is returned
:return: Object at the front of the queue
"""
obj = None
if not self.empty():
# decide how to swap
if self.s1Top:
obj = self.__swap_stacks(self.s2, self.s1)
self.s1Top = False
else:
obj = self.__swap_stacks(self.s1, self.s2)
self.s1Top = True
return obj
def empty(self):
"""
checks to see if the queue is empty
:return: True if empty, False otherwise
"""
return not(len(self.s1) or len(self.s2))
def __swap_stacks(self, filledStack, topStack):
"""
swaps the stacks by moving all of the elements to the other stack and returning
the top of the topStack initially
:param filledStack: stack that is filled with the elements
:param newStack: stack to be filled
:return: the top
"""
obj = topStack.pop()
while len(filledStack) > 1:
topStack.append(filledStack.pop())
return obj
# test the queue
q = Queue()
# test enqueue
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
# test dequeue
print(q.dequeue())
print(q.dequeue())
# enqueue some more
q.enqueue(4)
q.enqueue(5)
# dequeue the rest
while not q.empty():
print(q.dequeue())
# try to remove from an empty queue
print("this should be none: ", q.dequeue())
# add to the empty queue
q.enqueue(7)
q.enqueue(8)
q.enqueue(9)
# remove the last
while not q.empty():
print(q.dequeue())
<file_sep>/problem1.py
#Good morning! Here's your coding interview problem for today.
#This problem was recently asked by Google.
#Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
#For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
#Bonus: Can you do this in one pass?
nums = [10, 100, 4, 6, 7, 81, 2, 5, 8, 1, 0, 66, 78]
nullList = [] # check on an empty list
oneList = [1] # check on a list with one element
def sum_to_k(nums, k):
"""nums - this is a list contianing numbers
k - number seeing if we can sum to
"""
visited = set() # set that we will use to store seen values
# check to see if it's in the set, add num if not valid yet
for num in nums:
if k-num in visited: return True
else: visited.add(num)
return False # there isn't a numbers containing the sum
# test to make sure that it's working
print "Valid: ", sum_to_k(nums, 11)
print "Valid: ", sum_to_k(nums, 1)
print "Invalid: ", sum_to_k(nums, -1)
print "Empty: ", sum_to_k(nullList, 0)
print "One num should be false: ", sum_to_k(oneList, 1)
<file_sep>/secondLargestBST.py
"""
Given the root to a BST, return the node containing the second
largest value
8
/ \
10
\
14
/
12
\
13
so here we would return 13
The thought process for this is that the largest node in a BST is the node all the way to the right
so if we keep taking the option to go to the right, and when we get to the node that does not
allow us to move any farther right, that is the maximum value in the BST. So, the second largest node
in the tree, must be really close to that node, right? Well, kind of! If the maximum node is itself
a leaf node, then the node previous to that is the second largest node in the tree. But what happens
if that node is not a leaf node? Well, let's think about it, it could not have a subtree to the right
because that would mean that there is a node with a value greater than the current node which we're considering
the maximum, so that would contradict our claim of the node being the max node. So, the only case could be,
is if there is a left subtree. Now, if we think about the node that led us to the maximum node, (10 in the diagram above)
everything to the right of this node is greater than it, so returning 10 in this case would be wrong, because
we know that 13 is the second largest node. So, we can see, that if the max node has a left subtree, then we
want to return the maximum node from the left subtree, as that will be the second largest node, and NOT 10.
If the max node does not have a left subtree, then we will return the node that is previous to the max node.
So, this is simple. move as far to the right as possible, keep track of the current a prev node,
once there is no more moves to the right, check to see if there is a left subtree on the current node
if there isn't, then return prev, otherwise, return the max node from the left subtree. We then know this
algorithm is bounded by the height of the tree so the algorithm runs in O(h) time where in the best
case will be O(logn) (balanced tree) and in the worst case will be O(n) (essentially a linked list) and O(1) space.
"""
# tree node
class Node:
"""
Node used for a tree
"""
def __init__(self, value, left=None, right=None):
self.right = right
self.left = left
self.val = value
# helper methods
def has_right(self) -> bool:
return True if self.right is not None else False
def has_left(self) -> bool:
return True if self.left is not None else False
def is_leaf(self) -> bool:
return False if self.has_right() or self.has_left() else True
def find_second_largest(root: Node) -> Node:
"""
Finds the second largest node in a tree in O(h) time where h is the height of
the tree. The space is O(1) as we only use pointers to nodes within the tree
This solution assumes there is always two nodes in a tree. If there are not
two nodes, then None will be returned, indicating that there is not second
largest node.
"""
prev_node = None
curr_node = root
# find the max while keeping track of the previous
while curr_node.has_right():
prev_node = curr_node
curr_node = curr_node.right
# if the max node has a left subtree, return the max from the left subtree
if curr_node.has_left():
return find_max_node(curr_node.left)
# otherwise, return the prev node
return prev_node
def find_max_node(root: Node) -> Node:
curr_node = root
# move to the right until there is no more nodes to the right
while curr_node.has_right():
curr_node = curr_node.right
return curr_node
"""
8
/ \
10
\
14
/
12
\
13
"""
tree = Node(8, right=Node(10, right=Node(14, left=Node(12, right=Node(13)))))
"""
8
/ \
* 10
/ \
9 14
"""
tree2 = Node(8, right=Node(10, right=Node(14), left=Node(9)))
print(find_second_largest(tree).val) # should print 13
print(find_second_largest(tree2).val) # should print 10<file_sep>/centralPoints.py
# Good morning! Here's your coding interview problem for today.
# This problem was asked by LinkedIn.
# Given a list of points, a central point, and an integer k, find the nearest k points from the central point.
# For example, given the list of points [(0, 0), (5, 4), (3, 1)], the central point (1, 2), and k = 2, return [(0, 0), (3, 1)]
# so when you see the k closest or k smallest, you want to think of a heap right away
# this will then allow us to find the closest points to the center using the distance
# formula with the points that are given to us
# also notice the way that I use the heap:
# we use negative because we want to keep the closest values, so the larger ones
# we want to treat as being smaller, so we turn them negative so they get popped off first
# Also, you need to know the distance formula to solve this problem. I simply assume that this is know prior to
# attempting this solution
# my solution is O(n*log(k)) and O(k) space; since k can grow to the size of n, we must include it in the time
# comlpexity because it can grow to inifity with n
import heapq
from math import sqrt
def k_closest_points(points, cpoint, k):
k_nearest = []
cx, cy = cpoint # deconstruct the central point
for point in points: # O(n)
px, py = point # deconstruct each point
distance = sqrt(pow(px-cx, 2.0) + pow(py-cy, 2.0))
# check to see if we don't have k already
# insertion into the heap is log(k)
if len(k_nearest) < k:
heapq.heappush(k_nearest, (-1 * distance, point))
else:
heapq.heappushpop(k_nearest, (-1 * distance, point))
return [point for _, point in k_nearest]
print(k_closest_points([(0, 0), (5, 4), (3, 1), (100, 1), (1, 2)], (1, 2), 2))
<file_sep>/moveZeros.py
# Hi, here's your problem today. This problem was recently asked by Facebook:
# Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
# Example:
# Input: [0,1,0,3,12]
# Output: [1,3,12,0,0]
# You must do this in-place without making a copy of the array.
# Minimize the total number of operations.
# Right when I saw this problem I knew somewhat what I needed to do. The main thing was the concept
# that I needed to recognize, this is the TWO POINTER TECHNIQUE. The biggest thing to recognize
# is that when you get to a number in the array, you need to swap that number
# with the first zero that occurs in the array BEFORE it. You then need to have a pointer
# for the zero and for the first zero before it and for the index that you're moving down the array
#
# Watch and see how I do it below
def swap(i, j, arr):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def move_zeros(nums):
first_prev_zero = -1 # we haven't seen a zero
for i in range(len(nums)):
if first_prev_zero == -1 and nums[i] == 0:
first_prev_zero = i # set the first previous zero
if not first_prev_zero == -1 and nums[i]:
swap(first_prev_zero, i, nums)
next_zero = first_prev_zero + 1 # the next potential zero will be the location after the swap
first_prev_zero = -1 if next_zero == len(nums) or nums[next_zero] is not 0 else next_zero
return nums
test_arr = [0,1,0,3,12]
test_arr2 = [0, 0, 4, 6, 0, 1, 0, 0, 7, 9]
print(move_zeros(test_arr))
print(move_zeros(test_arr2))<file_sep>/ciruclarQueue.py
# leetcode problem 622
# Design your implementation of the circular queue.
# The circular queue is a linear data structure in which the operations are performed based on FIFO
# (First In First Out) principle and the last position is connected back to the first position to make a circle.
# It is also called "Ring Buffer".
# One of the benefits of the circular queue is that we can make use of the spaces in front of the queue.
# In a normal queue, once the queue becomes full,
# we cannot insert the next element even if there is a space in front of the queue.
# But using the circular queue, we can use the space to store new values.
# Your implementation should support following operations:
# MyCircularQueue(k): Constructor, set the size of the queue to be k.
# Front: Get the front item from the queue. If the queue is empty, return -1.
# Rear: Get the last item from the queue. If the queue is empty, return -1.
# enQueue(value): Insert an element into the circular queue. Return true if the operation is successful.
# deQueue(): Delete an element from the circular queue. Return true if the operation is successful.
# isEmpty(): Checks whether the circular queue is empty or not.
# isFull(): Checks whether the circular queue is full or not.
# the key to implementing a ciruclar queue is that there are n positions, but there are n+2 states
# if there were n+1 states, that would be fine, but we need to allow for the other state
# (i.e. if back is one space behind front, is it full or empty?)
# as a result of this, you want to add an extra space to the underlying array in your implementation
# if the back is now one less than the front, then we know the queue is empty, and if the back is
# two less than the front, then we know the queue is full
# the last implementation detail is that it's CIRUCLAR. As a result, we need to be using the mod function
# when we're incrementing value that represent the front and back index. This will ensure the values
# "wrap around" the queue. Once you understand these concepts, the rest becomes trivial.
class MyCircularQueue(object):
def __init__(self, k):
"""
Initialize your data structure here. Set the size of the queue to be k.
:type k: int
"""
self.back = -1
self.front = 0
self.size = k + 1 # use an extra space to tell teh different between empty and full
self.queue = [0] * self.size
def enQueue(self, value):
"""
Insert an element into the circular queue. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if not self.isFull():
self.back = (self.back + 1) % self.size
self.queue[self.back] = value
return True
return False
def deQueue(self):
"""
Delete an element from the circular queue. Return true if the operation is successful.
:rtype: bool
"""
if not self.isEmpty():
self.front = (self.front + 1) % self.size
return True
return False
def Front(self):
"""
Get the front item from the queue.
:rtype: int
"""
if not self.isEmpty():
return self.queue[self.front]
return -1
def Rear(self):
"""
Get the last item from the queue.
:rtype: int
"""
if not self.isEmpty():
return self.queue[self.back]
return -1
def isEmpty(self):
"""
Checks whether the circular queue is empty or not.
:rtype: bool
"""
if (self.back + 1) % self.size == self.front:
return True
return False
def isFull(self):
"""
Checks whether the circular queue is full or not.
:rtype: bool
"""
if (self.back + 2) % self.size == self.front:
return True
return False
# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()<file_sep>/nondecreasing.py
# This problem was asked by Facebook.
#
# Given an array of integers, write a function to determine whether the array could
# become non-decreasing by modifying at most 1 element.
#
# For example, given the array [10, 5, 7], you should return true,
# since we can modify the 10 into a 1 to make the array non-decreasing.
#
# Given the array [10, 5, 1], you should return false,
# since we can't modify any one element to get a non-decreasing array.
# Notes to myself: If the array is non-decreasing that means that it must
# be increasing from the left to the right, but DECREASING from the right to the left
# if we can move from right to left and then check to see if the value before the current
# value is less than OR EQUAL TO the current number, then we can move on.
# Note that using negation we get less than or equal to because it's not decreasing
# by staying stagnant.
# If the value is not, mark it as needed to be changed, but don't change it
# then if we get to a point where need to be changed is 1, and we have to change another
# return False, other wise return true
def nondecreasing(arr):
"""
Checks to see if the array given is non-decreasing or if one
Value can be changed that will make it non-decreasing
:param arr: array of numbers
:return: True if 0 or 1 element needs to be changed
"""
changed = 0
for i in reversed(range(1, len(arr))):
if arr[i-1] > arr[i]:
changed += 1 # mark the element as needed to be changed
if changed > 1: return False
return True
# check to make sure that it's working
print(nondecreasing([10, 5, 7])) # should be true
print(nondecreasing([10, 5, 1])) # should be false
print(nondecreasing([1, 8, 10, 7, 12])) # should be true
print(nondecreasing([19, 2, 7, 8, 1])) # should be false
print(nondecreasing([19, 2, 7, 8, 21])) # should be true
<file_sep>/Node.py
"""Node class used to solve linked list problems"""
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next<file_sep>/parentheses.py
# this problem has been asked by interviewers like google, fb, etc
# implement an algorith to PRINT ALL VALID (eg properly opened adn closed) combinations
# of n pair of parentheses
# Since the problem initially said that we want to print ALL of the combinations
# I immediately thought of writing a recursive algorithm. Although this may not
# be correct at first, it was the decision that I decided to make and it helps
# to tell your interviewer why you have this intuition. Anyways, on with the problem.
# Since I have had to implement a compiler checker a million times for interviews
# to check to see if the parentheses were closed or opened, I had some intuition
# on how to solve this problem, but nothing too great.
# after taking a greater look at the problem, a few things stuck out to me.
# 1. you always need to start with an open parentheses
# 2. you need to keep track of the number of pairs of parentheses within your string
# 3. you should know the number of "open" sets within the curret string that you're building
# when I say an "open" set, I mean that there is an open bracket that still needs to be closed
# after looking over these numbers, I realized that there is a connection between theses integers
# and the brackets. For every open bracket to the string, we can add one to the total number
# of open pairs within our current string, but it will not affect the number of closed pairs
# because we haven't closed anything by adding it. WHen you add a closed bracket to the
# string, you decrement the number of open paren and the number of pairs left. This is because
# a closing bracket will close the open bracket and it will complete a pair that we want.
# we then need to look at the base cases for these numbers.
# The easiest one is to know that if the open value becomes negative
# then we've closed a parentheses that does not have an open one to pair with, thus making an invalid string
# The second case is that the number of open brackets exceeds the number of pairs that are still
# left to be made. We can check for these at the beginning of the recursive call and backtrack
# when we reach these invalid states. Lastly, we know it's a valid string
# when the number of pairs is zero and open parentheses is zero.
# Although the case where pairs is zero and opn isn't zero isn't really possible, I like adding the check
# just for safety. This will have O(2^n) time complexity
# lastly, we're guarunteed to have all unique solutions because at each step in the recursive
# solution, a decision is made for the specific index within the string. Since that decision
# cannot be made again, we are guarunteed to have unique solutions
# To save some memory and time complexity of creating a new string,
# each time you append, I'm using a list and then concatinating the string together at the end.
def paren(n):
# call the helper function
paren_help(0, n, [])
def paren_help(opn, pairs, brackets):
# check if we've added too many openings or too many closings
if opn < 0 or opn > pairs: return
if pairs == 0 and opn == 0: # check to see if valid string
print("".join(brackets))
return # move back
# try to add bracket, move in the direction and then backtrack
for paren, diffo, diffp in [("(", 1, 0), (")", -1, -1)]:
brackets.append(paren)
paren_help(opn + diffo, pairs + diffp, brackets)
brackets.pop()
# testing to make sure it works
print('Set of 5')
paren(5)
print('\nSet of 4')
paren(4)<file_sep>/robotInGrid.py
# Imagine a robot sitting on the upper left corner of the grid with r rows
# and c columns. The robot can only move in two directions, right and down, but certain cells are "offliits"
# such that the robot cannot step on them. Design an algo to find A PATH for the robot from the top left
# to the bottom right.
# first things first, the problem specifies that we need to only find one path
# it also never specifies if it has to be the optimal path or not, so I'm going to
# assume that we can just use DFS and call it a day
# for this problem, I'm going to be using a build up "DP" style of code that
# will focus on building the solution from the bottom up.
# What this will do is continue calling the function until we get to the
# final destination. Once we get there, it will return an empty list, and
# then we will build the list back up by adding the move that was taken
# and then returning the list.
#
# Since this did come from the recursive section of CCI, I decided to go with
# the recrusive DP implementation, but I would normally use a stack and use backtracking
# to generate the path. Just so you can save some time and space complexity.
# also, quick note. Since we are returning the list to the stack frames, we don't allocate
# the space on the frame to store it as a parameter. A top down solution would require this
# and it would take up more space. This is something that you could talk to your interviewer about
from grid import matrix
def robot_path(grid):
"""
function to generate robot paths
"""
return rpath_help((0,0), grid)
def rpath_help(pos, grid):
"""
Helper function used to generate the path
"""
if pos[0] >= len(grid) or pos[1] >= len(grid[0]) or grid[pos[0]][pos[1]] == -1:
return None # we went off the grid, or invalid space
if pos[0] == len(grid) - 1 and pos[1] == len(grid[0]) -1:
return [] # return an empty path
# build the path from the bottom up
for dr, dc in [(1, 0), (0, 1)]:
npos = (pos[0] + dr, pos[1] + dc) # create the new pos
path = rpath_help(npos, grid)
if path is not None:
path.insert(0, (dr, dc)) # append the move onto the path
return path
# if we didn't find a valid path, return None
return None
# testing
m = matrix(5, 5)
print(robot_path(m))
<file_sep>/minPathWeight.py
#Given a m x n grid filled with non-negative numbers,
# find a path from top left to bottom right which minimizes the sum of all numbers along its path.
# Note: You can only move either down or right at any point in time.
# this problem has a very easy solution that you can think of from acting recursively
# there is only two ways to go, so given some point x,y we will act both ways and
# then return the min value for both directions. This will act recursively and will
# have a O(2^n) runtime because each node in the tree has two directions to go
# we can save some time with this by using a 2D array along with it and
# tracking values that we already computed. This will save on runtime, but will
# add the O(m*n) space to the space already needed on the stack for recursive calls.
# what if we could think in a DP standpoint and act optimally from a sub problem
# so starting at the endpoint, there is nowhere to go so we keep the value
# at that index. We then move to the left, we take the min of the
# element to the right and down and add this to the current value at that index
# we keep doing this right to left, bottom to up adding the min of the 2 directions
# to each element. The reason we work left and up is because it's the opposite of the
# movements that we are given and we're working backwards from the end goal (get why it's reversed now)
# we continue this all the way to the starting point. Now, we can simply return the value at the
# starting point and you're good to go!!! This will have an O(m*n) runtime and will require no extra spaceß
import sys
def minPathSum(grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m_sz = sys.maxsize
rows = len(grid)
cols = 0 if rows == 0 else len(grid[0])
for row in reversed(range(rows)):
for col in reversed(range(cols)):
r = m_sz if col +1 >= cols else grid[row][col +1]
d = m_sz if row +1 >= rows else grid[row +1][col]
min_val = 0 if r == m_sz and d == m_sz else min(r, d)
grid[row][col] += min_val
# return the least weighted path
return grid[0][0]<file_sep>/kmp.py
# a b c v a b b v c a
# 0 0 0 0 1 2 0 0 0 1
def failure_function(s):
pre = 0
suff = 1
pre_arr = [0] * (len(s)+1) # create the prefix function
while suff < len(s) and pre < len(s):
if s[pre] == s[suff]:
# continued prefix
pre_arr[suff+1] = pre + 1
suff += 1
pre += 1
else:
# restart prefix counter
if pre == 0:
suff += 1
pre = 0
return pre_arr
def kmp(s, pattern):
if len(s) == 0 and len(pattern) == 0: return True # both are empty
if len(pattern) == 0 or len(s) == 0: return False # once of them is empty
# we're looking for pattern within string
pre_arr = failure_function(pattern) # get the prefix array
pattern_i = str_i = 0 # set them both equal to zero
# search for the string within
occurrences = []
for i in range(len(s)):
while not pattern_i == -1:
while str_i < len(s): # continue searching as long as there is more string to search
if s[str_i] == pattern[pattern_i]: # they're equal
pattern_i += 1
str_i += 1
if pattern_i == len(pattern):
occurrences.append(str_i - pattern_i)
pattern_i -= 1 # move to potential prefix
else:
# check to see if we checked the beginning
# update on the prefix table
pattern_i -= 1
if pattern_i == -1:
str_i += 1
pattern_i = 0
else:
pattern_i = pre_arr[pattern_i]
return occurrences
print(kmp("abcvaaaavava", "aa"))
#print(failure_function("aa"))
#print(failure_function("abcvaaaavca"))
# str_i = 0->1->2
# pattern_i = 0->1->0<file_sep>/sort_LL.py
class LLNode:
def __init__(self, val, next_node=None):
self.val = val
self.next = next_node
def print_list(self):
print(self.val, end=" ")
if self.next:
self.next.print_list()
else:
print()
"""
Sort linked list in O(nlogn) time with O(1) space
This is simply a merge sort where we keep splitting the problem size in
half. At each row of the recursion tree we do O(n) amount of work
in the conquer step of the LL' comprehension. There are O(logn) rows
in the recursion tree because we split the problem size in half
each time.
I think the understanding of the problem is pretty intuitive, but
doing it might be a litt more tough. I wrote two helper functions to
help me do this problem. The first one splits a linked list in
half. The second one solves the brute force sort for mea and returns
the list. Finding the middle of a linked list is simply done by
using fast and slow pointers. As long as one is moving twice as
fast as the other it will cover twice the distance, so we know we're
at halfway when the fast pointer can no longer move two steps ahead
"""
def sort_LL(head: LLNode) -> LLNode:
return merge_srot(head)
def merge_srot(head: LLNode) -> LLNode:
# length of one or 2
if not head.next or not head.next.next:
return brute_force_sort(head)
# split in hald and call merge sort on both halves
split_left, split_right = split_ll(head)
left_sorted = merge_srot(split_left)
right_sorted = merge_srot(split_right)
# conquer both halves into one list and retunr the list
sorted_ll = None
sorted_ll_tail = None
# while there are still elements in both lsits
while left_sorted and right_sorted:
smallest_node = None
# get the smallest node from the two lists
if left_sorted.val < right_sorted.val:
smallest_node = left_sorted
left_sorted = left_sorted.next
else:
smallest_node = right_sorted
right_sorted = right_sorted.next
# remove the smallest node from on eof ht elists
smallest_node.next = None
# add the smallest node to the new list
if not sorted_ll_tail:
sorted_ll = smallest_node
sorted_ll_tail = smallest_node
else:
sorted_ll_tail.next = smallest_node
sorted_ll_tail = smallest_node
# add remaining elements
if left_sorted:
sorted_ll_tail.next = left_sorted
if right_sorted:
sorted_ll_tail.next = right_sorted
return sorted_ll
def split_ll(head: LLNode):
list1 = head
# create fast and slow pointers
fast = slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
# create list 2
list2 = slow.next
# split the lsits
slow.next = None
return (list1, list2)
def brute_force_sort(head: LLNode) -> LLNode:
node1 = head
node2 = head.next
if not node2:
return node1
smaller_val = node1.val if node1.val < node2.val else node2.val
larger_val = node1.val if node1.val > node2.val else node2.val
# assign the values
node1.val = smaller_val
node2.val = larger_val
return node1
ll = LLNode(1, LLNode(8, LLNode(3, LLNode(5, LLNode(7, LLNode(9, LLNode(2)))))))
sorted_ll = sort_LL(ll)
print("sorted list: ", end="")
sorted_ll.print_list()<file_sep>/grid.py
# python file used to create grids for coding problems
def matrix(n, m):
"""
Used to generate grids
"""
return [[0 for i in range(m)] for y in range(n)]<file_sep>/preorderTravItr.py
# Given a binary tree, return the pre-order traversal of its nodes' values
# because the recursive solution is obvious, complete the iterative one
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# to mimic recursion we will be using a stack. Since recursion continually adds stack frames
# onto the runtime stack, we should think of it in the same way to turn recursion into iteration
# next, we then know pre-order goes root->left->right
# thus, we want to initially add the root, then add right, then add left
# the reason we do this is because if the root of the tree has two children, we want the left
# child on the top of the stack. Thus, we push right then left
# we then continue poppping and pushing until the stack is empty
def preorderTraversal(root):
"""
:type root: TreeNode
:rtype: List[int]
"""
order = []
stack = [] # stack to mimic the recursion
if root is not None:
stack.append(root)
# pop off the next node then add right, left (we want left to be ontop)
while len(stack) > 0:
node = stack.pop()
if node.right is not None:
stack.append(node.right)
if node.left is not None:
stack.append(node.left)
# add to the end
order.append(node.val)
# return pre-order
return order
<file_sep>/addDigits.py
"""
Hi, here's your problem today. This problem was recently asked by Amazon:
Given a number like 159, add the digits repeatedly until you get a single number.
For instance, 1 + 5 + 9 = 15.
1 + 5 = 6.
So the answer is 6.
THOUGHT PROCESS:
What we're essentially going to be doing is, we want to be able to sum the digits of a number
and then check to see if that number is a single digit or not (we can) check to see if dividing
by 10 is greater than 0. Then we want to continue doing this until dividing by 10 is equal to zero.
"""
def add_digits(n) -> int:
summed_digits = n
while summed_digits // 10 > 0:
# not a single digit
summed_digits = _sum_digits(summed_digits)
return summed_digits
def _sum_digits(n) -> int:
num = 0
while n:
digit = n % 10
num += digit
n //= 10
return num
print(add_digits(159))<file_sep>/findMissingNumber.py
# Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
#
# Example 1:
#
# Input: [3,0,1]
# Output: 2
# Example 2:
#
# Input: [9,6,4,2,3,5,7,0,1]
# Output: 8
# this problem is painfully easy if you know some simple math formulas off the top of your head
# because they provide us with the fact that we're given n numbers from the range 0-n
# and we need to find the one number that is missing, we can simply use the formual to calculate
# the sum from 1-n, which is the sum from 0-n, and then subtract the running sum within numbers
# from that. You will then get the number that is missing.
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
total = n * (n + 1) / 2
return int(total - sum(nums))
<file_sep>/sortedArrayToBST.py
# Hi, here's your problem today. This problem was recently asked by LinkedIn:
# Given a sorted list of numbers, change it into a balanced binary search tree.
# You can assume there will be no duplicate numbers in the list.
# okay, so this problem is actually interesting. Although, not challenging, it requires you to think a bit though.
# the first thing you should do when you get a whole bunhc of jargon is to do a practice problem
# [1, 2, 3, 4, 5, 6, 7]
# we want the output to be
# 4
# 2 5
# 1 3 6 7
# Now, let's think about what it means for something to be a BST. We want for every node in the BST
# for everything to the right of it to be greater than or equal to the node, and everything to the left
# of the node to be less than the value at that node. Great. Now, let's look at the balanced definiton
# so for something to be balanced, the last full row in the tree must be at most one level less
# than the deepest node in the tree. So, to keep something balanced, it would make since if
# we divided the numbers in half, put one half on one side of the tree, and then put the other
# half on the other side of the tree. Doing this would be acting optimally and would ensure
# that we create a balanced tree. Since we know the numbers are already in sorted order, we can use this
# to our advantage. Notice that is we pull the middle number, 4, out of the list, then we have
# a situation where everything to the left of 4 in the list is less than 4 and everything to the
# right is greater than 4. We can then create a new node and give 4 the value for that node.
# we can then set the left of that node to the recursive result of this function for the
# left part of the array, and then we can set the right child of this node to the recursive result
# for the right child of the array. By picking the number in the middle, we act optimally to create
# a balanced tree, and we allow ourselves to utilize the definiton of a BST to our advantage. We
# know we're finished when the left pointer is greater than or equal to the right pointer, or with
# python (since we can utilize array splicing) when the array is empty
# let's look at how we would do this in code
# this implementation will have O(N) runtime and O(logn) space
# every number in the array has a recursive call, and there will be at most logn calls on the
# stack at once
from tree import Tree # tree node that I use for tree problmes
def sorted_list_to_BST(nums):
if nums is None or len(nums) == 0: return None # the base case
mid = (len(nums)-1) // 2
root = Tree(nums[mid])
root.left = sorted_list_to_BST(nums[:mid])
root.right = sorted_list_to_BST(nums[mid+1:])
return root
<file_sep>/youngestAncestor.py
# You're given three inputs, all of which are instances of a class that have an "ancestor" property pointing to their youngest ancestor.
# The first input is the top ancestor in an ancestral tree (i.e., the only instance that has no ancestor),
# and the other two inputs are descendants in the ancestral tree.
# Write a function that returns the youngest common ancestor to the two descendants.
# initially when I saw this problem, I got really excited, because I love working with trees and graphs
# Whenever you tackle a tree or graph problem, I highly recommend you write it out and try working through
# it on a piece of paper or a whiteboard. That will really help you come up with an algorithm!
# Try 1: in the first 30 seconds I came up witha solution that involved storing the path of one
# of the persons trail to the top ancestor, using a set (youll see why soon). Then traversing
# up the tree again with the second person until that person up the path is seen in the set.
# we use a set to allow for O(1) lookup
# this will take O(d) space and time. The d being the deeepest depth of the tree
# Try 2: Can we do this problem without extra space?
# yes, and the best way for me to think of this problem was like another problem that I saw
# where you have to find the first intersecting node in the LL
# for that problem you find the length of both LL's move the pointer pointing to the head
# of the longest list down until the current pointer points to a node at the same length
# as the shorter list (you with me still?) Then, you increment the two pointers down
# the list until they are both pointing to the same node. This is the same thing for this problem.
# we find the depth for both of the people, then increment up the tree for the deeper node. Once
# they are on the same level, we increment them up one each time until they point to the same node.
# this will always converge because they must converge to the top most ancestor node. Because
# working up the tree decreases the path options instead of increasing them
# O(d) time and O(1) space!! Viola!
def getDepth(person):
depth = 0
currAncestor = person
while currAncestor is not None:
depth += 1
currAncestor = currAncestor.ancestor
return depth
def getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo):
depthOfDescOne = getDepth(descendantOne) # get the depths
depthOfDescTwo = getDepth(descendantTwo)
# get nodes on the same level
while depthOfDescOne > depthOfDescTwo:
depthOfDescOne -= 1
descendantOne = descendantOne.ancestor
while depthOfDescTwo > depthOfDescOne:
depthOfDescTwo -= 1
descendantTwo = descendantTwo.ancestor
# increment up tree, until point at same node
while descendantOne is not descendantTwo:
descendantTwo = descendantTwo.ancestor
descendantOne = descendantOne.ancestor
return descendantTwo<file_sep>/range_tree.py
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given a binary search tree and a range [a, b] (inclusive),
return the sum of the elements of the binary search tree within the range.
For example, given the following tree:
5
/ \
3 8
/ \ / \
2 4 6 10
and the range [4, 9], return 23 (5 + 4 + 6 + 8).
"""
import math
class Node:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.right = right
self.left = left
def is_leaf(self) -> bool:
"""
if the node has a left or a right childen, then false is returned, otherwise
true is returned
"""
return not (self.left or self.right)
def sum_tree_range(root: Node, num_range:list) -> int:
"""
Sums the nodes within the BST that fall within the range given by
the two element array containing the range to be summed.
range: list witht the first element being the lower bound, and the second being the upper bound (inclusive)
bst_root: root of the BST
"""
return sum_tree_range_recursive(root, num_range, [float("-inf"), float("inf")])
def sum_tree_range_recursive(root: Node, num_range:list, bst_range: list) -> int:
"""
O(R) space and O(R) time
- where R represents the size of the range
- we only follow down the tree whne there is a path that can be within the range
as a result, the upper bound of recursive calls is the size of the range itself
"""
# check for base case of null root
if not root: return 0
# check to see if BST has any path that could some within the range
if not intersecting_ranges(bst_range, num_range):
print("not intersecting range")
return 0
# calculate the nodes position within the range
node_position = calculate_range_position(root.value, num_range)
# add the current node to the sum if it's within the range, otherwise, set sum to 0
range_sum = 0 if node_position is not 0 else root.value
# the current node has a value less than the range (or within range and still need to expore), so move to the right
# SOLVE TO THE RIGHT
if node_position == -1 or node_position == 0:
print("Moving right", [root.value, bst_range[1]])
range_sum += sum_tree_range_recursive(root.right, num_range, [root.value, bst_range[1]])
# the current node has a value greater than the range (or within range and still need to expore), so move to the left
# SOLVE TO THE LEFT
if node_position == 1 or node_position == 0:
print("Moving left", [bst_range[0], root.value])
range_sum += sum_tree_range_recursive(root.left, num_range, [bst_range[0], root.value])
return range_sum
# DOES NOT HAVE THE BST RANGE OPTIMIZATION
def sum_tree_range_iterative(root: Node, num_range: list) -> int:
range_sum = 0
stack = [root] if root else []
# while the stack isn't empty
while stack:
# get the current node, and calculate it's range position
curr_node = stack.pop()
if not curr_node: continue
curr_node_range_position = calculate_range_position(curr_node.value, num_range)
# if within the correct range, add the value
if curr_node_range_position == 0:
range_sum += curr_node.value
# add children to stack based on it's position within the range
# Explore the right
if curr_node_range_position == -1 or curr_node_range_position == 0: stack.append(curr_node.right)
# Explore the left
if curr_node_range_position == 1 or curr_node_range_position == 0: stack.append(curr_node.left)
return range_sum
def intersecting_ranges(a, b) -> bool:
intersection = min(a[1], b[1]) - max(a[0], b[0])
return True if intersection > 0 else False
def calculate_range_position(node_value: int, num_range: list) -> int:
"""
if the node_value is within the range, then 0 is returned,
if it's below the range, then -1 will be returned if it's
greater than the range, then 1 will be returned
"""
if node_value < num_range[0]: return -1
if node_value > num_range[1]: return 1
return 0
"""
5
/ \
3 8
/ \ / \
2 4 6 10
and the range [4, 9], return 23 (5 + 4 + 6 + 8).
"""
# bottom level
two = Node(value=2)
four = Node(value=4)
six = Node(value=6)
ten = Node(value=10)
eleven = Node(value=11, left=ten)
sixteen = Node(value=16, left=eleven)
# second level
three = Node(value=3, right=four, left=two)
eight = Node(value=8, right=sixteen, left=six)
# top level
five = Node(value=5, right=eight, left=three)
# recursive implementation
print("Recursive soltution")
print(sum_tree_range(five, [4, 9]))
print(sum_tree_range(eight, [4, 9]))
print(sum_tree_range(three, [4, 9]))
# iterative impelmentation
print("\nIterative soltution")
print(sum_tree_range_iterative(five, [4, 9]))
print(sum_tree_range_iterative(eight, [4, 9]))
print(sum_tree_range_iterative(three, [4, 9]))
<file_sep>/longestWordInDic.py
# Given a string and a string dictionary,
# find the longest string in the dictionary that can be formed by deleting some characters of the given string.
# If there are more than one possible results, return the longest word with the smallest lexicographical order.
# If there is no possible result, return the empty string.
#
# Example 1:
# Input:
# s = "abpcplea", d = ["ale","apple","monkey","plea"]
#
# Output:
# "apple"
# Example 2:
# Input:
# s = "abpcplea", d = ["a","b","c"]
#
# Output:
# "a"
# Note:
# All the strings in the input will only contain lower-case letters.
# The size of the dictionary won't exceed 1,000.
# The length of all the strings in the input won't exceed 1,000
# Immediately when I saw this question, I was a little nervous. The reason being is that
# I tend to be not as good with string problems as I am with other problems. BUT, this
# means I just need to work on them more, so here we go. I'm going to describe two different
# solutions for this problem.
# the first solution is a brute force solution. You've probably seen this in all kinds of
# interview problems on this repo, but it's thinking of teh solution like a powerset.
# we get to each character and thn choose to either add it to the list or not. We then
# check to see if that list matches on of the words in the dictionary and make the
# current word equal to that word. Then choose to not add it and update the current
# word if the word that didn't add it is longer or is the same length and lexiographically
# less than the currennt word. Sheesh. This will be O(2^n) time and O(n) space due
# to the stack space needed for recursion. The 2 comes from the node at each branch in the
# recursion tree branching by a factor of 2 due to adding and not adding the value
# That was a lot. Okay, now let's get to the arguably
# more simple solution that.
# My problem with initially solving this was that I was going to user a counter and then
# just make sure that the string s had >= the number of that specific character needed
# in the word. The problem that I ran into is that it's not just about the correct number,
# but also the order. That got me thinking. What if we had two "pointers" for each string
# we then move down the string s and as we move down, we check if the character at s[i] is the
# same character at word[j]; if it is, increment j because we found that character in the correct order
# We always increment i because we're passing down s, so no matter what we increment i. Then I had to think
# about the conditions for the loop. We want to stop when we've seen all the characters in word, or if
# we ran out of characters in s, so that is a simple condition to meet. You then update the max
# word if the current word is longer. I then added a little code tuning by just continuing if the current
# word that we're on is < len(m_word). This is because no matter if we found that word, it wouldn't replace
# m_word. BOOM, we now have a Olen(dic)*max(words)) complexity and are using O(max(word))
def findLongestWord(s, d):
m_word = ""
for word in d:
w_len = len(word)
if w_len < len(m_word): continue
s_index = w_index = 0 # indexes for the two strings
while w_index < w_len and s_index < len(s):
w_index = w_index + 1 if s[s_index] == word[w_index] else w_index
s_index += 1
# found all characters
if w_index == w_len:
if w_len == len(m_word):
m_word = min(m_word, word)
elif w_len > len(m_word):
m_word = word
return m_word
<file_sep>/problem5.py
# Leet code 129
# Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
# An example is the root-to-leaf path 1->2->3 which represents the number 123.
# Find the total sum of all root-to-leaf numbers.
# 1
# 2 3
# the sum would be 12+13 = 25
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.sumPaths(root, 0)
def sumPaths(self, rt, c_sum):
"""sums the paths to the leaf of the tree from root"""
if rt is None: return 0
c_sum = (c_sum * 10) + rt.val
if rt.left is None and rt.right is None: return c_sum
return self.sumPaths(rt.right, c_sum) + self.sumPaths(rt.left, c_sum)
<file_sep>/linklistmerge.py
# Good morning! Here's your coding interview problem for today.
#
# This problem was asked by Google.
#
# Given k sorted singly linked lists, write a function to merge all the lists into one sorted singly linked list.
# immediately, when I saw this problem, I knew what I needed to do, and there is a naive brute force solution
# that most people think of when they first see this problem. Naively people think of just iterating through
# all off the lists first node, and then picking the min out of those and then point to that node with the
# the pointer of the list being returned. Although this is easy and simple, the time complexity for this
# is enormous. This is because each time you pick the next smallest node, you have to go through ALL OF THE LISTS!!
# what if there was a way that we could utilize the fact that all of the lists are sorted, and initially
# go through each list once, but never have to iterate through all of them again just to find the next smallest
# The idea that I am talking about is building a heap of size k and running through all of the lists initally
# and adding the first node to the heap with an integer representing which list that this node came from.
# Once you've added the first node to the array, you will then build the min heap which takes O(k) time because
# there are k numbers. (If you need a refresher on that time complexity, I recommend you looking into heaps
# before continuing). Once we have the min heap built, we can then pop off the min value, and add the
# next node from that list that it came from (which takesn O(logk) time and then continue this process
# until all of the list pointers are at Null. We now have used a mergesort to merge all of the lists
# together in O(max(listsize)k) time and O(k) space. Much better than the niave version!!!!
# also note that I ma using heapreplace instead of heap.pop then heap.push. This is because each
# of those methods will take log(k) time whereas replace will take log(k) time.
# since I am not to sure of the input, I am assuming that the lists are given using an array that points to their
# head node.
from Node import Node # this will be used to build the LL
import heapq
def merge_k_lists(lists):
"""
Merges k sorted lists into one sorted lists
:param lists: array of linked lists
:return: sorted LinkedList
"""
heap = list() # create an array of size k
for i, n in enumerate(lists):
heap.append((n.data, n, i))
# build the min heap, and create list to return
heapq.heapify(heap)
head = None
curr = None
# continue removing and adding until correct
while len(heap) > 0:
val, minnode, arr_i, = heap[0] # peak the smallest
lists[arr_i] = lists[arr_i].next # move the current node down
n = lists[arr_i] # node to be added to the heap
minnode.next = None # set next to none so it's no longer a part of the prev list
# add it to the new list
if head is None:
head = minnode
curr = head
else:
curr.next = minnode
curr = minnode
heapq.heapreplace(heap, (n.data, n, arr_i)) if n is not None else heapq.heappop(heap)
return head
# lists to test the solution
list_a = Node(1, Node(5, Node(7)))
list_b = Node(2, Node(3, Node(4)))
list_c = Node(6, Node(10, Node(15, Node(20))))
l = [list_a, list_b, list_c]
new_head = merge_k_lists(l)
while new_head is not None:
print(new_head.data)
new_head = new_head.next
print('\ntesting on a single list:')
list_a = Node(1, Node(5, Node(7)))
new_head = merge_k_lists([list_a])
while new_head is not None:
print(new_head.data)
new_head = new_head.next
<file_sep>/kMins.py
# This problem was asked by Google.
# Given an array of integers and a number k, where 1 <= k <= length of the array,
# compute the maximum values of each subarray of length k.
# For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since:
# 10 = max(10, 5, 2)
# 7 = max(5, 2, 7)
# 8 = max(2, 7, 8)
#8 = max(7, 8, 7)
# Do this in O(n) time and O(k) space.
# You can modify the input array in-place and you do not need to store the results.
# You can simply print them out as you compute them.
# assume len(lst) >= k
# the key to solving this problem is recognizing that you're consistently moving down
# the list by removing the left most from the k values and inserting the right most
# into the comparison. As a result, the data structure that would fit this would
# be a queue, as it's insertion on one end, and deletion on the other. Since we're
# allowed to use O(k) space, which will be the size of the queue. We will fill the
# queue with the initial k items, take the max, and then remove from the front and
# add to the end to get the next max of k. This process will repeat until there
# are no more numbers to add to the queue
def k_maxs(lst, k):
"""
:param lst: list of numbers
:param k: increment of numbers that we compute the return of
:return: none, mins are printed
"""
queue = [lst[i] for i in range(k)]
lst = lst[k:]
for num in lst:
# print the min of current k, remove front add back
print(max(queue))
queue.remove(queue[0])
queue.append(num)
# print the final min
print(max(queue))
# space used for testing
lst1 = [1, 3, 5, 2, 8, 100, 3, 6]
lst2 = [10, 5, 2, 7, 8, 7]
k_maxs(lst1, 3)
print("next k_min")
k_maxs(lst1, 5)
print("their test")
k_maxs(lst2, 3)
<file_sep>/minNumberOfCoins.py
# Given an array of positive integers representing coin denominations and a single non-negative integer representing a
# target amount of money, implement a function that returns the smallest number of coins needed to make change for that
# target amount using the given coin denominations. Note that an unlimited amount of coins is at your disposal.
# If it is impossible to make change for the target amount, return -1.
# Okay, so when you see this problem, like I did, you probably thought, okay, let me just take the largest denom
# denom, divide out that number the most times, then move onto the next largest and so on, and that will
# get my answer. Yes that will work if you're give the current US coin system, but what if I gave you the
# values [3, 7] and the number 9 to count change for? You would divide out 7, then you would have remainder 2
# and then you would say that it wasn't possible and move on with your day WRONG
# When I saw this problem you want to count the nth number of coins needed to make change. So I immediately started
# thinking of recursion and DP. If you see that you need to calculate the nth number of soemthing, see if you can
# create a recurrence relation for calculating the kth number. For this, the kth value will be the T(k) = min(T(k-coin_vak), T(k))
# because if we take away the coin value from the current value that we're at, then we have T(k-coin) to find the
# smallest nuber of change for. If we minimize the smallest number of coins as we build the solution up,
# then by acting optimally, we will get the optimal solution of the min number of coins
# Once I realize the recurrence relation, I then draw out a 2D array, down the rows I put the coin denominations
# and acrosse the columns I put the values from 0-n (so the size of the matrix is coins*(n+1)). Once we have that
# we can then take the current denomination that we're at, and move down it's row, if the current i-coin_val == 0 or
# the element for any of the denominations for that column are not -1 (we initiallize the matrix to -1) Then
# we add one to that value and set the current element to the min of the current and the number of coins we just computed
# notice that we store a lot of vlaues that are -1 and we have to move down the columns for previously computed
# values, but more so even notice that we only care about the smallest value in that column, so we then
# can crush this matrix into a 1-dimmensional array that will contain the min number for that number of change
# for these denominations. We then continue the same computation except we don't have to find the min in the column
# that is not equal to -1. We still act optimmally by setting coins[i] = min(coins[i], 1+ coins[i-coin_val])
# this will now give us O(n*d) time and O(n) space. Where d is the number of denomination and n is the
# change value that we're computing
def minNumberOfCoinsForChange(n, denoms):
coins = [-1] * (n+1) # create an array of n+1
coins[0] = 0 # set the zeroth index to zero
for coin in denoms: # for every coin, try each index up to it
for i in range(coin, len(coins)): # go for every index
if (i-coin) >= 0 and (not coins[i-coin] == -1):
num_coins = 1 + coins[i-coin]
coins[i] = num_coins if coins[i] == -1 else min(coins[i], num_coins)
return coins[-1] # will be -1 if there are no ways to make it<file_sep>/tipleStep.cpp
/**
* A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time.
* Implement a method to count how many possible ways the child can run up the stairs
*
*
* So whenever you see a problem with "calculate the number of possible ways to..."
* you want to think of a recursive / dynamic programming problem
*
* For this problem, it's nice to start at the top stair and act like you're jumping backwards
* So we start at the nth step and take jumps backwards with all possibilities.
* Then we do that from the next step, and so on. We can do this completely recursively
* without any memoization, and this would take O(3^n) timecomplpexity because we have three
* directions to branch from for every node in the tree. But to decrease the time complexity
* we can store a vector (or array or whatever you want to call it in your language)
* to carry the values for each step once they're computed. Thus, when the call happens again for
* that specific step, we can simply do O(1) work by getting the value from the vector.
*
*/
#include <iostream>
#include <string>
#include <vector>
// prototype for function
int tripleStep(int i, std::vector<int> s);
int tripleStep(int n);
int main(){
int step; // variable to be used
std::cout << "How many steps are we climbing: ";
std::cin >> step;
// calculate the number of possible ways the child can step
std::vector<int> s(step+1, -1);
std::cout << "The child can step: " << tripleStep(step) << std::endl;
}
/*
Top-down solution
int tripleStep(int i, std::vector<int> s){
if(i < 0) return 0; // you can't make any movements from here
if(i == 0) return 1; // we reached a valid step sequence
if(s[i] != -1) return s[i]; // check to see if we already calculated the value
// calculate the number of sequences to get to step i
s[i] = tripleStep(i-1, s) + tripleStep(i-2, s) + tripleStep(i-3, s);
return s[i];
}
*/
/*
Create a bottom-up solution
*/
int tripleStep(int n){
int first = 1; // from the first step
int second = 2; // from the second step
int third = 4; // from the third step
for(int i = 4; i <= n; ++i){
int z = first + second + third;
first = second;
second = third;
third = z;
}
return third;
}<file_sep>/deepestNode.py
"""
Hi, here's your problem today. This problem was recently asked by Google:
You are given the root of a binary tree. Return the deepest node (the furthest node from the root).
Example:
a
/ \
b c
/
d
The deepest node in this tree is d at depth 3.
My thought process here is to use a queue, push in the node and the depth of the node
in a tuple, then if the node in question is deeper, then set that to the new deepest node
At the end, return the deepest
This will run in O(n) space and O(n) time
You could use a DFS instead of BFS and this would decrease the space to O(d),
but, I like using levels, I think they make the most sense for me to understand
in this situation, plus, RIP to Avicii
"""
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def __repr__(self):
# string representation
return self.val
def deepest(node):
# check for an empty tree
if not node: return node
# Fill this in.
deepest_node = (node, 1)
queue = [deepest_node]
# while there are still nodes to visit
while queue:
# pop off the front of the queue
node_and_level = queue.pop(0)
curr_node, curr_node_level = node_and_level
# update the deepest node in a fancy way using max
deepest_node = max(deepest_node, node_and_level, key=lambda x: x[1])
# add children to the queue if there are any
next_level = curr_node_level + 1
if curr_node.right: queue.append((curr_node.right, next_level))
if curr_node.left: queue.append((curr_node.left, next_level))
return deepest_node
root = Node('a')
root.left = Node('b')
root.left.left = Node('d')
root.right = Node('c')
print(deepest(root))<file_sep>/returnMaxLenZerosAndOnes.py
# given a binary array, return the max length of contiguous zeros and ones in the array
# capital one
# So Immediately when I saw this problem, I thought of the O(n) solution. I don't know if this
# is a testament to practice, but I realized that you want to almost converge in from the left
# and the right. Although I initially tried building from the left and incrementing the right
# I realized that we more so want to move in, instead of moving outwards. Then, when you find
# the same numbers of ones and zeros between the two you return that number, else you
# try to remove from the left if that's the correct removal, and if that's not the correct removal,
# then greedily remove from the right. The key is to decrement the count from the number
# at that index, then continue moving forward.
# lastly, we keep looping as long as left is < right, the reason being is that there will never
# be and equal number of 1's and 0's if they're also the same index, so that's why it's
# not <=
# great! O(n) time and O(1) space!! CHEERS BRADY
def max_len_zeros_and_ones(nums):
zeros = 0
ones = 0
# get the counts of all of them
for num in nums:
if num: ones += 1
else: zeros += 1
# set the pointsers
left = 0
right = len(nums) - 1
# move inwards and act greedy on removal
while left < right:
if zeros == ones:
return zeros + ones
# more zeros than ones
if ones < zeros and nums[left] == 0:
zeros -= 1
left +=1
elif zeros < ones and nums[left] == 1:
ones -= 1
left += 1
else: # remove the right
if left[nums]: ones -= 1
else: zeros -= 1
right -= 1
return 0
print(max_len_zeros_and_ones([0, 0, 0, 1, 1, 0, 0, 1 , 1, 0]))
print(max_len_zeros_and_ones([0, 0, 0, 1]))
print(max_len_zeros_and_ones([0, 0, 1, 0, 0, 1 , 1, 0]))
print(max_len_zeros_and_ones([0, 1]))
print(max_len_zeros_and_ones([0]))
print(max_len_zeros_and_ones([]))
print(max_len_zeros_and_ones([0, 0, 1, 1, 0, 0, 1 , 1, 0]))<file_sep>/editDistance.py
# This problem was asked by Google.
# The edit distance between two strings refers to the minimum number of character insertions,
# deletions, and substitutions required to change one string to the other.
# Given two strings, compute the edit distance between them.
def edit_distance_help(str1, str2, i, min_len):
"""
Gives the edit distance between two strings
:param str1: first string
:param str2: second string
:param i: index being compared
:return: the number of insertions, deletions, and removes to make the same
"""
# check if we're at the end of shortest length
if min_len is i: return abs(len(str1) - len(str2))
change = 0
if str1[i] is not str2[i]: change = 1
return change + edit_distance_help(str1, str2, i+1, min_len)
def edit_distance(str1, str2):
if str1 is None and str2 is None: return 0
if str1 is None: return len(str2)
if str2 is None: return len(str1)
# neither none, calculate edit distance
return edit_distance_help(str1, str2, 0, min(len(str1), len(str2)))
# prove that it works correctly
print(edit_distance("kitty", "abc"))
print(edit_distance("kitten", "sitting"))
print(edit_distance("brady", "shadyness"))
print(edit_distance("abc", None))
print(edit_distance(None, "abc"))
print(edit_distance(None, None))<file_sep>/nqueens.py
# The way I was going to initially solve this problem was with the AC-3
# algorithm. Because each column represents a state of possible
# variables that can be assigned, and then as you place
# the values, you eliminate the values from the tail arc. I know that probably
# wasn't the easiest description to follow, but I hope that you can look into
# AC-3 and understand what I am talking about. The reason why this isn't
# going to work is because it finds ONE solution if there is one
# think of k-coloring, all we want is one coloring of the states. It doesn't
# matter how we get there, or if there is other colorings, we just care about 1
# since this problem cares about all queen representations on the board,
# we can't use AC-3
# okay back to the drawing board. Let's assign a queen to each column
# and determine queens by their column. Then we can "place" a queen on the board
# by going to their column (or index in the board array) and then changing that
# element to the row that we're placing the queen in. We then move onto the
# next column and try to place a queen at all the rows that are valid.
# we continue doing that until the column we're at is one past the end
# of the board, and when we get there, we know that board position
# is valid because for every k column, assuming the board is valid up to that
# point, we then place a valid position and move to the k+1 column. Thus
# it acts in an inductive way so we know the board is valid from valid decisions
# from each column. The runtime is O(n^n)
# this is not great at all haha
# we also know that all solutions are unique because each state is determined
# by the prior decision. Since we only make prior decisions once, we know
# the current state is unique, and thus all solutions are unique
def n_queens(n):
p = [-1 for i in range(n)]
return eq_help(0, p, n)
def valid(col, row, qplacements):
"""
Checks to see if the current queen placement is valid
:param col: column of that specific queen
:param row: row the queen is being placed in
:param qplacements: current placements of queens
:return:
"""
# need to just validate to the right and diagonals
# the positions will be an array where each index represents the
# queens column, and the
for c, r in enumerate(qplacements):
if r == -1: continue # no queen placed yet
if r == row: return False # placed in the same row
if abs(c-col) == abs(r-row): return False # in the diagonal
# return true otherwise
return True
def eq_help(qcol, queens, n):
if qcol == n:
print(queens) # valid board
return
for row in range(n):
if valid(qcol, row, queens):
queens[qcol] = row # place the queen at the row
eq_help(qcol+1, queens, n) # place the q+1 queen
queens[qcol] = -1 # take off board
print('print all the ways to place 4 queens')
n_queens(4)
print('\nprint all the ways to print 5 queens')
n_queens(5)<file_sep>/roman.py
# given a roman num, return the value of the roman numeral
# the key here is to create a dictionary to map all the values of the letters
# iterate through the string, and only subtract the value from the number
# after it if the number before is smaller. They give some descriptions
# on the only numbers that can be decremented, but any valid roman
# numeral would stick to the more simple description I just gave.
# (question given on leetcode mock interview)
# passed all tests
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
# used as a mapping for the values
numeral = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
val = 0
i = 0
while i < len(s):
# check to see if we should decrease the value
if i+1 < len(s) and numeral[i] < numeral[i + 1]:
val += numeral[i + 1] - numeral[i]
i += 2
else:
val += numeral[i]
i += 1
# return the roman num
return val
<file_sep>/kStockTransactions.py
def find_max_stock_rev(prices, k):
return fms_help(-1, 0, k, prices)
def fms_help(curr_min, i, trans_remaining, prices):
if prices is None: return 0
if i == len(prices) or trans_remaining == 0: return 0 # there is no more profit to be made
# check to see if we update the current min
if curr_min == -1: curr_min = prices[i]
sell = (prices[i] - curr_min) if (prices[i] - curr_min) > 0 else 0
return max(sell + fms_help(-1, i+1, trans_remaining-1, prices), fms_help(min(curr_min, prices[i]), i+1, trans_remaining, prices))
stock_prices = [5, 2, 4, 0, 1]
print (find_max_stock_rev(stock_prices, 2))
<file_sep>/reversewords.py
# This problem is relatively easy to do not in place
# simply take the word and split the word at the whitespace
# you can then iterate over the words that were split in reverse order
# and then join the split words on a whitespace. bada boom bada bang
# O(s) time and space, where s is the length of the string
def reverse_words(s: str) -> str:
return ' '.join(reversed(s.split(' ')))
word = "hello world here"
print("reversed: \'{w}\'".format(w=reverse_words(word)))
# if we assume that the string is mutable (so this could be an instance where the characters are passed in
# an array) Then we can perform another algorithm to compute this result. The way I thought of this problem
# was to mentally replace all the characters for a word with a placeholder. If we then reverse the list with the
# placeholder, then the placeholder will be in the correct space i.e. the word is in the correct space in the lsit
# we just need to make sure the word is in the correct order. So if we reverse the whole list, then the words will
# be in the correct position. We then make a second pass with two pointers and reverse the words contained
# within the array themselves to get the words in the correct order.
# O(s) time and O(1) space
def reverse_words2(arr: list) -> list:
# implementation
reverse(arr, 0, len(arr)-1) # reverse the whole array
start = 0
for i in range(len(arr)):
if arr[i] == ' ' and i-1 >= 0: # check to see if we're on a delimiter
reverse(arr, start, i-1)
start = i+1 # place start after the delimiter
reverse(arr, start, len(arr)-1) # reverse the last word
return arr
def reverse(arr: list, start: int, finish: int):
while start < finish:
temp = arr[start]
arr[start] = arr[finish]
arr[finish] = temp
start += 1
finish -=1
word
word_list = [c for c in word]
print("".join(reverse_words2(word_list)))<file_sep>/excelColumn.py
# Given a column title as appear in an Excel sheet, return its corresponding column number.
#
# For example:
#
# A -> 1
# B -> 2
# C -> 3
# ...
# Z -> 26
# AA -> 27
# AB -> 28
# ...
# Example 1:
#
# Input: "A"
# Output: 1
# Example 2:
#
# Input: "AB"
# Output: 28
# Example 3:
#
# Input: "ZY"
# Output: 701
# The key to this problem is recognizing the multiple, and understanding that as you move
# right to left, you want to multiply your multiple by 26. I guess that acts as like
# the base for the characters. So it's almost like you're using base 26. Pretty interesting.
def titleToNumber(s: str) -> int:
val = 0 # initial value
multi = 1
for c in reversed(s):
val += multi * (ord(c ) -64)
multi *= 26
return val<file_sep>/shortestDistance.py
# This problem was asked by Google.
# You are given an M by N matrix consisting of booleans that represents a board.
# Each True boolean represents a wall. Each False boolean represents a tile you can walk on.
# Given this matrix, a start coordinate, and an end coordinate,
# return the minimum number of steps required to reach the end coordinate from the start.
# If there is no possible path, then return null. You can move up, left, down, and right.
# You cannot move through walls. You cannot wrap around the edges of the board.
# For example, given the following board:
# [[f, f, f, f],
# [t, t, f, t],
# [f, f, f, f],
# [f, f, f, f]]
#and start = (3, 0) (bottom left) and end = (0, 0) (top left),
# the minimum number of steps required to reach the end is 7,
# since we would need to go through (1, 2) because there is a wall everywhere else on the second row.
"""
For this problem, it's important that you immediately think of algorithms that involve the shortest
path to get to some place. Things like A* and Djikstras algo should pop into your head. For me,
it makes more since to think of each element wihtin the matrix as a node within a graph.
Each node connects to its neighbors, (up, left, down, right)
Let's first think of some of the complexities of the problem (or lack thereof). First things first,
we don't actually care about the path, we just care about the length traveled. Second, every distance
traveled is a length of 1, and since we know the start and end goal, we could use a heuristic of manhattan
distance to allow us to use A* algorithm. Lastly, we need to know about the children that can be added
as the next step from every step that we're currently at. If a neighbor is a True flag, then we don't
want to add it to the priority queue because it represents a wall. We can only add up down left and right
so we need to check the boundries of the walls
"""
import heapq
def manhattan_distance(start, end):
"""
calculates the manhattan distance between two points
:param start: tuple containing start coordinates (row, col)
:param end: tuple containing end coordinates (row, col)
:return: taxi distance between two points
"""
return abs(start[0] - end[0]) + abs(start[1] - end[1])
def neighbors(state, map):
"""
returns a list of neigh
:param state: current state within the algo
:param map: map containing true and false values
:return: list containing tuples with neighbors
"""
neighbors = []
if state[0] + 1 < len(map) and map[state[0]+1][state[1]] is not True: # moving down
neighbors.append((state[0]+1, state[1]))
if state[0] - 1 > -1 and map[state[0]-1][state[1]] is not True: # moving up
neighbors.append((state[0]-1, state[1]))
if state[1] + 1 < len(map[0]) and map[state[0]][state[1] + 1] is not True: # moving right
neighbors.append((state[0], state[1] + 1))
if state[1] - 1 > -1 and map[state[0]][state[1] - 1] is not True:
neighbors.append((state[0], state[1] - 1))
# return the neighbors from the state
return neighbors
def is_goal(state, goal):
if state[0] == goal[0] and state[1] == goal[1]:
return True
return False
def shortest_distance(map, start, goal):
"""
Given a map (matrix) of true and false booleans
return the shortest distance between two spots
:param map: matrix containing list
:param start: tuple containing start coordinates (row, col)
:param goal: tuple containing end coordinates (row, col)
:return:
"""
# priority queue used to implement A*
p_queue = [(0, ([], start))] # (f, (path, state))
visited = set() # set containing the visited nodes
while len(p_queue) > 0:
# pop off most optimistic node, add to visited
path, state = heapq.heappop(p_queue)[1]
visited.add(state)
# check if it's the goal state
if is_goal(state, goal):
return len(path)
# add children if not
for node in neighbors(state, map):
if node not in visited:
new_path = path + [node] # create a new path object
heuristic = manhattan_distance(goal, node) # find manhattan heuristic
heapq.heappush(p_queue, (heuristic + len(new_path), (new_path, node)))
# there is no path from start to goal
return -1
# testing for map distance
t_map = [[False, False, False, False],
[True, True, False, True],
[False, False, False, False],
[False, False, False, False]]
print shortest_distance(t_map, (3, 0), (0, 0))
print shortest_distance(t_map, (0, 3), (3, 3))
<file_sep>/findSquareRootN.py
"""
Good morning! Here's your coding interview problem for today.
Given a real number n, find the square root of n. For example, given n = 9, return 3.
Essentially, what we're going to do, is see if we can binary search for this number
so the way im going to look at it, is we're given a range from 0 to N, and we need
to find the number between here that when multiplied by itself gives us N. We can
then binary search for this number and find the square root in O(logn) time where n
is the number of integers from 0 to N
"""
from math import isclose
def find_square_root(n) -> float:
low = 0
high = n
while low <= high:
# get the median of the two numbers and then square it
median = (low + high) / 2.0
squared_median = median**2
# check to see how close we are to n
if isclose(n, squared_median, abs_tol=0.0003):
return round(median, 3)
elif squared_median < n: # if the current square is less than n, then don't worry about numbers smaller
low = median
else: # the squared median was too big, cut in half those numbers
high = median
# testing values
print(find_square_root(9))
print(find_square_root(15))
print(find_square_root(81))
print(find_square_root(144))
print(find_square_root(181))<file_sep>/dominos.py
# Hi, here's your problem today. This problem was recently asked by Twitter:
# Given a string with the initial condition of dominoes, where:
# . represents that the domino is standing still
# L represents that the domino is falling to the left side
# R represents that the domino is falling to the right side
# Figure out the final position of the dominoes.
# If there are dominoes that get pushed on both ends, the force cancels out and that domino remains upright.
# Example:
# Input: ..R...L..R.
# Output: ..RR.LL..RR
# Okay so I remember trying to do this problem around a year ago when my interview journey began
# I was on leet code, saw this problem, and thought that it couldn't be too bad, so I sat there an tried to figure
# it out but I continually failed. My problem was that I didn't understand how to handle the actions and
# organize them in a way that it took into account "time". You will see how I do this wiht my solution
# when you initially see this problem, you think that you can go left ot right and then change the values
# as you move down, but this is wrong. The reason being is that if you go left from right, you assume
# that the "time" passing first goes from left to right and that the actions don't happen in steps that
# sequentially go together. So, how can we mock this time step?
# the way that you can mock time moving is by using a QUEUE. This will allow you to mimic "passes of time" over
# the array and allow you to take into account the time that things happen. So, when you change an index, you will
# then put that domino that you just changed at the BACK of the queue, so everything infront of it still
# will happen first before that domino is processed.
# we can then create the initial time step by taking one pass over the inital string and filling it with
# the indexes that contain actions. Once we have these indexes, we will process them and then process
# the coressponding domino that needs to be updated. Once we update that new index, we will place that
# new index at the back of the queue to ensure that every action that needs to be processed in the time
# step before it, does get processed.
# we then continue this iteration until thq queue is empty.
# this will give us O(n) time and space because we create the queue and in the worst case will have to update
# every index of the dominos
# remember, this stuff is not easy. Don't get discouraged if you can't solve the problem or if you
# don't get it in the same time complexity. It takes a while to get good at interviewing and I'm not at
# the "master" level that I want to be at either. Just take it one day at a time and one problem at a time
def push_dominos(dominos):
res_dominos = [domino for domino in dominos]
queue = [i for i, domino in enumerate(dominos) if not domino == '.']
while len(queue) > 0: # iterate over the changes
action_i = queue.pop(0)
if res_dominos[action_i] == 'R': # check to see if falling right
attemptPushRight(action_i, res_dominos, queue)
if res_dominos[action_i] == 'L':
attemptPushLeft(action_i, res_dominos, queue)
return ''.join(res_dominos)
def attemptPushRight(action_i, res_dominos, queue):
update_i = action_i + 1
# check to make sure the updated index is within bounds and next is not falling left
if update_i < len(res_dominos) and res_dominos[update_i] is '.': # check to make sure unvisited
if (update_i+1 == len(res_dominos) or res_dominos[update_i+1] is not 'L'):
res_dominos[update_i] = 'R' # update to falling right
queue.append(update_i)
def attemptPushLeft(action_i, res_dominos, queue):
update_i = action_i - 1
if update_i > -1 and res_dominos[update_i] is '.':
if (update_i-1 < 0 or res_dominos[update_i-1] is not 'R'):
res_dominos[update_i] = 'L' # update to falling right
queue.append(update_i)
test = '..R...L..R.'
test2 = '.L.R...LR..L..'
print(push_dominos(test))
print(push_dominos(test2))
<file_sep>/spiraltraverse.py
# Hi, here's your problem today. This problem was recently asked by Amazon:
# You are given a 2D array of integers. Print out the clockwise spiral traversal of the matrix.
# Example:
# grid = [[1, 2, 3, 4, 5],
# [6, 7, 8, 9, 10],
# [11, 12, 13, 14, 15],
# [16, 17, 18, 19, 20]]
# The clockwise spiral traversal of this array is:
# 1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12
# to me, this problem is less hard, and more just implementation.
# It's not really challenging to create 4 for loops and iterate through the matrix
# it's mainly just finding how to end and where to start the various traversals
# Once you understand that you create the four bounds for iteration (these bounds encapsulate the permieter of
# a rectangle that you're iterating over) then you can easily come up with the solution. One thing
# that you can see was a bit tedious was decrementing the nuber of nodes. This is because ints are passed
# by copy so you can't simply just pass it to the function and have it change (unless you encapsulate it in
# an array or something). Either way, I'm sure you can find some convergence to test to make sure
# that you want to keep going or not by seeing if the corners of the square are valid, but I chose to
# do it this way for the sake of time. Make sure you understand why I added the checks to see if there are still nodes to
# visit when I call the methods. Notice that if I didn't do that, then up would produce 8 again for the second
# matrix. Very interesting huh? So this problem may not be so easy after all? I still don't think it's too
# bad and half way through doing this comment I changed the ndoes to visit to an array so I could
# pass it by reference. Cheers. Thanks Amazon for trying to trick me!
def spiral_print(nums):
if not nums or nums is None: return # get rid of bad matrix's
start_row = left_col = 0 # this will be the starting
right_col = len(nums[0]) - 1
end_row = len(nums) - 1
nodes_to_visit = [len(nums) * len(nums[0])]
# continue going as long as there are nodes to visit
while nodes_to_visit[0] > 0:
visit_right(nums, start_row, left_col, right_col, nodes_to_visit)
visit_down(nums, right_col, start_row + 1, end_row, nodes_to_visit)
visit_left(nums, end_row, right_col-1, left_col, nodes_to_visit)
visit_up(nums, left_col, end_row-1, start_row+1, nodes_to_visit)
# update start end left and right (converge them towards the center)
start_row += 1
end_row -=1
left_col += 1
right_col -= 1
def visit_right(matrix, fixed_row, start_col, end_col, nodes_to_visit):
if not nodes_to_visit[0]: return
for col in range(start_col, end_col+1):
print(matrix[fixed_row][col])
nodes_to_visit[0] -= 1
def visit_down(matrix, fixed_col, start_row, end_row, nodes_to_visit):
if not nodes_to_visit[0]: return
for row in range(start_row, end_row+1):
print(matrix[row][fixed_col])
nodes_to_visit[0] -= 1
def visit_left(matrix, fixed_row, start_col, end_col, nodes_to_visit):
if not nodes_to_visit[0]: return
for col in range(start_col, end_col-1, -1): # we need to include the end so we minus one and incrementer is in reverse
print(matrix[fixed_row][col])
nodes_to_visit[0] -= 1
def visit_up(matrix, fixed_col, start_row, end_row, nodes_to_visit):
if not nodes_to_visit[0]: return
for row in range(start_row, end_row-1, -1): # we're going up so we subtract
print(matrix[row][fixed_col])
nodes_to_visit[0] -= 1
test_matrix = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
test_matrix2 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
[13, 14, 15]
]
print('\ntesting on matrix 1')
spiral_print(test_matrix)
print('\ntesting on matrix 2')
spiral_print(test_matrix2)<file_sep>/longestRange.py
# given an array of numbers, return the longest range contained within the numbers
# ex) [1, 10, 8, 15, 0, 5, 12, 14, 16, 2, 4, 3, 11, 13, 9], the longest range here would be [0, 5]
# the most obvious solution is to sort the list and then find the
# longest range using two pointers. This works great, but we're bottlenecked at O(nlogn)
# complexity. Can we do better?
# it just so happens that we can. What if we could access all of the numbers
# immediately, and then iterated from the smallest number until the largest number
# in the array. this would be O(n + k) where k is the distance from the smallest
# number to the largest number. This would also take O(n) space but would
# be much faster than O(nlogn)
import sys
def longest_range(nums):
seen = set(nums)
min_val = min(nums)
max_val = max(nums)
# iterate through the range
rng = [-1, -1]
val = min_val
begin = None
cnt = 0
while val <= max_val:
if val in seen:
if begin is None: begin = val # not in
else: cnt += 1 # increment the range count
else: # not seen
begin = None
cnt = 0
# check if we update the range
if begin is not None: # we found some range
if (cnt+1) > (rng[1] - rng[0]):
rng[0] = begin
rng[1] = begin + cnt
val += 1
# return the range
return rng
test_nums = [1, 10, 8, 0, 5, 2, 4, 3]
test_nums2 = [1, 10, 8, 15, 0, 5, 12, 14, 16, 2, 4, 3, 11, 13, 9]
print(longest_range(test_nums))
print(longest_range(test_nums2))
# lets do even better!
# to do this we will use a map. We will fill all the numnbers into a map and set the value to false
# The false means that we havent' checked over this number before. You will understand why we do this
# and don't just use a set when I explain it. THe first pass we create the map, the second pass we
# move through the array and find the longest range. WHat we do there is start at the number and
# check to see if there are numbers before it and numbers after it that belong in the range.
# when we do this, we check in the map. We want to turn the value to true when we visit that value
# so we don't try to iterate over that range again. The reason I say this is that imagine the input
# was a sorted array that was also filled with consecutive numbers. Then we would check over it n^2 times
# if we didn't store whether we saw that value yet or not. We really don't want to do this. If we've seen
# the value, MOVE ON, Kapeesh. Good. We have the algo let's get it together
def expand_range(num: int, visited_nums: dict) -> int:
curr_range = 1 # just counting the current number
val = num - 1
while val in visited_nums and not visited_nums[val]:
curr_range += 1
visited_nums[val] = True # visit the value
val -= 1
val = num + 1
while val in visited_nums and not visited_nums[val]:
curr_range += 1
visited_nums[val] = True # visit the value
val += 1
return curr_range
def longest_range_fast(nums) -> int:
visited_num = {n : False for n in nums} # create the map
longest_range = 0
for n in nums:
if not visited_num[n]: # check to make sure we haven't visited it
longest_range = max(longest_range, expand_range(n, visited_num))
return longest_range
print(longest_range_fast(test_nums))
print(longest_range_fast(test_nums2))<file_sep>/cutBrickWall.py
# a wall consists of several rows of bricks of various integer lengths and uniform height
# your goal is to find a vertical line going from teh top to the bottom of teh wall that cuts
# through the fewest number of bricks. If the line goes through the edge between two bricks, this does
# not count as a cut
# given an input consisting of brick lengths for each row, return the fewest number of bricks that
# must be cut to create a vertical line
# so I guess I have a step ahead because this chapter in the daily coding problem is on hashtables,
# so I guess I have an understanding of what we need to use. Still, this can be a little tricky so
# bare with me
# Initially, I drew out the problem and tried to understand what we were focusing on. In this problem
# we aren't focusing on the bricks themselves, we're focusing on the ends of the bricks, or
# the vertical lines that they create after you place them. So in my head, I got rid of the bricks
# and decided to focus on the vertical lines that are created. In reality, we're trying to find
# the distance from the start that appears the most times when iterating through each row. I.e.
# the vertical line distance that appears the most when counting the distances in each row.
# If we can get this number, then we know the bricks that we have to cut through because those
# will be equal to # rows - (# rows containing most frequent line). Since we want to keep track of
# numbers and their frequencies, we can think of it as a key value pair, DING DING DING, dictionary time
# Now I choose to use something a little more 'fancy'. I chose to use a counter, since we are counting
# the number of times the vertical line shows up. This means I don't need to worry about checking
# for whether the key is in the counter, I can just add to it and wham, we get the number that we want.
# the last tricky thing that we need to look out for is that we need not count the vertical distance
# at the last brick. Since this will be the most counted line since the wall must end at this line.
# so you only need to iterate through the len(bricks[i])-2 (because -1 would include the last element)\
# once you've counted all of the vertical lines in each row, simply max over the values in
# the counter (or dictionary / hashmap) and then subtract this number from the number of
# rows in the wall, voila, you now have solved the problem!
from collections import Counter
count = Counter() # this will be used to count the number of bricks ending at bick n
def cut_wall(bricks):
for row in bricks:
end = 0
for brick in row[:-1]: # include every brick but the last brick
end += brick # add the length of brick
count[end] += 1 # increment the count of the brick that ends there
return len(bricks) - max(count.values()) # subtract the bricks we don't cut through from the total rows
# test to make sure I'm not a dummy
b = [[3, 5, 1, 1],
[2, 3, 3, 2],
[5, 5],
[4, 4, 2],
[1, 3, 3, 3],
[1, 1, 6, 1, 1]]
print(cut_wall(b))
<file_sep>/README.md
# daily_coding_problems
repository containing my solutions to the daily coding problems sent out by DDaily Coding Problem, HackerRanked, LeetCode, CodeFights, Inteview Cake etc. All of these solutions are in python :snake: to allow me (and you) to focus on the concepts of the problems instead of relying on meeting the syntactical verboseness required for languages like C and C++.
Although I do enjoy coding in those languages, I prefer to interview in python as I use it A LOT for my AI class.
Join me by solving a problem a day to help us all reach interviews with top tech companies! Are you ready? Let's get started!
# What to expect
1. One coding problem to be completed and pushed to this repository everyday
- the problem will directly come from Daily Coding Problem, HackerRanked, LeetCode, CodeFights, Inteview Cake etc
2. Problem definition in comments at the top of the file
3. Detailed explination on various answers that I arrived at (I will try to include my best, as well as brute force solutions)
4. You to increase your coding skills and problem knowledge
<file_sep>/tree.py
class Tree:
def __init__(self, value, right=None, left=None):
self.value = value
self.right = right
self.left = left
<file_sep>/numberWaysToDecode.py
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Facebook.
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded.
For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable. For example, '001' is not allowed.
NOW VALID SOLUTION. FIXED ISSUES
"""
def find_number_of_ways_to_decode(s) -> int:
# base cases
if len(s) == 0: return 0
if len(s) == 1: return 1
if len(s) == 2: return 2
# take the first number off and find the ways to get the rest
total_ways = find_number_of_ways_to_decode(s[1:])
# check to see if we can take two
total_ways += 0 if int(s[:2]) > 26 else find_number_of_ways_to_decode(s[2:])
return total_ways
def find_num_ways_decode_iterative(s) -> int:
# if s empty return 0
if not s: return 0
if len(s) == 1: return 1
# create an array of zeros, storing the computed values so we can build the solution
ways_decode = [0 for i in s]
# base cases
ways_decode[-1] = 1
ways_decode[-2] = 2
# move from the back to the front
for i in reversed(range(len(s)-2)):
ways_decode[i] += ways_decode[i+1]
# check to see if we can split it at 2
ways_decode[i] += 0 if ((i+2) >= len(s)) or int(s[i:i+2]) > 26 else (ways_decode[i+2])
return ways_decode[0]
print('Recursive', find_number_of_ways_to_decode('11111'))
print('Iterative', find_num_ways_decode_iterative('11111'))
print('Recursive', find_number_of_ways_to_decode('111112'))
print('Iterative', find_num_ways_decode_iterative('111112'))
print('Recursive', find_number_of_ways_to_decode('1115112'))
print('Iterative', find_num_ways_decode_iterative('1115112'))
<file_sep>/countingChange.py
# given and infinite number of quarters, dimes, knickles, and pennies; Count the number
# of ways to represent n cents
# this is a classic DP problem. The second you see "count the number of ways.." You want
# to think of DP and/or recursion. When I first saw this problem, I had already done a bunch
# of DP so I decided to start with creating an extra array and defining the relation of
# the ith ways of counting change. So in this "cents" we be building up the solution.
# think about it like this. The number of ways to count 0 cents in change is zero because there
# is one way to count zero cents. Lets say we want to count the number of ways to count 2 cents.
# Lets first try to take a coin from each of our categories and then find the number of ways
# to count i - (coin value) cents. So if I put a penny down, then I would need to find the
# number of ways to count 1 cent. Now lets try to take a quarter and put it down. Well
# this would mean the person would now owe you 23 cents, so this is not good. you could have
# -23 to count from, so just return zero because that is not a viable option. We then continue
# doing this until we get to the nth index and voila, you have the number of ways to count
# n cents.
# so, you're probably asking, can't we just make a recursive solution and call it a day?
# sure, get O(3^n) time complexity and O(n) space for the recursive calls! That doesn't
# sound too good, but if you need to initially start the ball rolling in an interview,
# it will never hurt to give that brute force solution and then try to make it more refined
# it might help you see that the ith cent only relies on calculating how to count the
# i-25, i-10, i-5, and i-1 cent value. Also note, you could speed up the recursive
# brute force solution by using memoization to get the relation.
def count_cents(n):
"""
This function counts the number of ways to make n cents in change
:param n: the cent value
:return: int representing the number of cents in change created
"""
counts = [0] * (n+1) # note we do n+1 to make space for zero
counts[0] = 1 # set the zero'th place to 1
# for every coin
for cent in [1, 5, 10, 20]:
# add increment the number of ways to count i coins by the number of ways to
# count i-cent. Only choose the numbers in the range from that cent forward
for i in range(cent, n + 1):
counts[i] += counts[i-cent]
return counts[n]
# print out the value
print(count_cents(7))
print(count_cents(12))
<file_sep>/paintfill.py
# Implement the "paint fill" function that one might see on many image editing programs.
# Thatis, given a screen (represented by a 2d array of colors), a point, and a new color,
# fill in teh surrounding area until the colro changed from the original color
# okay, well, immediately I am thinking of graph theory when I see this problem
# the reason being is that the section of color that we're changing acts like a graph
# by this I mean that only the color that is connected through up, right, left and down
# movements should be the color that is changed. If we see the color anywhere else
# on the screen, we shouldn't change it because it is not part of the "fill area"
# that we're supposed to be updating. So, we should think of the inital point
# as the starting point in the graph. We then want to expand out from the starting
# point using a DFS (you can also use BFS, but you will have to handle it a bit differently)
# When you expand from teh points, if the new "graph node" contains the color that
# you need to change, you change the color and then expand from that node because
# there could be more pixels that you need to change which are connected to that one
# where does the base case happen? The base case will happen when the color
# at the cell is not the color we're trying to change, or if we're outside of the display
def paint_fill(display, point, color):
"""
Updates the display and fills the surrounding area of that point
from the original color to the new one
:param display: 2D array of colors
:param point: (row, col) tuple
:param color: character
"""
if display is None or len(display) == 0: return # invalid display
og_color = display[point[0]][point[1]] # get's the OG color
pf_help(display, point, color, og_color)
return display
def pf_help(disp, pt, newc, ogc):
"""
fills in the display with the new color using graph theory
:param disp: 2D matrix
:param pt: current point on the display
:param newc: new color to change to
:param ogc: original color
"""
row, col = pt
if row not in range(len(disp)) or col not in range(len(disp[0])): return # invalid point
if not disp[row][col] == ogc: return # not a color that we need to change
disp[row][col] = newc # change the color
for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
pf_help(disp, (row+dr, col+dc), newc, ogc)
# testing display
d = [['W', 'W', 'W', 'B', 'B', 'Y'],
['Y', 'Y', 'Y', 'Y', 'B', 'Y'],
['W', 'W', 'Y', 'Y', 'Y', 'Y'],
['G', 'B', 'G', 'Y', 'Y', 'B'],
['G', 'B', 'R', 'G', 'Y', 'B'],
['G', 'B', 'B', 'G', 'Y', 'B']]
# fill the space with oragane
d = paint_fill(d, (3, 3), 'O')
# reprint the value
for r in d:
print(r)
<file_sep>/KnightOnBoard.py
"""
Hi, here's your problem today. (You've reached the end of the problems for now - in the meanwhile,
here is a random question. And visit CoderPro for more practice!) This problem was recently asked by Google:
A chess board is an 8x8 grid. Given a knight at any position (x, y) and a number of moves k,
we want to figure out after k random moves by a knight, the probability that the knight will still be on the chessboard. Once the knight leaves the board it cannot move again and will be considered off the board.
Here's some starter code:
def is_knight_on_board(x, y, k, cache={}):
# Fill this in.
print is_knight_on_board(0, 0, 1)
THOUGHT PROCESS:
Okay, so immediately when I read this question, I thought of a DFS that has to try all possible combinations of moves.
Since we need the probability that the night will land on the board given some completely random selection of moves
we need to first "experience" all of the moves and account for every possible scenerio that can happen. So, this
is essentially enumerating all move paths that are possible given k moves.
Now to first do this, we can think of this in a recursive nature (because for most this is easier to understand).
First we check to see if the current number move that we're on is greater than k (or if we decrement k, then we
check to see if it's equal to zero). If that is the case, we then check to see if we're on the board or not. We can then
return (1, 0) for 1 on board, zero off, or (0, 1) for 0 on the board and then 1 off. We can then build this solution up
and store the results in a cache, so if we cross paths with another path that has already found the solution for some
spot on the board, we can just utilize the already computed solution instead of redoing the work. This means that will
make at most O(8x8xk) calls or O(k).
We can then also write two helper functions to make the code easier to understand. One of the helper functions
will take the current coordinates of the chess piece and return true/false depending on whether the piece is on
the board or not. The second will take the current coordinates and return all of the possible positions that a night
can land based on the current location (8 different possibilities)
Continue scrolling for iterative solution
"""
def is_knight_on_board(x, y, k, cache={}):
# call the recusive solution
num_on, num_off = _knight_on_board_recursive((x,y), k, cache)
return num_on / (num_off + num_on)
def _knight_on_board_recursive(pos, moves_left, cache):
"""
Returns a touple (num_on, num_off) representing the number of
times the knight was on the board and the number of times
the knight was off the board
"""
# check to see if the current position is in the cache
if cache.get(pos, None): return cache.get(pos)
# check to see if we're out of moves
if moves_left == 0: return (1, 0) if _on_board(pos) else (0, 1)
# check to see if we're off the board
if not _on_board(pos): return (0, 1)
# otherwise, get the on off counters from the current position
curr_on, curr_off = (0, 0)
for new_pos in all_knight_moves(pos):
on, off = _knight_on_board_recursive(new_pos, moves_left-1, cache)
curr_off += off
curr_on += on
# add the probability to the cache and return it
cache[pos] = (curr_on, curr_off)
return cache.get(pos)
def all_knight_moves(pos) -> list:
row, col = pos
new_positions = []
# upward moves
new_positions.append((row-2, col+1))
new_positions.append((row-2, col-1))
# downward moves
new_positions.append((row+2, col+1))
new_positions.append((row+2, col-1))
# rightward moves
new_positions.append((row-1, col+2))
new_positions.append((row+1, col+2))
# lewftward moves
new_positions.append((row-1, col-2))
new_positions.append((row+1, col-2))
return new_positions
def _on_board(pos) -> bool:
"""
Checks to see if the current position is on
an 8x8 board. We assume this will be the range
from 0-7
"""
row, col = pos
if row not in range(0, 8): return False
if col not in range(0, 8): return False
return True
print(is_knight_on_board(0, 0, 1))
"""
Now that we've created a recursive solution. Let's recreate this in an iterative way.
I'm going to use the same functions that we created before, but this time instead
of using recursion, we will mimic it by utilizing a stack. This is essentially
what recursion is doing anyway. Each time a function gets called, it gets added to the
stack. We will just create that stack ourselves and remove the ability for us to
create a stack overflow.
"""
def is_knight_on_board_iterative(x, y, k, cache={}):
pos = (x, y)
stack = [(pos, k)] # (curr_pos_knight, moves_left)
landed_on = 0
landed_off = 0
while stack:
curr_pos, moves_left = stack.pop()
# check if the current position is in cache
if moves_left == 0:
landed_on += 1 if _on_board(curr_pos) else 0
landed_off += 1 if not _on_board(curr_pos) else 0
continue
# not in cache, check to see if we're off the board
if not _on_board(curr_pos):
landed_off += 1
continue
# add all possible positions from our current position
for new_pos in all_knight_moves(curr_pos):
stack.append((new_pos, moves_left - 1))
return landed_on / (landed_on + landed_off)
print(is_knight_on_board_iterative(0, 0, 1))<file_sep>/closestValBST.py
# Given a BST and a target value, return the closest value to the target, that is contained within the bst
# 10
# / \
# 5 15
# / \ / \
# 2 5 13 22
# \
# 14
# Okay, so when I see a BST problem, I immediately think of the fact that I'm given something that is sorted
# for a reason and I need to make a better algorithm as a result of that; and when I say better I mean bigger, faster, stronger (ayye wassup ye)
# So, to utilize the sorting to it's full potential, we should be thinking of how search is done in a BST. When we get
# to a node, we want to move in the direction that will lead us closer to the value that we're searching for
# so, let's say we're searching for 12, we will start at 10, move to the right because 12 > 10, then we will move to the left
# because 12 < 15 and then to the right again because 12 < 13. We're at null, so we should have the answer of the closest
# value by now.
# okay, but hold up hold up. We need something to maintain the closest value. So we will use a variable called closest
# and initalize that to infinity because we want a difference that is unbounded initially. as we move through the tree
# we will check to see if the difference betwee tree.value and target is < closest-target. If it is, then update
# closest to tree.value and then keep moving along. Note, that you want to use abs for the difference incase there are negatives
# That means, if we follow on the correct searching path, we will run into the closest value to our searched value within the tree
# assuming that the tree is balanced,(best case) this will run in O(logn) time and O(1) space, worst case O(n) time O(1) space
# the worst case will happen when the tree looks like a linked list
# note that you can also create this algorithm recursively, but the space will move up to O(logn) for best case and O(n) for worst
# The space comes from the stack frames being created (look into recursion if you don't understand that)
import sys
def findClosestBstValue(root, target):
closest = sys.maxsize
currNode = root
while currNode is not None:
closest = min(currNode.val, closest, key=lambda x: abs(x-target))
if currNode.val == target: break
elif target < currNode.val: currNode = currNode.left
else: currNode = currNode.right
return closest<file_sep>/singleCycle.py
# You are given an array of integers. Each integer represents a jump of its value in the array.
# For instance, the integer 2 represents a jump of 2 indices forward in the array; the integer -3 represents a
# jump of 3 indices backward in the array. If a jump spills past the array's bounds, it wraps over to the other side.
# For instance, a jump of -1 at index 0 brings us to the last index in the array.
# Similarly, a jump of 1 at the last index in the array brings us to index 0.
# Write a function that returns a boolean representing whether the jumps in the array form a single cycle.
# A single cycle occurs if, starting at any index in the array and following the jumps,
# every element is visited exactly once before landing back on the starting index.
# Immediately when I see this problem, I see a directed graph with an adjacency list
# so each node (or element in the array) points to another node in the graph
# that you can move to, from the current node. So, to maneuver to the next index
# you take the index that you're at and whatever is at that index to it and that will take you
# to the next index that you can go to. welll..... I wish that was all it was for this problem.
# you also need to account for the index going out of bounds, and you need to account for negative
# numbers. Rolling around the array is easy, so we will just use mod len(array) to do this (just like a circular queue)
# you will then also need to add the length of the array, to take care of negative value roll over. Few, okay
# now we can move around correctly. So how do we detect a cycle with all of the nodes?
# so by this definiton, if we start anywhere in the graph, we should land back at that node
# and only visit the nodes in the graph exactly once. So don't get tricked with this problem
# and try running this algo for each node in the graph. You only need to prove it for one
# and it inductively proves the rest. So, for this problem, well start at the zero index
# and then hopefully land back in the zeroth index.
# what happens if there is a cycle that doens't land back at zero? This means that we
# need to keep track if nodes within the graph have already been visited. To do this
# I utilize the graph given and set that nodes next value to None. This means we've already
# been there at that node. Lasltly, how do we know when to stop? We stop when the next value
# is none (or already visited) or if the next value is zero and zero has already been visited
# This will allow us to differentiate between a cycle and a single cycle
# To decide what to return, we check to see that all nodes in the graph are visited
# and if the nextNode is zero. If either of these are not true, return False, otherwise True
# O(n) time and O(1) space
def hasSingleCycle(array):
nxtNode = 0 # start at the zero index
while nxtNode is not None:
if nxtNode == 0 and array[0] == None: break # made it back to start
temp = array[nxtNode]
array[nxtNode] = None # mark as visited
nxtNode = (nxtNode + temp + len(array)) % len(array) if temp is not None else None
# check to make sure all visited and nxtNode is 0
return False if any(array) or not nxtNode == 0 else True<file_sep>/validateParen.py
# Good morning! Here's your coding interview problem for today.
# This problem was asked by Google.
# Given a string of parentheses, write a function to compute the minimum number of parentheses to be removed to make the string valid
# (i.e. each open parenthesis is eventually closed).
# For example, given the string "()())()", you should return 1. Given the string ")(",
# you should return 2, since we must remove all of them.
# immediately when I see a problem involving parentheses. I IMMEDIATELY THINK OF USING A STACK.
# the reason for this is that we want to focus on the last thing placed into the stack which is
# the most recent parenthese. This will allow us to make open and closing pairs.
# what we will do here is start with a stack and add to the stack when there is an opening
# parentheses. If it's a closing paren, we will check to see if the length of the stack is > 1
# if it is pop of the end of the stack. If the length of the stack is == 0, then we add one to removed
# because that closing paren cannot be there. Okay, great that's O(n) space and time. Let's do better
# if you noticed we used the stack, but really didn't care about what was in there, we only cared about
# the length because we solely put one type of paren into it. So, we could exchange the stack for an int called open
# we will then use this as the "stack" and increment it when we see open parens and decrement when we see closing ones
# (assuming it's greater than 0)
# lastly, what if the string contained only opening paren? How would we handle this. Well, after we go through
# all of the parentheses, we will then add the number of remaining open paren to the removed value. This is because
# we will need to remove all of these to make the string valid! Great O(n) time and O(1) space!!!! LETSS GOOOOO
def min_removed(parens):
"""
returns the number of parentheses that need to be removed to make a valid string
return: int representing removed paren
"""
remove = open_paren = 0
for paren in parens:
if paren == '(':
open_paren += 1
else:
if open_paren > 0: open_paren -= 1
else: remove += 1
return remove + open_paren
# tests to make sure it works!
print('((((: removed', min_removed('(((('))
print(')(: removed', min_removed(')('))
print('(()))((: removed', min_removed('(()))(('))
print('()())(): removed', min_removed('()())()'))<file_sep>/invertBinaryTree.py
# This is one of the most infamous problems that I have done in a long time, and this
# is because the creator of Homebrew was not able to do this problem... so Google dropped him
# NOW, almost every software person at Google uses his software. So, if you aren't able
# to do a couple leet code problems, don't freak out. It's not the end of the world and we ALL
# struggle with different problems and question types
# okay, so the problem is probably pretty obvious, invert a Binary tree. But what does that even mean?
# Invert a binary tree.
#Example:
#Input:
# 4
# / \
# 2 7
# / \ / \
#1 3 6 9
#Output:
# 4
# / \
# 7 2
# / \ / \
#9 6 3 1
# so, pretty much when you look at the problem, given a root node, you want to swap the
# right and left children. Then recursively keep doing that down the tree.
# let's first loook at the base case. So the base case would be if the root is null, so we just want to
# return null at that point
# so if you've ever done a problem that involves swapping numbers you know you want to use a temp variable
# to store the values and then move on from there to the next set. Here we will swap the right and left
# children and then tell the children to do the same thing for their children. We keep doing this down
# the tree and you keep going until you get to null, and then you work your way back up the tree!
# finally, you return the root node. Ez pz.
def invertTree(root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root is None: return root
swap_children(root)
# invert the children
invertTree(root.right)
invertTree(root.left)
return root
# iterative solution
def invertBinaryTree(tree):
queue = [tree]
while len(queue) > 0:
node = queue.pop() # get the first node
if node is not None:
swap_children(node)
queue.append(node.left)
queue.append(node.right)
return tree
def swap_children(node):
temp = node.right
node.right = node.left
node.left = temp<file_sep>/shiftingLetters.py
# We have a string S of lowercase letters, and an integer array shifts.
# Call the shift of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').
# For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.
# Now for each shifts[i] = x, we want to shift the first i+1 letters of S, x times.
# Return the final string after all such shifts to S are applied.
# Input: S = "abc", shifts = [3,5,9]
# Output: "rpl"
# Although this problem may seem a bit daunting, it is really just a mix of core CS
# concepts that are smushed together to make a medium diff problem
# In my opinion, the key to this problem is realizing that the sum of the shifts
# from i to the end of the list, is the number of shifts applied to that specific
# index within the string. So, we can sum the list of numbers, apply that shift to
# the first letter, then subtract the number at i in shifts from the sum and apply
# that shift to the next number. The last key aspect of this question is that you
# need to understand the "wrap around". Whenever you hear wrap around, think of
# the MOD function immediately. Since there are 26 letters in the alphabet, if
# we treat z as 25, then z + 1 mod % 26 will give us 0 which will be 'a'. We will
# then add this number to ord('a') which will act as the base to be incremented on
# and then add this character to a list of characters. We don't want to keep recreating
# new strings because they're immutable and will load up in memory. Return the joining
# of all of the character as a string and you have the final result.
class Solution(object):
def shiftingLetters(self, S, shifts):
"""
:type S: str
:type shifts: List[int]
:rtype: str
"""
# create a list so we aren't creating a bunch of strings in mem
newS = []
shift = sum(shifts) # sum all of the shifts
for i, c in enumerate(S):
newS.append(chr(((ord(c)-ord('a') + shift) % 26) + ord('a')))
shift -= shifts[i]
return "".join(newS)<file_sep>/cycleLL.py
# Given a linked list, determine if it has a cycle in it.
#
# To represent a cycle in the given linked list,
# we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to.
# If pos is -1, then there is no cycle in the linked list.
# This might be one of the weirdest cycle problems that I've ever seen. Most cycle problems, you
# can run something like a fast slow and if they ever meet than you know you have a cycle,
# you could also do the HashSet where you hash the actual node itself and not just the value
# so when you see that object again, you know you have a cycle in the LL
# The thin that threw me off was the position, I still really don't understand it so I just put a flag
# to check if that position was correct or not. I then just compared to see if I have seen that object
# or not using a set. Sets are implemented using hashing so this allows for theoretical O(1) lookup
# (depending on the collisions and resolution). If we see that current node in the set, then
# we know there is a cycle; return False. Otherwise, if head turns into None, return True. Super easy,
# but a very common problem!
def hasCycle(head, pos):
"""
:type head: ListNode
:type pos: int
:rtype: bool
"""
if pos == -1: return False
seen = set()
while head is not None:
if head in seen:
return False
else:
seen.add(head)
head = head.next
return True
<file_sep>/palindromeNumber.py
"""
Write a program that checks whether an integer is a palindrome.
For example, 121 is a palindrome, as well as 888. 678 is not a palindrome.
Do not convert the integer into a string.
So, for this problem, we will convert the number an array by moding the first
digit off, and then placing it in an array and then dividing by 10 to shift
the rest of the digits down. Once the number is equal to zero, then we will
run a palindrome check on the array of digits
This will run in O(log_10(n)) where n represents the number passed in
This space will also be O(log_10(n)) or O(d) where d represents the number
of digits in the number, n
"""
def palindrome_number(n) -> bool:
digits = []
# create the array of digits
while n:
digit = n % 10
digits.append(digit)
n //= 10 # integer divide
# check to see if palindrome
left = 0
right = len(digits) - 1
palindrome = True
while left < right:
# check to see if the digits are the same
if digits[left] != digits[right]:
palindrome = False
# move the pointers
left += 1
right -= 1
return palindrome
# run tests
print("678", palindrome_number(678))
print("6786", palindrome_number(6786))
print("8", palindrome_number(8))
print("89998", palindrome_number(89998))
<file_sep>/bitmath.cpp
/* Good morning! Here's your coding interview problem for today.
# This problem was asked by Facebook.
# Given three 32-bit integers x, y, and b,
# return x if b is 1 and y if b is 0,
# using only mathematical or bit operations. You can assume b can only be 1 or 0.
*/
#include <cstdint>
#include <iostream>
/*
Okay, so this problem definitely is more suited towards programmers that have a more "formal"
CS degree. One that involves a little more low level programming and systems courses.
It is not very hard per say, but the concepts are something that you will learn in one of these courses
and I totally would've not known how to do this without my comparch class. Also, note that I chose
to use C++ for this problem because I perfer to do low level problems in non-python programming languages
Anyways, so the key to this problem is understanding bit-shifts and masks, and really you follow
The same procedure for botth the maskings. What I am doing is taking b and then shifting it to the
right 31 bits, this will then fill the number with trailing zeros and place the LSB in the MSB slot.
I then take the MSB and shift that down 31 bits so the number is now filled with all ones or all zeros.
The key is that left shifting will not carry the LSB where right shifting will carry the MSB. So, we can
then and this new "mask" with x and with y, so we can either "adopt" that value if our mask is 0xffff or
we will discard it because our mask is all zeros.
Notice the one difference between the x checek and the y check. For the y check, I first negate the
value. This is because when we shift down and back with b being 0, we want the mask to be all 1's.
The only way to do this is to start with a 1 in the LSB. This will then also turn 1 into zero which
creates the all zero mask that we wanted as well.
Lastly, we or the two checks so we get the proper integer to return. This my friends, is how you
make a "proper" ternary function!
*/
int32_t bitmath(int32_t x, int32_t y, int32_t b){
int32_t xcheck = ((b << 31) >> 31) & x; // this will be all zeros if it was 0, and all 1's otherwise, then and with x
int32_t ycheck = ((!b << 31) >> 31) & y;
return ycheck | xcheck;
}
int main(){
std::cout << "Test b is 1: ";
std::cout << bitmath(3, 10, 1) << std::endl;
std::cout << "Test b is 0: ";
std::cout << bitmath(3, 10, 0) << std::endl;
}
<file_sep>/KcoloredGraph.py
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given an undirected graph represented as an adjacency matrix and an integer k,
write a function to determine whether each vertex in the graph can be colored
such that no two adjacent vertices share the same color using at most k colors.
O(n) space where n is the number of nodes in the graph
O(n*n*k) time beacuse at every node you at the worst go through every value and check every dependency edge
To me, this problem is VERY similar to the N queens problem. Essentially, what we're trying to do, is go
through the graph, select a node, assign it a value, then try to move through the graph all the way
until there is no more nodes to assign a value, and all the nodes have been assigned a value that is
valid.
My thought process is that, in the worst case, we need to try all combinations of colorings in the graph.
Now, technically we could just assign random colors, then keep flipping the ones that aren't valid
until they become valid and then call it a day. This really doesn't sound like to great of an idea to me,
but its a decent start none the less.
Hmm. Okay, so let's try to break the problem down. Let's assume we're at a node in the graph. We don't really
care about how we got there, but we want to asssign this node a color. Now, we know that the only valid
colors are the colorst that are in the domain of colors, D, which are not in the set of colors S, which
represent the set of colors for nodes that are already colored which are connected to our current node
with an edge. You might have to read through that another time to make sure you fully understand what im
trying to say because that is a mouth full. We can then take our current node, assign it a color that is in
the set of valid colors, given the current graph orientation of color assignments, and then move onto the
next node in the graph, and continue this pattern until we get to a point where the set of valid colors is
empty and we still have a node that is in need of assignment, or until we've assigned all the nodes a valid
color and have completed our job!
Now, how do we move to the next node? Well, since we're given the graph in a matrix, I find it easiest to think
of the node as simply the index we're currentl at. So index 0, would be the first node, and when we ask the
graph for the edges from index zero to other nodes all we need to do is graph[node] and this will return an
array of length n filled with 0's and 1's. The index that we're at in that array represents a node within the
graph and if there is a 1 as the value at that index, then that means that there is a connection between our
current node and the other node in the graph. If there is a zero, then there is no connection to that node and thus
no constraint between our node and that node.
Now that we know how to traverse the graph, let's write a backtracking algorithm to solve this problem for us.
First, we will start at node 0. Then we will assign it a node in the domain of valid colors, and then move onto
node 1 and check to see if there is a valid color that can be assigned given our current coloring orientation.
If there is, great, assign it that value and move onto node 2. We keep this process going until our node index
is greater than the length of the graph. This means that we've successfully colored the whole graph in a valid
orientation. If we run into a situation where we can't add a valid color with our current orientation, then
we backtrack and have the previous node try a different color. And this backtracking continues until we satisfy
the constraints again.
Great! Let's write the code. Note that in the code below, I was speed coding and I chose to check the range
of all colors and then check to see if it's valid. Another perfectly fine solution would be to create a function
called, valid_colorings and then have it return a list of valid colorings instead of also checking to see if it's
valid in the if statement, in fact, im going to do that right
"""
def k_coloring(graph, k):
values = [None] * len(graph) # array containing the value within the domain of k
return solve_csp_2(0, values, graph, k)
def solve_csp(curr_node, node_values, graph, k):
# check to see if the current node is greater than the length of the grapp
# then return true because we've assigned values that align with constraints
# and have no more nodes to check. Also a graph with no nodes in it can be valid with any k of colors
if curr_node >= len(graph): return True
# pick a value, check to see if valid, if valid move to next node otherwise, try agian
next_node = curr_node + 1
for value in range(k):
node_values[curr_node] = value
# check to see if the current node coloring is valid, then check to see if we can create a valid coloring
if valid_constraints(curr_node, graph, node_values) and solve_csp(next_node, node_values, graph, k):
return True
# not valid or not a valid selection, backtrack and try a new value
# did not find a valid coloring for the current orientation return false
return False
def solve_csp_2(curr_node, node_values, graph, k):
# check to see if the current node is greater than the length of the grapp
# then return true because we've assigned values that align with constraints
# and have no more nodes to check. Also a graph with no nodes in it can be valid with any k of colors
if curr_node >= len(graph): return True
# pick a value, check to see if valid, if valid move to next node otherwise, try agian
next_node = curr_node + 1
for value in valid_colorings(curr_node, graph, node_values, k):
node_values[curr_node] = value
# check to see if we can construct a valid coloring with the given orientation
if solve_csp_2(next_node, node_values, graph, k): return True
# not valid or not a valid selection, backtrack and try a new value
# did not find a valid coloring for the current orientation return false
return False
def valid_colorings(curr_node, graph, node_values, k) -> list:
colors = set([color for color in range(k)])
node_edges = graph[curr_node]
for node, has_edge in enumerate(node_edges):
node_color = node_values[node]
if has_edge and node_color in colors:
colors.remove(node_color)
return list(colors)
def valid_constraints(curr_node, graph, node_values) -> bool:
node_edges = graph[curr_node]
for node, has_edge in enumerate(node_edges):
# check to see if there is a connection that also has the same value
if has_edge and (node_values[node] == node_values[curr_node]):
return False
# return true if there is a connection without the same value
return True
test_graph = [
[0, 1, 1, 1],
[1, 0, 1, 0],
[1, 1, 0, 0],
[1, 0, 0 ,0]
]
test_graph_2 = [
[0, 1, 1],
[1, 0, 0],
[1, 0, 0]
]
print(k_coloring(test_graph, 3)) # this should be true because you should be able to color anything with three colors
print(k_coloring(test_graph, 2)) # this is false because you get stuck with the dependency at assigning to the node 2
print(k_coloring(test_graph_2, 2)) # this is true, set 0 to value 0 and then node 1 and 2 to value 1<file_sep>/facebookQuxes.py
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Facebook.
On a mysterious island there are creatures known as Quxes which come in three colors:
red, green, and blue. One power of the Qux is that if two of them are standing next to each other,
they can transform into a single creature of the third color.
Given N Quxes standing in a line, determine the smallest number of them remaining after any possible sequence of such transformations.
This looks like a classic recursion problem to me. You need to try all of the different combinations if possible
to be able to determine the min number of possible qux on the island. To do this, we will choose to either pair
them or we will not pair them. But we can only pair them if they're not next to someone of the same color as them
We then keep moving down with a swap index, and return the size of the array at the end. We can then take the min
as we go back up the recursion tree to then get the minimum number possible.
It is important to note that a transformation, you need to go one back becuase this could potentially cause
the index before to now swap with the newly transformed, so you can see that I take the max of 0 and i-1
to ensure that we never create a negative index
"""
def determineMinimumQux(quxes: list) -> int:
return recusiveSwaps(0, quxes)
def recusiveSwaps(i: int, arr: list) -> int:
# check to see if swap index is greater or equal to arr length
if i >= len(arr): return len(arr)
# choice of not transforming
minQuxes = recusiveSwaps(i+1, arr)
# Choice of transforming (must be a valid transform)
if validTransformationIndex(i, arr):
transformmedColor = transform(arr[i], arr[i+1])
newArr = arr[:i] + [transformmedColor] + arr[i+2:]
minQuxes = min(minQuxes, recusiveSwaps(max(i-1, 0), newArr))
return minQuxes
def validTransformationIndex(i, arr):
hasNext = (i+1) < len(arr)
return hasNext and (arr[i] is not arr[i+1])
def transform(color1, color2) -> str:
colorSet = set([color1, color2])
if colorSet == set(["R", "B"]): return "G"
if colorSet == set(["R", "G"]): return "B"
return "R"
# can only turn into two
testQuxesTwo = ['R', 'B', 'G']
# should be 1
testQuxes = ['R', 'G', 'B', 'G', 'B']
print(determineMinimumQux(testQuxes))
print(determineMinimumQux(testQuxesTwo))<file_sep>/champagne.py
# consider a pyramid of champagne glasses where the the 1st row has 1 glass
# the second row has two glasses, the third row has three, and so on.
# we pour a certain amount of champagne into the top glass, and that glass
# fills and pours equally into the left and right glasses of that glass.
# Note that if 2 glasses are poured into one glass, 0.5 of a glass will fall to the left
# and 0.5 will fall to the right.
# given a row for the glass, and the glass number in that row, return the
# amount of champagne that is in that glass
# assume that if we're at the bottom row it still spills over
# note that the values given are 0 indexed. So the zero'th row will have 1 glass
# so when I saw this problem, I realized that we want to overflwo to the row
# below us and the row below us and the column to the left. The reason I saw
# this is I started drawing out a tree, and drew the arrow that created the pour
# direction. If we follow the arrows, we see that the (row-1, col) pours into
# the glass at (row, col) and the (row-1, col-1) pour into that glass as well
# I then thought of building the solution with a matrix and going row by row
# all the way through the row that we're searchig for.; We then return the
# value at the matrix location query_row, query_col. This is like a DP
# build up problem. Very nice, O(n^2) time and O(n^2) space
# query_row is the row that the glass is in
# query_glass is the col that the glass is in
def find_champagne_glass(poured, query_row, query_glass):
pyramid = [[0 for _ in range(i+1) ] for i in range(query_row+1)] # create a "pyramid" matrix, because the row determines it
pyramid[0][0] = poured
# build pyramid down until row, col
for row in range(len(pyramid)):
for col in range(row + 1):
# subtract one cup and move overflow to the left and right cups
overflow = pyramid[row][col]-1 if pyramid[row][col]-1 > 0 else 0
pyramid[row][col] -= overflow # update to the correct amount left in glass
if row + 1 < len(pyramid):
pyramid[row+1][col] += (overflow * 1.0) / 2
if row + 1 < len(pyramid) and col + 1 < len(pyramid):
pyramid[row + 1][col +1] += (overflow * 1.0) / 2
# query the row and glass
return pyramid[query_row][query_glass]
# testing
print(find_champagne_glass(2, 1, 1))
print(find_champagne_glass(5, 2, 1))
print(find_champagne_glass(10, 1, 1))<file_sep>/countUniValTree.py
# count the number of unival trees
# these are trees where nodes under it have the same value
# the key to this problem is to think of this recursion from the bottom up
# if you don't and you check from the top down, you will be evaluating
# every subtree multiple times. Instead, we can think of this from the bottom
# up and check if the bottom is a uni tree, and then bump up to the next level
# and check to see if that is a universal tree. The parent of the two nodes
# will only be a universal tree if the two nodes below it are universal trees
# so we can make the check at the solely below it because we've already checked
# everything below those two children (so we've inductively proven it already).
# lastly, we need to think of the null case. When we reach null, we want to
# not count a uni tree, but we want to give the parent of the null ptr to still
# have the opportunity to be a uni tree (you will see why this is important)
# so, if we think of this first, we cannot decide whether a node is a uni
# tree based on the number of uni trees below it. Maybe the child of the parent
# wasnt a uni tree, but there were 100's of uni trees below that child. Although
# there might have been 100's of uni trees, we cannot determine that this parent
# is a unitree or not. Instead, we must also pass back a value with the total
# number of uni trees. To do this, we will pass back a boolean value that will
# represent whether this node was a uni tree. We can then make the decision at the
# parent of whether this one was a unitree or not based on the boolean
# and checking to see if the numbers match. This will run in O(n) time and
# will take extra space since we're adding to the stack for each call O(logn) assuming
# the tree is balanced, and O(n) extra space if there is no balance constraint.
def unival(root):
num, _ = unival_help(root)
return num
def unival_help(root):
if root is None: return 0, True # check the base case
total = 0 # total number of uni trees
uni = True # represent whether current parent is a uni tree
if root.left: # check the left
ltotal, luni = unival_help(root.left)
uni = (luni and uni) and (root.val == root.left.val) # check to see if still valid
total += ltotal
if root.right: # check the right
rtotal, runi = unival_help(root.left)
uni = (runi and uni) and (root.val == root.right.val) # check to see if still valid
total += rtotal
return total + 1 if uni else total, uni
<file_sep>/problem6.py
# This problem was asked by Facebook.
# Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded.
# For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
# You can assume that the messages are decodable. For example, '001' is not allowed.
# The key to this problem is to understand that for each number, we can either count
# just the singular number, or we can check to see if that number and the next one
# add up to <= 26 and then move the count by an increment of 2. The best way for me
# to think about this was looking at the problem from a tree standpoint. If you think
# of the problem as counting from each index, than we can do some pruning to the
# tree by using dynamic programming by storing intermediate values
# ex) for the string '111', we can think of the tree as storing the index of the current
# character that we will be looking at for counting. So from the first index, we can either
# go to index 1, or we can go to index 2 (going to index 1 means we only read the first 1,
# and going to index 2 means that we read the first 2, and their int representation was
# <= 26 so it's a valid path). We can continue doing this splitting until we get to
# an index that is equal to the length of the string, once we get here we return 1 because
# this represents 1 path that we could count. we then backtrack up and continue on with the
# next path. To make the algo more time efficient, we can use an array to keep track
# of the calculated counts from an index. Thus, once we reach that index again, we no longer
# have to recalculate all of the possibilities
#
# ` 0
# 1 2
# 2 3 3
# 3
#
#
def decode(str):
"""takes an encodes string returns the number of ways to decode it
str: str"""
return decode_help(str, [-1] * len(str), 0)
def decode_help(msg, arr, i):
"""This function will decode a str given the string of numbers
arr will be used for dynamic programming so we don't have to calculate
values from the same index multiple times
msg: str - contains the encoded message
arr: list - list of calculated values
i: int - integer representing the index of the string we're at"""
if i == len(msg): return 1 # this is one way to count
if not arr[i] == -1: return arr[i] # we've already calculated the value
# count the number of ways from i
count_i = 0
count_i += decode_help(msg, arr, i + 1)
if i+1 < len(msg) and int(msg[i:i+2]) <= 26:
count_i += decode_help(msg, arr, i+2)
# update the array and return the number of counts
arr[i] = count_i
return arr[i]
# run tests on the program
msg1 = '111'
msg2 = '11234'
msg3 = '27'
msg4 = ''
print (decode(msg1))
print (decode(msg2))
print (decode(msg3))
print (decode(msg4)) # there is only one way to decode an empty message
<file_sep>/removeLLDuplicates.py
"""
Hi, here's your problem today. This problem was recently asked by Twitter:
Given a linked list, remove all duplicate values from the linked list.
For instance, given 1 -> 2 -> 3 -> 3 -> 4, then we wish to return the linked list 1 -> 2 -> 4.
Essentially what we do here is run though the list, get a set of the duplicate
elements within the list, so when we pass through it a second time, we see if that
current value is a duplicate, if so, then we remove it from the list. So we make two
passes, one to get the duplicates, and one to remove the duplicates from the list
O(n) time and space
"""
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def __str__(self):
if not self.next:
return str(self.val)
return str(self.val) + " " + str(self.next)
def remove_duplicate_nodes(head:Node):
duplicates = get_duplicates(head)
prev = None
curr = head
# while there are more nodes to process
while curr is not None:
# check to see if curr is in seen
if curr.val in duplicates:
# remove curr from the list
prev.next = curr.next
curr = curr.next
else:
prev = curr
curr = curr.next
def get_duplicates(head:Node) -> set:
seen = set()
has_duplicates = set()
curr = head
while curr is not None:
# check to see if it's in seen
if curr.val not in seen:
seen.add(curr.val)
else:
has_duplicates.add(curr.val)
curr = curr.next
return has_duplicates
n = Node(1, Node(2, Node(3, Node(3, Node(4)))))
n2 = Node(1, Node(2, Node(3, Node(3, Node(4, Node(2))))))
# 1 2 3 3 4
print("List 1 before:",n)
remove_duplicate_nodes(n)
print(n)
print("List 2 before:", n2)
remove_duplicate_nodes(n2)
print(n2)
<file_sep>/kdistinct.py
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb".
I have no idea why this problem is considered hard? Maybe it's all perspective and maybe I could just be wrong
The way I see this is we use a fast and slow pointer, and then move down the string and keep a set of characters.
Once the set is at size k, then we can add no new characters and are forced to remove from the left side. The only
issue with using a set though, is that we don't know the number of times that the character is within that
substring, so maybe using a map that will contain the count of the characters within that substring and then use
an int to count the current number of characters within that substring. And then that will allow us to check
the number of characters. I guess you could also use the length of the numebr of keys, since there are only guarunteed
26 keys, that is technically O(1), but im not too sure how that implementation is done within the dictionary DS in python
I guess, we will just use that and then call it a day from there. Let's do it
"""
from collections import defaultdict
def longest_substring_k_distinct(s, k) -> int:
"""
We pass over each of the characters in the string 2 times in the worst case, so
the time complexity is O(n), we use a counter for the characters in the string,
since there are only 26 characters in the alphabet, we use O(1) space because
the character size does not depend on the input. TADA! We killed it!
"""
if not s: return 0
# max length
max_lenth = 1
# create a counter and set the first character count to 1
counts = defaultdict(int) # set the first character to a count of 1
counts[s[0]] += 1
num_characters = 1
# create fast and slow pointers
# assume that the left pointer shows what is currently contained and the next index of the right pointer is what is in question
slow = fast = 0
while slow < len(s) and fast + 1 < len(s):
# get the next character
next_char = s[fast+1]
# if the number of characters is less than k, then add that character to the set
if num_characters < k:
num_characters += 1 if counts[next_char] is 0 else 0 # add to the num of characters if that character is not in the set
counts[next_char] += 1 # update the counter
fast += 1 # move the fast pointer
elif counts[next_char] is 0: # k is at max capacity and the next character is not in the current seen set
# move the slow forward and remove the character from the count
counts[s[slow]] -= 1
# if there are no more of the characters in the seen set, remove it then move up the slow
num_characters -= 1 if counts[s[slow]] is 0 else 0
slow += 1
else: # the current character is in the seen set and k is equal to max character
# add the count and move the fast forward
counts[next_char] += 1
fast += 1
# get the max length
max_lenth = max(max_lenth, (fast + 1 - slow))
return max_lenth
# testing
s1 = "abcba"
print("Test1 {s}:".format(s=s1), longest_substring_k_distinct(s1, 2))
s2 = "abcbbbca"
print("Test1 {s}:".format(s=s2), longest_substring_k_distinct(s2, 2))
s3 = "abcbzzzbbca"
print("Test1 {s}:".format(s=s3), longest_substring_k_distinct(s3, 2))
s4 = "abcbzzcczbbca"
print("Test1 {s}:".format(s=s4), longest_substring_k_distinct(s4, 3))
<file_sep>/problem2.py
# given a list of numbers (in sorted order) determine the number that is missing from the list
# only one number will be missing and the range of the numebrs will be filled besides that
# numbers will go from 1-100
numbers = [x+1 for x in range(100)] # creates a list of 1-100
missing3 = [x for x in numbers if not x == 3] # missing 3
missing59 = [x for x in numbers if not x == 59] # missing 59
missing100 = [x for x in numbers if not x == 100]
missing1 = [x for x in numbers if not x == 1]
def detect_missing_num(nums):
"""given a list of numbers, return the number that is missing from the list
nums - list of numbers with range from 1-100, missing one number
Goal: brute for solution is to run through the indexe one by one and
check to see when index+1 does not equal the current number
O(n)
A faster solution is to treat it like a binary search and
split the numbers in half. If the current index+1 equals the
number at that index, then we know everything to the left of that
index is correct. If the current index + 2 is equal to the number there
then we know something is missing to the left. Treat it as a binary search
and split the data again until the right is less than the left. Once the right
is less than the left, we know left is at the index where the number is missing
Return left + 1"""
left = 0
right = len(nums) - 1 # gives the rightmost index
while left <= right:
mid = (left + right) / 2 # calculate the mid index
m_num = nums[mid]
if m_num == mid+2: # something is missing to the left of this number
right = mid - 1
else: # we know something is missing to the right
left = mid + 1 # everything to the left is correct
# left will now equal the index where the number is missing
# add one to the index to get the number
return left + 1
# check to make sure the solution is working on all cases, including numbers at the ends
print detect_missing_num(missing59)
print detect_missing_num(missing3)
print detect_missing_num(missing100)
print detect_missing_num(missing1)
<file_sep>/distance.py
import re
comma_delimeter = r'\s*\,\s*'
axis_coordinate = r'(\-?\d+)'
def kth_closest_pair():
input_points = input("Enter three dimensional points as (x, y, z): ")
pattern = re.compile(r'{p}{c}{p}{c}{p}'.format(c=comma_delimeter, p=axis_coordinate))
# finds all points and converts the string into an int
try:
points = [(int(p[0]), int(p[1]), int(p[2])) for p in pattern.findall(input_points)]
except:
print("error parsing input.")
exit(1)
print("\n", points)
def find_all_numbers():
# create regex and then compile it into a regex object
regex = r'[+-]?\d+'
pattern = re.compile(regex)
# ask for an input from the user
input_str = input("Enter a string with numbers: ")
# find all numbers within the string using the regex
print("\nALL NUMBERS WITHIN THE STRING:")
for num in pattern.findall(input_str):
print(num)
kth_closest_pair()<file_sep>/reverseLL.py
# This is one of the more classic interview problems that I've seen
# Not only have I seen this in various interviews, but it's come up in
# some of my data structures class. I feel like this is one of those
# early right of passage problems. It's not hard, but it can be tough to wrap
# your head around. Even if you've done this problem before, you really need
# to think about what you're doing or else you can get caught up in this
# Null trap. Don't do that!
# the main topic for this problem is RUNNERS. So what is a runner,
# A runner is a pointer that moves down the list ahead of others.
# this will then help you solve linked list problems in O(n) time
# instead of O(n^2). So whenever you get to a LL problem and it involves
# moving nodes around, think about using runners. Most of the time, it will
# require 3 pointers with LL problems (two to do the work and then one
# to keep track of the work) but it's all problem specific so take
# that with a grain of salt.
# okay, first things first, let's think about what's happening here
# at a simple case (IE, in the middle of the list)
# we want to get the current node to point to the previous node.
# so we can do that by just moving the current nodes next to previous
# and we're done right? WRONG. If you do that you will lose track of the
# rest of the list. You need to also keep track of a next runner
# that will maintain the next node for curr to go to after you
# have "rotated" curr to point to the one before it.
# lastly, it helps me to think as if there was another LL called
# reveresed, and we will append to the front of this LL
# so we're indirectly reversing it. Thinking of it as previous
# trips me up, but if that's what is best for you then do that!
from Node import Node
def reverse_LL(head):
curr = None # start curr one behind next
rev = None # start rev at None incase there is no nodes
nxt = head # start nxt at the front, we will assume we move to next immediately
while nxt:
curr = nxt # go to the current one
nxt = nxt.next # move it down
curr.next = rev # reverse it
rev = curr # get rev to point to the new front
return rev
# build the list backwards
a = Node('a')
b = Node('b', a)
c = Node('c', b)
r = reverse_LL(c)
while r:
print(r.data)
r = r.next
<file_sep>/inorderpreorder.py
from tree import Tree # used for tree nodes
def pre_and_inorder_build(preorder: list, inorder: list) -> Tree:
if not preorder and not inorder: return None # check to see when there are no roots left
if len(preorder) == 1 and len(inorder) == 1: return preorder[0]
root = Tree(preorder[0]) # get the value from it
i = inorder.index(root) # get the index within inorder that val is at, this will split the list
root.left = pre_and_inorder_build(preorder[1:1+i], inorder[0:i]) # ()
root.right = pre_and_inorder_build(preorder[1+i:], inorder[i+1:]) # (i+1-end of list)
<file_sep>/smallestDifferrennce.py
# given two non empty arrays, THe function should find the pair of numbers (one from the first array and second array) whose absolute difference
# is the closest to zero and return them as an array. First index from first array, second from second array
# This solution runs in O(mlogm + nlogm) time and O(1) space
# will complete explination tomorrow
from bisect import bisect_right
import sys
def smallestDifference(arrayOne, arrayTwo):
arrayTwo.sort() # mlogm
arr = None
diff = sys.maxsize
for num in arrayOne: #nlogm
i = bisect_right(arrayTwo, num) # find index to insert
for di in [-1, 0]: # check current index and left one
inRange = i+di in range(0, len(arrayTwo))
if inRange and abs(num - arrayTwo[i+di]) < diff:
arr = [num, arrayTwo[i+di]]
diff = abs(num - arrayTwo[i+di])
return arr<file_sep>/bottomViewTree.py
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Yelp.
The horizontal distance of a binary tree node describes how far left or right the node will be when the tree is printed out.
More rigorously, we can define it as follows:
The horizontal distance of the root is 0.
The horizontal distance of a left child is hd(parent) - 1.
The horizontal distance of a right child is hd(parent) + 1.
For example, for the following tree, hd(1) = -2, and hd(6) = 0.
5
/ \
3 7
/ \ / \
1 4 6 9
/ /
0 8
The bottom view of a tree, then, consists of the lowest node at each horizontal distance.
If there are two nodes at the same depth and horizontal distance, either is acceptable.
For this tree, for example, the bottom view could be [0, 1, 3, 6, 8, 9].
Given the root to a binary tree, return its bottom view.
Here's my logic, we want to go through the tree in a level order, and then keep a dictionary
that will have the key be the horizontal distance and the value be the node that is at the lowest
point in the tree with that horizontal value. Then once we traverse the whole tree, we can sort the
dictionary based on the keys, and then map the array to the values, which whill be the nodes.
The reason we want to do a level order traversal is that we can use that to our advantage that when
we come across a new node with the same horizontal distance, since we can use it to our advantage that
the node at that same horizontal distance must have came before this current node or is on the same level.
As a result, we can simplt write over that in our dictionary!
Great! This will run in O(nlogn) time and O(n) space. This is because in the worst case, when the tree is full
then we will have half the number of nodes in the last level, this will then mean that the number of nodes
in the bottom view will be proportional to the total number of nodes in the tree, and thus, will be linearly
correlated to n, so the sorting time will still be upper bounded by O(nlogn)
Also, in the queue, we will store the node and the horizontal distance in a tuple
This will then allow us to update the bottom view dictionary as we will have the horizontal distnace
of the current node.
"""
from tree import Tree
def bottom_view_tree(root: Tree) -> list:
# dictionary to store the horizontal distances
horizontal_distances = {}
queue = [] if not root else [(root, 0)] # (node, hd)
# while there are still tuples in the queue, get the lowest horizontal distances
while queue:
# get the current node
node, hd = queue.pop()
# update the horiztonal distances dictionary
horizontal_distances[hd] = node.value
# add the children
if node.right: queue.append((node.right, hd + 1))
if node.left: queue.append((node.left, hd - 1))
# sort by hd, and then map to the value using a list comprehension
return [v for k, v in sorted(horizontal_distances.items(), key=lambda x: x[0])]
test_tree = Tree(5, Tree(7, Tree(9,left=Tree(8)), left=Tree(6)), left=Tree(3, Tree(4), left=Tree(1, left=Tree(0))))
"""
10(0)
/ \
(-1)1 15(1)
/
12(0)
"""
test_tree_2 = Tree(10, left=Tree(1), right=Tree(15, left=Tree(12)))
print(bottom_view_tree(test_tree))
print(bottom_view_tree(test_tree_2)) | 54ab23fb16cd19e87db3fa8a869693eaeed00d3f | [
"Markdown",
"Python",
"C++"
]
| 108 | Python | Bradysm/daily_coding_problems | e7337517813186c8fd9d9b7ead067e09e5644286 | 484cb4a4ec9518cd70fb76354203b07791f1ba75 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.