Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
231 changes: 229 additions & 2 deletions McBopomofo.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

18 changes: 18 additions & 0 deletions McBopomofoShare/Base.lproj/Localizable.strings
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"share.loadingContent" = "Loading shared content…";
"share.noInputItems" = "No shared items were received.";
"share.noSupportedContent" = "No supported shared content was received.";
"share.noDisplayablePhraseEntries" = "No phrase entries are available to display.";
"share.failedToWriteTempFile" = "Unable to write the temporary file.";
"share.failedToCreateUrl" = "Unable to build the McBopomofo URL.";
"share.failedToOpenApp" = "Unable to open McBopomofo.";
"share.error.failedToLoadSharedText" = "Unable to read the shared text.";
"share.error.failedToDecodeSharedText" = "Unable to decode the shared text.";
"share.error.failedToLoadContact" = "Unable to read the shared contact.";
"share.error.failedToParseContact" = "Unable to parse the shared contact.";
"share.error.phraseTooLong" = "\"%@\" exceeds %ld characters.";
"share.error.containsNonChineseCharacters" = "\"%@\" contains non-Chinese characters.";
"share.error.noDisplayablePhraseEntries" = "No valid phrase entries are available to add.";
"share.error.multipleErrorsHeader" = "Some shared content could not be used:";
"Cancel" = "Cancel";
"Add" = "Add";
"Add User Phrases" = "Add User Phrases";
82 changes: 82 additions & 0 deletions McBopomofoShare/Base.lproj/ShareViewController.xib
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="24765" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="24765"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="ShareViewController" customModule="McBopomofoShare" customModuleProvider="target">
<connections>
<outlet property="cancelButton" destination="NVE-vN-dkz" id="AT5-hj-nPW"/>
<outlet property="sendButton" destination="1uM-r7-H1c" id="VED-Ni-DyJ"/>
<outlet property="shareTitle" destination="aNc-0i-CWK" id="Swi-0g-OGd"/>
<outlet property="view" destination="1" id="2"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<customView translatesAutoresizingMaskIntoConstraints="NO" id="1">
<rect key="frame" x="0.0" y="0.0" width="388" height="202"/>
<subviews>
<button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="1uM-r7-H1c">
<rect key="frame" x="312" y="10" width="66" height="24"/>
<buttonCell key="cell" type="push" title="Send" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="2l4-PO-we5">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
<string key="keyEquivalent">D</string>
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</buttonCell>
<connections>
<action selector="send:" target="-2" id="yic-EC-GGk"/>
</connections>
</button>
<button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="NVE-vN-dkz">
<rect key="frame" x="238" y="10" width="66" height="24"/>
<buttonCell key="cell" type="push" title="Cancel" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="6Up-t3-mwm">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
<string key="keyEquivalent" base64-UTF8="YES">
Gw
</string>
</buttonCell>
<constraints>
<constraint firstAttribute="width" relation="greaterThanOrEqual" constant="60" id="cP1-hK-9ZX"/>
</constraints>
<connections>
<action selector="cancel:" target="-2" id="Qav-AK-DGt"/>
</connections>
</button>
<textField focusRingType="none" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="aNc-0i-CWK">
<rect key="frame" x="140" y="171" width="108" height="16"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="left" title="My Service Title" id="0xp-rC-2gr">
<font key="font" metaFont="systemBold"/>
<color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<imageView horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="4M6-D5-WIf">
<rect key="frame" x="110" y="171" width="22" height="22"/>
<constraints>
<constraint firstAttribute="width" constant="22" id="BOe-aZ-Njc"/>
<constraint firstAttribute="height" constant="22" id="zLg-1a-wlZ"/>
</constraints>
<imageCell key="cell" refusesFirstResponder="YES" alignment="left" imageScaling="proportionallyDown" id="q3u-Am-ZIA"/>
</imageView>
</subviews>
<constraints>
<constraint firstItem="1uM-r7-H1c" firstAttribute="leading" secondItem="NVE-vN-dkz" secondAttribute="trailing" constant="8" id="1UO-J1-LbJ"/>
<constraint firstItem="NVE-vN-dkz" firstAttribute="leading" relation="greaterThanOrEqual" secondItem="1" secondAttribute="leading" constant="20" symbolic="YES" id="3N9-qo-UfS"/>
<constraint firstAttribute="bottom" secondItem="1uM-r7-H1c" secondAttribute="bottom" constant="10" id="4wH-De-nMF"/>
<constraint firstAttribute="bottom" secondItem="NVE-vN-dkz" secondAttribute="bottom" constant="10" id="USG-Gg-of3"/>
<constraint firstItem="1uM-r7-H1c" firstAttribute="leading" secondItem="NVE-vN-dkz" secondAttribute="trailing" constant="8" id="a8N-vS-Ew9"/>
<constraint firstItem="aNc-0i-CWK" firstAttribute="centerY" secondItem="4M6-D5-WIf" secondAttribute="centerY" constant="2.5" id="ilP-G0-GVG"/>
<constraint firstItem="NVE-vN-dkz" firstAttribute="width" secondItem="1uM-r7-H1c" secondAttribute="width" id="qPo-ky-Fcw"/>
<constraint firstAttribute="trailing" secondItem="1uM-r7-H1c" secondAttribute="trailing" constant="10" id="qfT-cw-QQ2"/>
<constraint firstAttribute="centerX" secondItem="aNc-0i-CWK" secondAttribute="centerX" id="uV3-Wn-RA3"/>
<constraint firstItem="aNc-0i-CWK" firstAttribute="leading" secondItem="4M6-D5-WIf" secondAttribute="trailing" constant="10" id="vFR-5i-Dvo"/>
<constraint firstItem="aNc-0i-CWK" firstAttribute="top" secondItem="1" secondAttribute="top" constant="15" id="vpR-tf-ebx"/>
</constraints>
<point key="canvasLocation" x="140" y="154"/>
</customView>
</objects>
</document>
124 changes: 124 additions & 0 deletions McBopomofoShare/ContactShareInputPlugin.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// Copyright (c) 2022 and onwards The McBopomofo Authors.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// 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 AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

import Contacts
import Foundation
import UniformTypeIdentifiers

final class ContactPhraseEntryExtractor {
private let sanitizer = PhraseEntrySanitizer()

func phraseEntries(from contacts: [CNContact]) -> PhraseEntrySanitizationResult {
let names = contacts
.compactMap(displayName(for:))
.map(normalizedName(from:))

return sanitizer.sanitize(names)
}

private func displayName(for contact: CNContact) -> String? {
let formatter = CNContactFormatter()
formatter.style = .fullName
if let name = formatter.string(from: contact), !name.isEmpty {
return name
}

if !contact.organizationName.isEmpty {
return contact.organizationName
}

return nil
}

private func normalizedName(from name: String) -> String {
name.trimmingCharacters(in: .whitespacesAndNewlines)
}
}


final class ContactShareInputPlugin: ShareInputPlugin {
private let extractor = ContactPhraseEntryExtractor()

func matchingProviders(in providers: [NSItemProvider]) -> [NSItemProvider] {
let vCardType = UTType.vCard.identifier
return providers.filter { $0.hasItemConformingToTypeIdentifier(vCardType) }
}

func loadPhraseEntries(from providers: [NSItemProvider], completion: @escaping (Result<[String], any Error>) -> Void) {
let group = DispatchGroup()
let lock = NSLock()
var allContacts: [CNContact] = []
var allErrors: [ShareInputError] = []
let vCardType = UTType.vCard.identifier

for provider in providers {
group.enter()
provider.loadDataRepresentation(forTypeIdentifier: vCardType) { data, error in
defer { group.leave() }

if let error {
NSLog("Failed to load vCard: %@", error.localizedDescription)
lock.lock()
allErrors.append(.failedToLoadContact)
lock.unlock()
return
}

guard let data else {
lock.lock()
allErrors.append(.failedToLoadContact)
lock.unlock()
return
}

do {
let contacts = try CNContactVCardSerialization.contacts(with: data)
lock.lock()
allContacts.append(contentsOf: contacts)
lock.unlock()
} catch {
NSLog("Failed to parse vCard: %@", error.localizedDescription)
lock.lock()
allErrors.append(.failedToParseContact)
lock.unlock()
}
}
}

group.notify(queue: .main) {
let sanitization = self.extractor.phraseEntries(from: allContacts)
let uniqueErrors = (allErrors + sanitization.errors).uniqued()
if !uniqueErrors.isEmpty {
completion(.failure(ShareInputErrorGroup(errors: uniqueErrors)))
return
}

guard !sanitization.entries.isEmpty else {
completion(.failure(ShareInputError.noDisplayablePhraseEntries))
return
}

completion(.success(sanitization.entries))
}
}
}
29 changes: 29 additions & 0 deletions McBopomofoShare/Info.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIconFile</key>
<string>icon</string>
<key>NSExtension</key>
<dict>
<key>NSExtensionAttributes</key>
<dict>
<key>NSExtensionActivationRule</key>
<string>SUBQUERY (
extensionItems,
$extensionItem,
SUBQUERY (
$extensionItem.attachments,
$attachment,
ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.vcard"
OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.text"
).@count &gt; 0
).@count &gt; 0</string>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.share-services</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).ShareViewController</string>
</dict>
</dict>
</plist>
64 changes: 64 additions & 0 deletions McBopomofoShare/PhraseEntrySanitizer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copyright (c) 2022 and onwards The McBopomofo Authors.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// 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 AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

import Foundation

final class PhraseEntrySanitizer {
func sanitize(_ entries: [String]) -> PhraseEntrySanitizationResult {
var sanitized: [String] = []
var errors: [ShareInputError] = []

for entry in entries {
let trimmed = entry.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
continue
}

guard containsOnlyChineseCharacters(trimmed) else {
errors.append(.containsNonChineseCharacters(trimmed))
continue
}

sanitized.append(trimmed)
}

return PhraseEntrySanitizationResult(
entries: Array(Set(sanitized)).sorted(),
errors: errors.uniqued()
)
}

private func containsOnlyChineseCharacters(_ text: String) -> Bool {
!text.isEmpty && text.unicodeScalars.allSatisfy { scalar in
// Match common CJK Unified Ideographs blocks directly because CharacterSet does not offer a precise built-in "Chinese-only" test here.
switch scalar.value {
case 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xF900...0xFAFF, 0x20000...0x2A6DF,
0x2A700...0x2B73F, 0x2B740...0x2B81F, 0x2B820...0x2CEAF, 0x2CEB0...0x2EBEF,
0x30000...0x3134F:
return true
default:
return false
}
}
}
}
Loading
Loading