diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..0a9b14eae --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +*.js linguist-vendored +*.css linguist-vendored +*.html linguist-vendored \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..e287602b7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules +build +chrome +firefox +.vscode diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..063bcd179 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,14 @@ +language: node_js +node_js: + - "node" +before_script: + - "npm install -g typescript" + - "npm install -g gts" + - "npm install -g addons-linter" + - "npm install -g lintspaces-cli" +script: + - "gts check" + - "lintspaces -nt -d 'spaces' -i 'js-comments' src/* *.html manifest-*.json css/popup.css css/import.css" + - "npm run firefox" + - "npm run chrome" + - "addons-linter firefox" diff --git a/ISSUE_TEMPLATE.md b/ISSUE_TEMPLATE.md new file mode 100644 index 000000000..dd6efb364 --- /dev/null +++ b/ISSUE_TEMPLATE.md @@ -0,0 +1,3 @@ + + + diff --git a/LICENSE b/LICENSE index 0fe67bfb8..ebf4a3833 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2017 Zhe Li +Copyright (c) 2017 Authenticator Extension Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index abfd92652..e8d951a3a 100644 --- a/README.md +++ b/README.md @@ -1 +1,39 @@ -# Authenticator2 \ No newline at end of file + + +# Authenticator [![Build Status](https://travis-ci.org/Authenticator-Extension/Authenticator.svg?branch=dev)](https://travis-ci.org/Authenticator-Extension/Authenticator) [![Crowdin](https://d322cqt584bo4o.cloudfront.net/authenticator-firefox/localized.svg)](https://crowdin.com/project/authenticator-firefox) + +> Authenticator generates 2-Step Verification codes in your browser. + +You can install Authenticator from the [Chrome Web Store](https://chrome.google.com/webstore/detail/authenticator/bhghoamapcdpbohphigoooaddinpkbai) or from [Firefox Add-ons](https://addons.mozilla.org/en-US/firefox/addon/auth-helper/). + +## Build Setup + +Compile for Chrome: + +```bash +npm install +npm run chrome +``` +Compile for Firefox: + +```bash +npm install +npm run firefox +``` + +Compile for development: + +``` bash +# install typescript +npm install -g typescript +#install gts +npm install -g gts +# install dependencies +npm install +# check typescript style +gts check +# try to auto fix style issue +gts fix +# compile +npm run compile +``` diff --git a/_locales/en/messages.json b/_locales/en/messages.json new file mode 100644 index 000000000..269eb466d --- /dev/null +++ b/_locales/en/messages.json @@ -0,0 +1,238 @@ +{ + "extName": { + "message": "Authenticator", + "description": "Extension Name." + }, + "extShortName": { + "message": "Authenticator", + "description": "Extension Short Name." + }, + "extDesc": { + "message": "Authenticator generates 2-Step Verification codes in your browser.", + "description": "Extension Description." + }, + "added": { + "message": " has been added.", + "description": "Added Account." + }, + "errorqr": { + "message": "Unrecognized QR code.", + "description": "QR Error." + }, + "errorsecret": { + "message": "Secret Error. Only Base32(A-Z, 2-7 and =) and HEX(0-9 and A-F) are supported. However, your secret is: ", + "description": "Secret Error." + }, + "add_qr": { + "message": "Scan QR Code", + "description": "Scan QR Code." + }, + "add_secret": { + "message": "Manual Entry", + "description": "Manual Entry." + }, + "close": { + "message": "Close", + "description": "Close." + }, + "ok": { + "message": "Ok", + "description": "OK." + }, + "yes": { + "message": "Yes", + "description": "Yes." + }, + "no": { + "message": "No", + "description": "No." + }, + "account": { + "message": "Account", + "description": "Account." + }, + "accountName": { + "message": "Account Name", + "description": "Account Name." + }, + "issuer": { + "message": "Issuer", + "description": "Issuer." + }, + "secret": { + "message": "Secret", + "description": "Secret." + }, + "updateSuccess": { + "message": "Success.", + "description": "Update Success." + }, + "updateFailure": { + "message": "Failure.", + "description": "Update Failure." + }, + "about": { + "message": "About", + "description": "About." + }, + "export_import": { + "message": "Export / Import", + "description": "Export and Import." + }, + "settings": { + "message": "Settings", + "description": "Settings." + }, + "security": { + "message": "Security", + "description": "Security." + }, + "current_phrase": { + "message": "Current Password", + "description": "Current Passphrase." + }, + "new_phrase": { + "message": "New Password", + "description": "New Passphrase." + }, + "phrase": { + "message": "Password", + "description": "Passphrase." + }, + "confirm_phrase": { + "message": "Confirm Password", + "description": "Confirm Passphrase." + }, + "confirm_delete" : { + "message": "Are you sure you want to delete this secret? This action cannot be undone.", + "description": "Remove entry confirmation" + }, + "security_warning": { + "message": "This password will be used to encrypt your secrets. No one can help you if you forget the password.", + "description": "Passphrase Warning." + }, + "update": { + "message": "Update", + "description": "Update." + }, + "phrase_incorrect": { + "message": "You cannot add a new account or export data until all accounts are decrypted. Please enter the correct password before continuing.", + "description": "Passphrase Incorrect." + }, + "phrase_not_match": { + "message": "Password does not match.", + "description": "Passphrase Not Match." + }, + "encrypted": { + "message": "Encrypted", + "description": "Encrypted." + }, + "copied": { + "message": "Copied", + "description": "Copied." + }, + "feedback": { + "message": "Feedback", + "description": "Feedback." + }, + "translate": { + "message": "Translate", + "description": "Translate." + }, + "source": { + "message": "Source Code", + "description": "Source Code." + }, + "passphrase_info": { + "message": "Enter password to decrypt account data.", + "description": "Passphrase Info" + }, + "sync_clock": { + "message": "Sync Clock with Google", + "description": "Sync Clock" + }, + "remember_phrase": { + "message": "Remember Password", + "description": "Remember Passphrase" + }, + "clock_too_far_off": { + "message": "Caution! Your local clock is too far off, please fix it before continuing.", + "description": "Local Time is Too Far Off" + }, + "remind_backup": { + "message": "Do you have a backup for your secrets? Don't wait until it's too late!", + "description": "Remind Backup" + }, + "capture_failed": { + "message": "Capture failed, please reload the page and try again.", + "description": "Capture Failed" + }, + "based_on_time": { + "message": "Time Based", + "description": "Time Based" + }, + "based_on_counter": { + "message": "Counter Based", + "description": "Counter Based" + }, + "resize_popup_page": { + "message": "Resize Popup Page", + "description": "Resize Popup Page" + }, + "scale": { + "message": "Scale", + "description": "Scale" + }, + "export_info": { + "message": "Warning: all backups are unencrypted. Want to add an account to another app? Hover over the top right part of any account and hit the hidden button.", + "description": "Export menu info text" + }, + "download_backup": { + "message": "Download Backup File", + "description": "Download backup file." + }, + "import_backup": { + "message": "Import Backup", + "description": "Import backup." + }, + "import_backup_file": { + "message": "Import Backup File", + "description": "Import backup file." + }, + "import_backup_code": { + "message": "Import Text Backup", + "description": "Import backup code." + }, + "dropbox_backup": { + "message": "Auto Backup to Dropbox", + "description": "Auto backup to Dropbox." + }, + "dropbox_code": { + "message": "Dropbox Code", + "description": "Dropbox code." + }, + "dropbox_token": { + "message": "Dropbox Token", + "description": "Dropbox token." + }, + "dropbox_authorization": { + "message": "Get Code", + "description": "Dropbox authorization." + }, + "show_all_entries": { + "message": "Show all entries", + "description": "Show all entries." + }, + "dropbox_risk": { + "message": "Warning: backups saved in Dropbox are unencrypted. Use at your own risk.", + "description": "Dropbox backup risk warning." + }, + "import_error_password": { + "message": "You must provide correct password to import backups.", + "description": "Error password warning when import backups." + }, + "local_passphrase_warning": { + "message": "Your password is stored locally, please change it in the security menu immediately.", + "description": "localStorage password warning." + } +} diff --git a/_locales/es/messages.json b/_locales/es/messages.json new file mode 100644 index 000000000..3a8296d82 --- /dev/null +++ b/_locales/es/messages.json @@ -0,0 +1,238 @@ +{ + "extName": { + "message": "Autenticador", + "description": "Extension Name." + }, + "extShortName": { + "message": "Autenticador", + "description": "Extension Short Name." + }, + "extDesc": { + "message": "Autenticador genera vereficación de dos pasos para tu navegador.", + "description": "Extension Description." + }, + "added": { + "message": " ha sido añadido.", + "description": "Added Account." + }, + "errorqr": { + "message": "Código de QR no es reconocido.", + "description": "QR Error." + }, + "errorsecret": { + "message": "Error al secreto. Sólo Base32 (A-Z, 2-7 y =) y hexadecimal (0-9 y A-f) son compatibles. Sin embargo, su secreto es: ", + "description": "Secret Error." + }, + "add_qr": { + "message": "Escanear código QR", + "description": "Scan QR Code." + }, + "add_secret": { + "message": "Entrada Manual", + "description": "Manual Entry." + }, + "close": { + "message": "Cierra", + "description": "Close." + }, + "ok": { + "message": "Ok", + "description": "OK." + }, + "yes": { + "message": "Si", + "description": "Yes." + }, + "no": { + "message": "No", + "description": "No." + }, + "account": { + "message": "Cuenta", + "description": "Account." + }, + "accountName": { + "message": "Nombre de Cuenta", + "description": "Account Name." + }, + "issuer": { + "message": "Emisor", + "description": "Issuer." + }, + "secret": { + "message": "Secreto", + "description": "Secret." + }, + "updateSuccess": { + "message": "Éxito.", + "description": "Update Success." + }, + "updateFailure": { + "message": "Fracaso.", + "description": "Update Failure." + }, + "about": { + "message": "Acerca de", + "description": "About." + }, + "export_import": { + "message": "Exportación \/ importación", + "description": "Export and Import." + }, + "settings": { + "message": "Configuración -", + "description": "Settings." + }, + "security": { + "message": "Seguridad", + "description": "Security." + }, + "current_phrase": { + "message": "Contraseña actual", + "description": "Current Passphrase." + }, + "new_phrase": { + "message": "Nueva contraseña", + "description": "New Passphrase." + }, + "phrase": { + "message": "Contraseña", + "description": "Passphrase." + }, + "confirm_phrase": { + "message": "Confirme su contraseña", + "description": "Confirm Passphrase." + }, + "confirm_delete": { + "message": "¿Está seguro que desea eliminar esta secreto? ¡Esto no se puede deshacer.", + "description": "Remove entry confirmation" + }, + "security_warning": { + "message": "Esta contraseña se utilizará para cifrar tus secretos. Nadie le puede ayudar Si olvidas la contraseña.", + "description": "Passphrase Warning." + }, + "update": { + "message": "Actualizar", + "description": "Update." + }, + "phrase_incorrect": { + "message": "No puede Agregar una nueva cuenta o exportar los datos hasta que todas las cuentas se descifran. Introduce la contraseña correcta antes de continuar.", + "description": "Passphrase Incorrect." + }, + "phrase_not_match": { + "message": "Las contraseñas no coinciden.", + "description": "Passphrase Not Match." + }, + "encrypted": { + "message": "Cifrados", + "description": "Encrypted." + }, + "copied": { + "message": "Copiado", + "description": "Copied." + }, + "feedback": { + "message": "Comentarios", + "description": "Feedback." + }, + "translate": { + "message": "Traducir", + "description": "Translate." + }, + "source": { + "message": "Código fuente", + "description": "Source Code." + }, + "passphrase_info": { + "message": "Introduzca la contraseña para descifrar los datos de la cuenta.", + "description": "Passphrase Info" + }, + "sync_clock": { + "message": "Sincroniza el reloj con Google", + "description": "Sync Clock" + }, + "remember_phrase": { + "message": "Recuerda Contraseña", + "description": "Remember Passphrase" + }, + "clock_too_far_off": { + "message": "¡Precaución! Su reloj local está demasiado lejos, por favor arreglarlo antes de continuar.", + "description": "Local Time is Too Far Off" + }, + "remind_backup": { + "message": "¿Tienes una copia de seguridad de tus secretos? ¡No esperes hasta que sea demasiado tarde!", + "description": "Remind Backup" + }, + "capture_failed": { + "message": "Error en Captura, por favor recarga la página e inténtelo de nuevo.", + "description": "Capture Failed" + }, + "based_on_time": { + "message": "Tiempo en función", + "description": "Time Based" + }, + "based_on_counter": { + "message": "Contador basado en", + "description": "Counter Based" + }, + "resize_popup_page": { + "message": "Cambiar el tamaño de página", + "description": "Resize Popup Page" + }, + "scale": { + "message": "Escala", + "description": "Scale" + }, + "export_info": { + "message": "ADVERTENCIA: todos los backups son unencrypted. ¿Desea agregar una cuenta a otra aplicación? Pasa el cursor sobre la parte superior derecha de cualquier cuenta y presione el botón oculto.", + "description": "Export menu info text" + }, + "download_backup": { + "message": "Descargar archivo de respaldo", + "description": "Download backup file." + }, + "import_backup": { + "message": "Copia de seguridad de importación", + "description": "Import backup." + }, + "import_backup_file": { + "message": "Importar archivo de copia de seguridad", + "description": "Import backup file." + }, + "import_backup_code": { + "message": "Copia de seguridad de importación", + "description": "Import backup code." + }, + "dropbox_backup": { + "message": "Copia de seguridad automática a Dropbox", + "description": "Auto backup to Dropbox." + }, + "dropbox_code": { + "message": "Código de Dropbox", + "description": "Dropbox code." + }, + "dropbox_token": { + "message": "Token de Dropbox", + "description": "Dropbox token." + }, + "dropbox_authorization": { + "message": "Obtener el código de", + "description": "Dropbox authorization." + }, + "show_all_entries": { + "message": "Mostrar todas las entradas", + "description": "Show all entries." + }, + "dropbox_risk": { + "message": "ADVERTENCIA: backups guardados en Dropbox están sin cifrar. Usar bajo su propio riesgo.", + "description": "Dropbox backup risk warning." + }, + "import_error_password": { + "message": "Debe proporcionar la contraseña correcta para la importación de copias de seguridad.", + "description": "Error password warning when import backups." + }, + "local_passphrase_warning": { + "message": "La contraseña se almacena localmente, por favor cambiarlo en el menú de seguridad inmediatamente.", + "description": "localStorage password warning." + } +} \ No newline at end of file diff --git a/_locales/ja/messages.json b/_locales/ja/messages.json new file mode 100644 index 000000000..eec5d6907 --- /dev/null +++ b/_locales/ja/messages.json @@ -0,0 +1,238 @@ +{ + "extName": { + "message": "Authenticator", + "description": "Extension Name." + }, + "extShortName": { + "message": "Authenticator", + "description": "Extension Short Name." + }, + "extDesc": { + "message": "Authenticator はお使いのブラウザーで2段階認証コードを生成します。", + "description": "Extension Description." + }, + "added": { + "message": " 追加されました。", + "description": "Added Account." + }, + "errorqr": { + "message": "QR コードが認識できません。", + "description": "QR Error." + }, + "errorsecret": { + "message": "認証コードが間違っています。Base32 (A-Z, 2-7, =) と HEX (0-9, A-F) のみ使用できます。認証コード: ", + "description": "Secret Error." + }, + "add_qr": { + "message": "QRコードをスキャン", + "description": "Scan QR Code." + }, + "add_secret": { + "message": "手動入力", + "description": "Manual Entry." + }, + "close": { + "message": "閉じる", + "description": "Close." + }, + "ok": { + "message": "OK", + "description": "OK." + }, + "yes": { + "message": "はい", + "description": "Yes." + }, + "no": { + "message": "いいえ", + "description": "No." + }, + "account": { + "message": "アカウント", + "description": "Account." + }, + "accountName": { + "message": "アカウント名", + "description": "Account Name." + }, + "issuer": { + "message": "発行者", + "description": "Issuer." + }, + "secret": { + "message": "シークレット", + "description": "Secret." + }, + "updateSuccess": { + "message": "成功しました。", + "description": "Update Success." + }, + "updateFailure": { + "message": "失敗しました。", + "description": "Update Failure." + }, + "about": { + "message": "このアプリついて", + "description": "About." + }, + "export_import": { + "message": "エクスポート\/インポート", + "description": "Export and Import." + }, + "settings": { + "message": "設定", + "description": "Settings." + }, + "security": { + "message": "セキュリティ", + "description": "Security." + }, + "current_phrase": { + "message": "現在のパスワード", + "description": "Current Passphrase." + }, + "new_phrase": { + "message": "新しいパスワード", + "description": "New Passphrase." + }, + "phrase": { + "message": "パスワード", + "description": "Passphrase." + }, + "confirm_phrase": { + "message": "パスワードの再入力", + "description": "Confirm Passphrase." + }, + "confirm_delete": { + "message": "この認証を削除しても宜しいですか? この操作を元に戻すことはできません。", + "description": "Remove entry confirmation" + }, + "security_warning": { + "message": "このパスワードは認証を暗号化するために使用されます。パスワードを紛失した場合には復旧できませんのでお気をつけください。", + "description": "Passphrase Warning." + }, + "update": { + "message": "更新", + "description": "Update." + }, + "phrase_incorrect": { + "message": "すべてのアカウントが解読されるまで、新しいアカウントを追加したり、データをエクスポートすることはできません。続行する前に正しいパスワードを入力してください。", + "description": "Passphrase Incorrect." + }, + "phrase_not_match": { + "message": "パスワードが一致しません。", + "description": "Passphrase Not Match." + }, + "encrypted": { + "message": "暗号化", + "description": "Encrypted." + }, + "copied": { + "message": "コピーしました。", + "description": "Copied." + }, + "feedback": { + "message": "ご意見", + "description": "Feedback." + }, + "translate": { + "message": "翻訳", + "description": "Translate." + }, + "source": { + "message": "ソース コード", + "description": "Source Code." + }, + "passphrase_info": { + "message": "アカウントデータを復号化するパスワードを入力してください。", + "description": "Passphrase Info" + }, + "sync_clock": { + "message": "Google と時刻を同期", + "description": "Sync Clock" + }, + "remember_phrase": { + "message": "パスワードを記憶します。", + "description": "Remember Passphrase" + }, + "clock_too_far_off": { + "message": "危険!お使いの環境の日時が実際の日時と離れすぎています。続ける前にまずは修正してください。", + "description": "Local Time is Too Far Off" + }, + "remind_backup": { + "message": "認証のバックアップは取っていますか?忘れないうちにぜひ!", + "description": "Remind Backup" + }, + "capture_failed": { + "message": "キャプチャーできませんでした。再読込してもう一度お試しください。", + "description": "Capture Failed" + }, + "based_on_time": { + "message": "タイム ベース", + "description": "Time Based" + }, + "based_on_counter": { + "message": "カウンター ベース", + "description": "Counter Based" + }, + "resize_popup_page": { + "message": "ポップアップのサイズを変更", + "description": "Resize Popup Page" + }, + "scale": { + "message": "大きさ", + "description": "Scale" + }, + "export_info": { + "message": "警告: バックアップはすべて暗号化されていません。別のアプリにアカウントを追加したい場合、アカウントの右上にカーソルを合わせ、非表示のボタンを押してください。", + "description": "Export menu info text" + }, + "download_backup": { + "message": "バックアップファイルのダウンロード", + "description": "Download backup file." + }, + "import_backup": { + "message": "バックアップのインポート", + "description": "Import backup." + }, + "import_backup_file": { + "message": "バックアップファイルのインポート", + "description": "Import backup file." + }, + "import_backup_code": { + "message": "テキストのバックアップのインポート", + "description": "Import backup code." + }, + "dropbox_backup": { + "message": "Dropbox へ自動バックアップ", + "description": "Auto backup to Dropbox." + }, + "dropbox_code": { + "message": "Dropboxのコード", + "description": "Dropbox code." + }, + "dropbox_token": { + "message": "Dropboxのトークン", + "description": "Dropbox token." + }, + "dropbox_authorization": { + "message": "コードを取得", + "description": "Dropbox authorization." + }, + "show_all_entries": { + "message": "すべての登録を表示", + "description": "Show all entries." + }, + "dropbox_risk": { + "message": "警告: Dropbox に保存したバックアップは暗号化されていません。お気をつけください。", + "description": "Dropbox backup risk warning." + }, + "import_error_password": { + "message": "バックアップをインポートするために正しいパスワードを入力してください。", + "description": "Error password warning when import backups." + }, + "local_passphrase_warning": { + "message": "パスワードをローカル環境に保存しました。すぐにメニューのセキュリティから変更してください。", + "description": "localStorage password warning." + } +} \ No newline at end of file diff --git a/_locales/ru/messages.json b/_locales/ru/messages.json new file mode 100644 index 000000000..2b867506e --- /dev/null +++ b/_locales/ru/messages.json @@ -0,0 +1,238 @@ +{ + "extName": { + "message": "Авторизация", + "description": "Extension Name." + }, + "extShortName": { + "message": "Авторизация", + "description": "Extension Short Name." + }, + "extDesc": { + "message": "Аутентификатор генерирует коды подтверждения (Totp) 2-шаг в вашем браузере.", + "description": "Extension Description." + }, + "added": { + "message": " добавлено.", + "description": "Added Account." + }, + "errorqr": { + "message": "Unrecognized QR code.", + "description": "QR Error." + }, + "errorsecret": { + "message": "Секретный ошибка. Только Base32 (A-Z, 2-7 и =) и ШЕСТНАДЦАТЕРИЧНЫЙ (0-9 и A-F) поддерживаются. Однако ваш секрет: ", + "description": "Secret Error." + }, + "add_qr": { + "message": "Отсканировать QR-код", + "description": "Scan QR Code." + }, + "add_secret": { + "message": "Ручной ввод", + "description": "Manual Entry." + }, + "close": { + "message": "Закрыть", + "description": "Close." + }, + "ok": { + "message": "Готово", + "description": "OK." + }, + "yes": { + "message": "Да", + "description": "Yes." + }, + "no": { + "message": "Нет", + "description": "No." + }, + "account": { + "message": "Account", + "description": "Account." + }, + "accountName": { + "message": "Имя учётной записи", + "description": "Account Name." + }, + "issuer": { + "message": "Издатель", + "description": "Issuer." + }, + "secret": { + "message": "Секрет", + "description": "Secret." + }, + "updateSuccess": { + "message": "Успех.", + "description": "Update Success." + }, + "updateFailure": { + "message": "Неудача.", + "description": "Update Failure." + }, + "about": { + "message": "О расширении", + "description": "About." + }, + "export_import": { + "message": "Экспортировать и импортировать", + "description": "Export and Import." + }, + "settings": { + "message": "Настройки", + "description": "Settings." + }, + "security": { + "message": "Настройки Безопасности", + "description": "Security." + }, + "current_phrase": { + "message": "Текущий пароль", + "description": "Current Passphrase." + }, + "new_phrase": { + "message": "Новый Пароль", + "description": "New Passphrase." + }, + "phrase": { + "message": "Пароль", + "description": "Passphrase." + }, + "confirm_phrase": { + "message": "Подтвердить Пароль", + "description": "Confirm Passphrase." + }, + "confirm_delete": { + "message": "Вы правда хотите удалить этот секрет? Это действие безвозвратное.", + "description": "Remove entry confirmation" + }, + "security_warning": { + "message": "Этот пароль будет использоваться для вашего секрета. Ни кто вам не поможет если вы его забудете.", + "description": "Passphrase Warning." + }, + "update": { + "message": "Обновить", + "description": "Update." + }, + "phrase_incorrect": { + "message": "Вы не можете добавить новую учетную запись или вывести данные, пока не будет выполнен вход во все учётные записи. Пожалуйста, введите правильный пароль, прежде чем продолжить.", + "description": "Passphrase Incorrect." + }, + "phrase_not_match": { + "message": "Пороли не совпадают.", + "description": "Passphrase Not Match." + }, + "encrypted": { + "message": "Encrypted", + "description": "Encrypted." + }, + "copied": { + "message": "Скопировано", + "description": "Copied." + }, + "feedback": { + "message": "Отзыв", + "description": "Feedback." + }, + "translate": { + "message": "Перевод", + "description": "Translate." + }, + "source": { + "message": "Исходный код", + "description": "Source Code." + }, + "passphrase_info": { + "message": "Введите пароль для доступа к данным учётной записи.", + "description": "Passphrase Info" + }, + "sync_clock": { + "message": "Синхронизировать время с Google", + "description": "Sync Clock" + }, + "remember_phrase": { + "message": "Запомнить пароль", + "description": "Remember Passphrase" + }, + "clock_too_far_off": { + "message": "Внимание! Ваши местные часы слишком далеко, пожалуйста, исправить перед продолжением.", + "description": "Local Time is Too Far Off" + }, + "remind_backup": { + "message": "Не ждите если у вас есть копия ваших секретов или иначе будет поздно!", + "description": "Remind Backup" + }, + "capture_failed": { + "message": "Фокусировка не удалась, перезагрузите страницу и повторите попытку.", + "description": "Capture Failed" + }, + "based_on_time": { + "message": "Time Based", + "description": "Time Based" + }, + "based_on_counter": { + "message": "Counter Based", + "description": "Counter Based" + }, + "resize_popup_page": { + "message": "Изменение размера всплывающего окна", + "description": "Resize Popup Page" + }, + "scale": { + "message": "Масштаб", + "description": "Scale" + }, + "export_info": { + "message": "Внимание: все резервные копии не зашифрованы. Хотите добавить учетную запись в другое приложение? Наведите курсор на верхнюю правую часть любой учетной записи и нажмите скрытую кнопку.", + "description": "Export menu info text" + }, + "download_backup": { + "message": "Скачать резервную копию", + "description": "Download backup file." + }, + "import_backup": { + "message": "Импорт резервной копии", + "description": "Import backup." + }, + "import_backup_file": { + "message": "Импортировать резервный файл", + "description": "Import backup file." + }, + "import_backup_code": { + "message": "Импорт текста резервной копии", + "description": "Import backup code." + }, + "dropbox_backup": { + "message": "Автосохранение резервной копии в Dropbox", + "description": "Auto backup to Dropbox." + }, + "dropbox_code": { + "message": "Dropbox код", + "description": "Dropbox code." + }, + "dropbox_token": { + "message": "Dropbox маркер", + "description": "Dropbox token." + }, + "dropbox_authorization": { + "message": "Получить код", + "description": "Dropbox authorization." + }, + "show_all_entries": { + "message": "Показать все записи", + "description": "Show all entries." + }, + "dropbox_risk": { + "message": "Внимание: резервные копии, сохраненные в Dropbox, не зашифрованы. Используйте на свой страх и риск.", + "description": "Dropbox backup risk warning." + }, + "import_error_password": { + "message": "Для импорта резервных копий необходимо указать правильный пароль.", + "description": "Error password warning when import backups." + }, + "local_passphrase_warning": { + "message": "Ваш пароль хранится локально, пожалуйста немедленно изменить его в меню безопасность.", + "description": "localStorage password warning." + } +} \ No newline at end of file diff --git a/_locales/zh_CN/messages.json b/_locales/zh_CN/messages.json new file mode 100644 index 000000000..143bb51cf --- /dev/null +++ b/_locales/zh_CN/messages.json @@ -0,0 +1,238 @@ +{ + "extName": { + "message": "身份验证器", + "description": "Extension Name." + }, + "extShortName": { + "message": "身份验证器", + "description": "Extension Short Name." + }, + "extDesc": { + "message": "身份验证器用以在浏览器中生成二步认证代码。", + "description": "Extension Description." + }, + "added": { + "message": "已添加。", + "description": "Added Account." + }, + "errorqr": { + "message": "无法识别的QR码。", + "description": "QR Error." + }, + "errorsecret": { + "message": "密钥错误,仅支持Base32(A-Z,2-7及=)和HEX(0-9及A-F)格式,然而您的密钥是:", + "description": "Secret Error." + }, + "add_qr": { + "message": "扫描QR码", + "description": "Scan QR Code." + }, + "add_secret": { + "message": "手动输入", + "description": "Manual Entry." + }, + "close": { + "message": "关闭", + "description": "Close." + }, + "ok": { + "message": "确定", + "description": "OK." + }, + "yes": { + "message": "是", + "description": "Yes." + }, + "no": { + "message": "否", + "description": "No." + }, + "account": { + "message": "账户", + "description": "Account." + }, + "accountName": { + "message": "账户名称", + "description": "Account Name." + }, + "issuer": { + "message": "签发方", + "description": "Issuer." + }, + "secret": { + "message": "密钥", + "description": "Secret." + }, + "updateSuccess": { + "message": "成功。", + "description": "Update Success." + }, + "updateFailure": { + "message": "失败。", + "description": "Update Failure." + }, + "about": { + "message": "关于", + "description": "About." + }, + "export_import": { + "message": "导出 \/ 导入", + "description": "Export and Import." + }, + "settings": { + "message": "设置", + "description": "Settings." + }, + "security": { + "message": "安全", + "description": "Security." + }, + "current_phrase": { + "message": "当前密码", + "description": "Current Passphrase." + }, + "new_phrase": { + "message": "新密码", + "description": "New Passphrase." + }, + "phrase": { + "message": "密码", + "description": "Passphrase." + }, + "confirm_phrase": { + "message": "确认密码", + "description": "Confirmm Passphrase." + }, + "confirm_delete": { + "message": "您确定要删除此密钥吗?此操作无法撤销。", + "description": "Remove entry confirmation" + }, + "security_warning": { + "message": "您的密钥将使用此密码进行加密。如果您忘记了密码没有人能够提供帮助。", + "description": "Passphrase Warning." + }, + "update": { + "message": "更新", + "description": "Update." + }, + "phrase_incorrect": { + "message": "部分账户与密码不匹配,您无法添加新账户、导出账户数据或者更改密码。请提供正确的密码后重试。", + "description": "Passphrase Incorrect." + }, + "phrase_not_match": { + "message": "两次密码不一致。", + "description": "Passphrase Not Match." + }, + "encrypted": { + "message": "已加密", + "description": "Encrypted." + }, + "copied": { + "message": "已复制", + "description": "Copied." + }, + "feedback": { + "message": "问题反馈", + "description": "Feedback." + }, + "translate": { + "message": "参与翻译", + "description": "Translate." + }, + "source": { + "message": "源代码", + "description": "Source Code." + }, + "passphrase_info": { + "message": "输入密码以解码账户数据。", + "description": "Passphrase Info" + }, + "sync_clock": { + "message": "通过Google校准时间", + "description": "Sync Clock" + }, + "remember_phrase": { + "message": "记住密码", + "description": "Remember Passphrase" + }, + "clock_too_far_off": { + "message": "注意!您的本地时钟时间差过大,请修正后再进行操作。", + "description": "Local Time is Too Far Off" + }, + "remind_backup": { + "message": "您是否为密钥创建了备份?不要等到为时已晚。", + "description": "Remind Backup" + }, + "capture_failed": { + "message": "捕捉失败,请重载您正在浏览的页面后重试。", + "description": "Capture Failed" + }, + "based_on_time": { + "message": "基于时间", + "description": "Time Based" + }, + "based_on_counter": { + "message": "基于计数器", + "description": "Counter Based" + }, + "resize_popup_page": { + "message": "调整弹出页面尺寸", + "description": "Resize Popup Page" + }, + "scale": { + "message": "比例", + "description": "Scale" + }, + "export_info": { + "message": "警告:所有备份均未加密。想要将账号添加至其他应用?请点击账号右上角隐藏的图标。", + "description": "Export menu info text" + }, + "download_backup": { + "message": "下载备份文件", + "description": "Download backup file." + }, + "import_backup": { + "message": "导入备份", + "description": "Import backup." + }, + "import_backup_file": { + "message": "导入备份文件", + "description": "Import backup file." + }, + "import_backup_code": { + "message": "导入备份文本", + "description": "Import backup code." + }, + "dropbox_backup": { + "message": "自动备份至Dropbox", + "description": "Auto backup to Dropbox." + }, + "dropbox_code": { + "message": "Dropbox授权码", + "description": "Dropbox code." + }, + "dropbox_token": { + "message": "Dropbox Token", + "description": "Dropbox token." + }, + "dropbox_authorization": { + "message": "获取授权码", + "description": "Dropbox authorization." + }, + "show_all_entries": { + "message": "显示全部条目", + "description": "Show all entries." + }, + "dropbox_risk": { + "message": "警告:保存至Dropbox的备份均未备份,您需自担风险。", + "description": "Dropbox backup risk warning." + }, + "import_error_password": { + "message": "您必须提供正确的密码才能导入备份。", + "description": "Error password warning when import backups." + }, + "local_passphrase_warning": { + "message": "您的密码保存在了本地,请立即通过安全菜单更改密码。", + "description": "localStorage password warning." + } +} diff --git a/_locales/zh_TW/messages.json b/_locales/zh_TW/messages.json new file mode 100644 index 000000000..a2c4b925b --- /dev/null +++ b/_locales/zh_TW/messages.json @@ -0,0 +1,238 @@ +{ + "extName": { + "message": "Authenticator", + "description": "Extension Name." + }, + "extShortName": { + "message": "Authenticator", + "description": "Extension Short Name." + }, + "extDesc": { + "message": "Authenticator用以在瀏覽器中生成二步認證程式碼。", + "description": "Extension Description." + }, + "added": { + "message": "已新增。", + "description": "Added Account." + }, + "errorqr": { + "message": "無法識別的QR碼。", + "description": "QR Error." + }, + "errorsecret": { + "message": "金鑰錯誤,僅支援Base32(A-Z,2-7及=)和HEX(0-9及A-F)格式,然而您的金鑰是:", + "description": "Secret Error." + }, + "add_qr": { + "message": "掃描QR碼", + "description": "Scan QR Code." + }, + "add_secret": { + "message": "手動輸入", + "description": "Manual Entry." + }, + "close": { + "message": "關閉", + "description": "Close." + }, + "ok": { + "message": "確定", + "description": "OK." + }, + "yes": { + "message": "是", + "description": "Yes." + }, + "no": { + "message": "否", + "description": "No." + }, + "account": { + "message": "賬戶", + "description": "Account." + }, + "accountName": { + "message": "賬戶名稱", + "description": "Account Name." + }, + "issuer": { + "message": "簽發方", + "description": "Issuer." + }, + "secret": { + "message": "金鑰", + "description": "Secret." + }, + "updateSuccess": { + "message": "成功。", + "description": "Update Success." + }, + "updateFailure": { + "message": "失敗。", + "description": "Update Failure." + }, + "about": { + "message": "關於", + "description": "About." + }, + "export_import": { + "message": "匯出 \/ 匯入", + "description": "Export and Import." + }, + "settings": { + "message": "設定", + "description": "Settings." + }, + "security": { + "message": "安全", + "description": "Security." + }, + "current_phrase": { + "message": "當前密碼", + "description": "Current Passphrase." + }, + "new_phrase": { + "message": "新密碼", + "description": "New Passphrase." + }, + "phrase": { + "message": "密碼", + "description": "Passphrase." + }, + "confirm_phrase": { + "message": "確認密碼", + "description": "Confirm Passphrase." + }, + "confirm_delete": { + "message": "您確定要刪除此金鑰嗎?此操作無法撤銷。", + "description": "Remove entry confirmation" + }, + "security_warning": { + "message": "您的金鑰將使用此密碼進行加密。如果您忘記了密碼沒有人能夠提供幫助。", + "description": "Passphrase Warning." + }, + "update": { + "message": "更新", + "description": "Update." + }, + "phrase_incorrect": { + "message": "部分賬戶與密碼不匹配,您無法新增新賬戶、匯出賬戶資料或者更改密碼。請提供正確的密碼後重試。", + "description": "Passphrase Incorrect." + }, + "phrase_not_match": { + "message": "兩次密碼不一致。", + "description": "Passphrase Not Match." + }, + "encrypted": { + "message": "已加密", + "description": "Encrypted." + }, + "copied": { + "message": "已複製", + "description": "Copied." + }, + "feedback": { + "message": "問題反饋", + "description": "Feedback." + }, + "translate": { + "message": "參與翻譯", + "description": "Translate." + }, + "source": { + "message": "原始碼", + "description": "Source Code." + }, + "passphrase_info": { + "message": "輸入密碼以解碼賬戶資料。", + "description": "Passphrase Info" + }, + "sync_clock": { + "message": "通過Google校準時間", + "description": "Sync Clock" + }, + "remember_phrase": { + "message": "記住密碼", + "description": "Remember Passphrase" + }, + "clock_too_far_off": { + "message": "注意!您的本地時鐘時間差過大,請修正後再進行操作。", + "description": "Local Time is Too Far Off" + }, + "remind_backup": { + "message": "您是否為金鑰建立了備份?不要等到為時已晚。", + "description": "Remind Backup" + }, + "capture_failed": { + "message": "捕捉失敗,請過載您正在瀏覽的頁面後重試。", + "description": "Capture Failed" + }, + "based_on_time": { + "message": "基於時間", + "description": "Time Based" + }, + "based_on_counter": { + "message": "基於計數器", + "description": "Counter Based" + }, + "resize_popup_page": { + "message": "調整彈出頁面尺寸", + "description": "Resize Popup Page" + }, + "scale": { + "message": "比例", + "description": "Scale" + }, + "export_info": { + "message": "警告:所有備份均未加密。想要將賬號新增至其他應用?請點選賬號右上角隱藏的圖示。", + "description": "Export menu info text" + }, + "download_backup": { + "message": "下載備份檔案", + "description": "Download backup file." + }, + "import_backup": { + "message": "匯入備份", + "description": "Import backup." + }, + "import_backup_file": { + "message": "匯入備份檔案", + "description": "Import backup file." + }, + "import_backup_code": { + "message": "匯入備份文字", + "description": "Import backup code." + }, + "dropbox_backup": { + "message": "自動備份至Dropbox", + "description": "Auto backup to Dropbox." + }, + "dropbox_code": { + "message": "Dropbox授權碼", + "description": "Dropbox code." + }, + "dropbox_token": { + "message": "Dropbox Token", + "description": "Dropbox token." + }, + "dropbox_authorization": { + "message": "獲取授權碼", + "description": "Dropbox authorization." + }, + "show_all_entries": { + "message": "顯示全部條目", + "description": "Show all entries." + }, + "dropbox_risk": { + "message": "警告:儲存至Dropbox的備份均未備份,您需自擔風險。", + "description": "Dropbox backup risk warning." + }, + "import_error_password": { + "message": "您必須提供正確的密碼才能匯入備份。", + "description": "Error password warning when import backups." + }, + "local_passphrase_warning": { + "message": "您的密碼儲存在了本地,請立即通過安全選單更改密碼。", + "description": "localStorage password warning." + } +} \ No newline at end of file diff --git a/crowdin.yml b/crowdin.yml new file mode 100644 index 000000000..987c85f93 --- /dev/null +++ b/crowdin.yml @@ -0,0 +1,8 @@ +files: + - source: /_locales/en/messages.json + translation: /_locales/%two_letters_code%/messages.json + languages_mapping: + two_letters_code: + zh-CN: zh_CN + zh-TW: zh_TW + pt-BR: pt_BR diff --git a/css/DroidSansMono.woff2 b/css/DroidSansMono.woff2 new file mode 100644 index 000000000..ca4b22690 Binary files /dev/null and b/css/DroidSansMono.woff2 differ diff --git a/css/content.css b/css/content.css new file mode 100644 index 000000000..cb30a6aaa --- /dev/null +++ b/css/content.css @@ -0,0 +1,25 @@ +#__ga_grayLayout__ { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: rgba(0, 0, 0, 0.6); + z-index: 1000000; + display: none; + cursor: crosshair; +} + +#__ga_grayLayout__ .scan { + width: 100%; + height: 100%; + position: absolute; + top: 0; + opacity: 0.5; +} + +#__ga_captureBox__ { + position: absolute; + border: white 1px dashed; + display: none; +} \ No newline at end of file diff --git a/css/font-awesome.css b/css/font-awesome.css new file mode 100644 index 000000000..3b2b7cfee --- /dev/null +++ b/css/font-awesome.css @@ -0,0 +1,1800 @@ +/*! + * Font Awesome 4.3.0 by @davegandy - http://fontawesome.io - @fontawesome + * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) + */ +/* FONT PATH + * -------------------------- */ +@font-face { + font-family: 'FontAwesome'; + src: url('fontawesome-webfont.woff2') format('woff2'); + font-weight: normal; + font-style: normal; +} +.fa { + display: inline-block; + font: normal normal normal 14px/1 FontAwesome; + font-size: inherit; + text-rendering: auto; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + transform: translate(0, 0); +} +/* makes the font 33% larger relative to the icon container */ +.fa-lg { + font-size: 1.33333333em; + line-height: 0.75em; + vertical-align: -15%; +} +.fa-2x { + font-size: 2em; +} +.fa-3x { + font-size: 3em; +} +.fa-4x { + font-size: 4em; +} +.fa-5x { + font-size: 5em; +} +.fa-fw { + width: 1.28571429em; + text-align: center; +} +.fa-ul { + padding-left: 0; + margin-left: 2.14285714em; + list-style-type: none; +} +.fa-ul > li { + position: relative; +} +.fa-li { + position: absolute; + left: -2.14285714em; + width: 2.14285714em; + top: 0.14285714em; + text-align: center; +} +.fa-li.fa-lg { + left: -1.85714286em; +} +.fa-border { + padding: .2em .25em .15em; + border: solid 0.08em #eeeeee; + border-radius: .1em; +} +.pull-right { + float: right; +} +.pull-left { + float: left; +} +.fa.pull-left { + margin-right: .3em; +} +.fa.pull-right { + margin-left: .3em; +} +.fa-spin { + -webkit-animation: fa-spin 2s infinite linear; + animation: fa-spin 2s infinite linear; +} +.fa-pulse { + -webkit-animation: fa-spin 1s infinite steps(8); + animation: fa-spin 1s infinite steps(8); +} +@-webkit-keyframes fa-spin { + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + 100% { + -webkit-transform: rotate(359deg); + transform: rotate(359deg); + } +} +@keyframes fa-spin { + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + 100% { + -webkit-transform: rotate(359deg); + transform: rotate(359deg); + } +} +.fa-rotate-90 { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1); + -webkit-transform: rotate(90deg); + -ms-transform: rotate(90deg); + transform: rotate(90deg); +} +.fa-rotate-180 { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2); + -webkit-transform: rotate(180deg); + -ms-transform: rotate(180deg); + transform: rotate(180deg); +} +.fa-rotate-270 { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); + -webkit-transform: rotate(270deg); + -ms-transform: rotate(270deg); + transform: rotate(270deg); +} +.fa-flip-horizontal { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1); + -webkit-transform: scale(-1, 1); + -ms-transform: scale(-1, 1); + transform: scale(-1, 1); +} +.fa-flip-vertical { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1); + -webkit-transform: scale(1, -1); + -ms-transform: scale(1, -1); + transform: scale(1, -1); +} +:root .fa-rotate-90, +:root .fa-rotate-180, +:root .fa-rotate-270, +:root .fa-flip-horizontal, +:root .fa-flip-vertical { + filter: none; +} +.fa-stack { + position: relative; + display: inline-block; + width: 2em; + height: 2em; + line-height: 2em; + vertical-align: middle; +} +.fa-stack-1x, +.fa-stack-2x { + position: absolute; + left: 0; + width: 100%; + text-align: center; +} +.fa-stack-1x { + line-height: inherit; +} +.fa-stack-2x { + font-size: 2em; +} +.fa-inverse { + color: #ffffff; +} +/* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen + readers do not read off random characters that represent icons */ +.fa-glass:before { + content: "\f000"; +} +.fa-music:before { + content: "\f001"; +} +.fa-search:before { + content: "\f002"; +} +.fa-envelope-o:before { + content: "\f003"; +} +.fa-heart:before { + content: "\f004"; +} +.fa-star:before { + content: "\f005"; +} +.fa-star-o:before { + content: "\f006"; +} +.fa-user:before { + content: "\f007"; +} +.fa-film:before { + content: "\f008"; +} +.fa-th-large:before { + content: "\f009"; +} +.fa-th:before { + content: "\f00a"; +} +.fa-th-list:before { + content: "\f00b"; +} +.fa-check:before { + content: "\f00c"; +} +.fa-remove:before, +.fa-close:before, +.fa-times:before { + content: "\f00d"; +} +.fa-search-plus:before { + content: "\f00e"; +} +.fa-search-minus:before { + content: "\f010"; +} +.fa-power-off:before { + content: "\f011"; +} +.fa-signal:before { + content: "\f012"; +} +.fa-gear:before, +.fa-cog:before { + content: "\f013"; +} +.fa-trash-o:before { + content: "\f014"; +} +.fa-home:before { + content: "\f015"; +} +.fa-file-o:before { + content: "\f016"; +} +.fa-clock-o:before { + content: "\f017"; +} +.fa-road:before { + content: "\f018"; +} +.fa-download:before { + content: "\f019"; +} +.fa-arrow-circle-o-down:before { + content: "\f01a"; +} +.fa-arrow-circle-o-up:before { + content: "\f01b"; +} +.fa-inbox:before { + content: "\f01c"; +} +.fa-play-circle-o:before { + content: "\f01d"; +} +.fa-rotate-right:before, +.fa-repeat:before { + content: "\f01e"; +} +.fa-refresh:before { + content: "\f021"; +} +.fa-list-alt:before { + content: "\f022"; +} +.fa-lock:before { + content: "\f023"; +} +.fa-flag:before { + content: "\f024"; +} +.fa-headphones:before { + content: "\f025"; +} +.fa-volume-off:before { + content: "\f026"; +} +.fa-volume-down:before { + content: "\f027"; +} +.fa-volume-up:before { + content: "\f028"; +} +.fa-qrcode:before { + content: "\f029"; +} +.fa-barcode:before { + content: "\f02a"; +} +.fa-tag:before { + content: "\f02b"; +} +.fa-tags:before { + content: "\f02c"; +} +.fa-book:before { + content: "\f02d"; +} +.fa-bookmark:before { + content: "\f02e"; +} +.fa-print:before { + content: "\f02f"; +} +.fa-camera:before { + content: "\f030"; +} +.fa-font:before { + content: "\f031"; +} +.fa-bold:before { + content: "\f032"; +} +.fa-italic:before { + content: "\f033"; +} +.fa-text-height:before { + content: "\f034"; +} +.fa-text-width:before { + content: "\f035"; +} +.fa-align-left:before { + content: "\f036"; +} +.fa-align-center:before { + content: "\f037"; +} +.fa-align-right:before { + content: "\f038"; +} +.fa-align-justify:before { + content: "\f039"; +} +.fa-list:before { + content: "\f03a"; +} +.fa-dedent:before, +.fa-outdent:before { + content: "\f03b"; +} +.fa-indent:before { + content: "\f03c"; +} +.fa-video-camera:before { + content: "\f03d"; +} +.fa-photo:before, +.fa-image:before, +.fa-picture-o:before { + content: "\f03e"; +} +.fa-pencil:before { + content: "\f040"; +} +.fa-map-marker:before { + content: "\f041"; +} +.fa-adjust:before { + content: "\f042"; +} +.fa-tint:before { + content: "\f043"; +} +.fa-edit:before, +.fa-pencil-square-o:before { + content: "\f044"; +} +.fa-share-square-o:before { + content: "\f045"; +} +.fa-check-square-o:before { + content: "\f046"; +} +.fa-arrows:before { + content: "\f047"; +} +.fa-step-backward:before { + content: "\f048"; +} +.fa-fast-backward:before { + content: "\f049"; +} +.fa-backward:before { + content: "\f04a"; +} +.fa-play:before { + content: "\f04b"; +} +.fa-pause:before { + content: "\f04c"; +} +.fa-stop:before { + content: "\f04d"; +} +.fa-forward:before { + content: "\f04e"; +} +.fa-fast-forward:before { + content: "\f050"; +} +.fa-step-forward:before { + content: "\f051"; +} +.fa-eject:before { + content: "\f052"; +} +.fa-chevron-left:before { + content: "\f053"; +} +.fa-chevron-right:before { + content: "\f054"; +} +.fa-plus-circle:before { + content: "\f055"; +} +.fa-minus-circle:before { + content: "\f056"; +} +.fa-times-circle:before { + content: "\f057"; +} +.fa-check-circle:before { + content: "\f058"; +} +.fa-question-circle:before { + content: "\f059"; +} +.fa-info-circle:before { + content: "\f05a"; +} +.fa-crosshairs:before { + content: "\f05b"; +} +.fa-times-circle-o:before { + content: "\f05c"; +} +.fa-check-circle-o:before { + content: "\f05d"; +} +.fa-ban:before { + content: "\f05e"; +} +.fa-arrow-left:before { + content: "\f060"; +} +.fa-arrow-right:before { + content: "\f061"; +} +.fa-arrow-up:before { + content: "\f062"; +} +.fa-arrow-down:before { + content: "\f063"; +} +.fa-mail-forward:before, +.fa-share:before { + content: "\f064"; +} +.fa-expand:before { + content: "\f065"; +} +.fa-compress:before { + content: "\f066"; +} +.fa-plus:before { + content: "\f067"; +} +.fa-minus:before { + content: "\f068"; +} +.fa-asterisk:before { + content: "\f069"; +} +.fa-exclamation-circle:before { + content: "\f06a"; +} +.fa-gift:before { + content: "\f06b"; +} +.fa-leaf:before { + content: "\f06c"; +} +.fa-fire:before { + content: "\f06d"; +} +.fa-eye:before { + content: "\f06e"; +} +.fa-eye-slash:before { + content: "\f070"; +} +.fa-warning:before, +.fa-exclamation-triangle:before { + content: "\f071"; +} +.fa-plane:before { + content: "\f072"; +} +.fa-calendar:before { + content: "\f073"; +} +.fa-random:before { + content: "\f074"; +} +.fa-comment:before { + content: "\f075"; +} +.fa-magnet:before { + content: "\f076"; +} +.fa-chevron-up:before { + content: "\f077"; +} +.fa-chevron-down:before { + content: "\f078"; +} +.fa-retweet:before { + content: "\f079"; +} +.fa-shopping-cart:before { + content: "\f07a"; +} +.fa-folder:before { + content: "\f07b"; +} +.fa-folder-open:before { + content: "\f07c"; +} +.fa-arrows-v:before { + content: "\f07d"; +} +.fa-arrows-h:before { + content: "\f07e"; +} +.fa-bar-chart-o:before, +.fa-bar-chart:before { + content: "\f080"; +} +.fa-twitter-square:before { + content: "\f081"; +} +.fa-facebook-square:before { + content: "\f082"; +} +.fa-camera-retro:before { + content: "\f083"; +} +.fa-key:before { + content: "\f084"; +} +.fa-gears:before, +.fa-cogs:before { + content: "\f085"; +} +.fa-comments:before { + content: "\f086"; +} +.fa-thumbs-o-up:before { + content: "\f087"; +} +.fa-thumbs-o-down:before { + content: "\f088"; +} +.fa-star-half:before { + content: "\f089"; +} +.fa-heart-o:before { + content: "\f08a"; +} +.fa-sign-out:before { + content: "\f08b"; +} +.fa-linkedin-square:before { + content: "\f08c"; +} +.fa-thumb-tack:before { + content: "\f08d"; +} +.fa-external-link:before { + content: "\f08e"; +} +.fa-sign-in:before { + content: "\f090"; +} +.fa-trophy:before { + content: "\f091"; +} +.fa-github-square:before { + content: "\f092"; +} +.fa-upload:before { + content: "\f093"; +} +.fa-lemon-o:before { + content: "\f094"; +} +.fa-phone:before { + content: "\f095"; +} +.fa-square-o:before { + content: "\f096"; +} +.fa-bookmark-o:before { + content: "\f097"; +} +.fa-phone-square:before { + content: "\f098"; +} +.fa-twitter:before { + content: "\f099"; +} +.fa-facebook-f:before, +.fa-facebook:before { + content: "\f09a"; +} +.fa-github:before { + content: "\f09b"; +} +.fa-unlock:before { + content: "\f09c"; +} +.fa-credit-card:before { + content: "\f09d"; +} +.fa-rss:before { + content: "\f09e"; +} +.fa-hdd-o:before { + content: "\f0a0"; +} +.fa-bullhorn:before { + content: "\f0a1"; +} +.fa-bell:before { + content: "\f0f3"; +} +.fa-certificate:before { + content: "\f0a3"; +} +.fa-hand-o-right:before { + content: "\f0a4"; +} +.fa-hand-o-left:before { + content: "\f0a5"; +} +.fa-hand-o-up:before { + content: "\f0a6"; +} +.fa-hand-o-down:before { + content: "\f0a7"; +} +.fa-arrow-circle-left:before { + content: "\f0a8"; +} +.fa-arrow-circle-right:before { + content: "\f0a9"; +} +.fa-arrow-circle-up:before { + content: "\f0aa"; +} +.fa-arrow-circle-down:before { + content: "\f0ab"; +} +.fa-globe:before { + content: "\f0ac"; +} +.fa-wrench:before { + content: "\f0ad"; +} +.fa-tasks:before { + content: "\f0ae"; +} +.fa-filter:before { + content: "\f0b0"; +} +.fa-briefcase:before { + content: "\f0b1"; +} +.fa-arrows-alt:before { + content: "\f0b2"; +} +.fa-group:before, +.fa-users:before { + content: "\f0c0"; +} +.fa-chain:before, +.fa-link:before { + content: "\f0c1"; +} +.fa-cloud:before { + content: "\f0c2"; +} +.fa-flask:before { + content: "\f0c3"; +} +.fa-cut:before, +.fa-scissors:before { + content: "\f0c4"; +} +.fa-copy:before, +.fa-files-o:before { + content: "\f0c5"; +} +.fa-paperclip:before { + content: "\f0c6"; +} +.fa-save:before, +.fa-floppy-o:before { + content: "\f0c7"; +} +.fa-square:before { + content: "\f0c8"; +} +.fa-navicon:before, +.fa-reorder:before, +.fa-bars:before { + content: "\f0c9"; +} +.fa-list-ul:before { + content: "\f0ca"; +} +.fa-list-ol:before { + content: "\f0cb"; +} +.fa-strikethrough:before { + content: "\f0cc"; +} +.fa-underline:before { + content: "\f0cd"; +} +.fa-table:before { + content: "\f0ce"; +} +.fa-magic:before { + content: "\f0d0"; +} +.fa-truck:before { + content: "\f0d1"; +} +.fa-pinterest:before { + content: "\f0d2"; +} +.fa-pinterest-square:before { + content: "\f0d3"; +} +.fa-google-plus-square:before { + content: "\f0d4"; +} +.fa-google-plus:before { + content: "\f0d5"; +} +.fa-money:before { + content: "\f0d6"; +} +.fa-caret-down:before { + content: "\f0d7"; +} +.fa-caret-up:before { + content: "\f0d8"; +} +.fa-caret-left:before { + content: "\f0d9"; +} +.fa-caret-right:before { + content: "\f0da"; +} +.fa-columns:before { + content: "\f0db"; +} +.fa-unsorted:before, +.fa-sort:before { + content: "\f0dc"; +} +.fa-sort-down:before, +.fa-sort-desc:before { + content: "\f0dd"; +} +.fa-sort-up:before, +.fa-sort-asc:before { + content: "\f0de"; +} +.fa-envelope:before { + content: "\f0e0"; +} +.fa-linkedin:before { + content: "\f0e1"; +} +.fa-rotate-left:before, +.fa-undo:before { + content: "\f0e2"; +} +.fa-legal:before, +.fa-gavel:before { + content: "\f0e3"; +} +.fa-dashboard:before, +.fa-tachometer:before { + content: "\f0e4"; +} +.fa-comment-o:before { + content: "\f0e5"; +} +.fa-comments-o:before { + content: "\f0e6"; +} +.fa-flash:before, +.fa-bolt:before { + content: "\f0e7"; +} +.fa-sitemap:before { + content: "\f0e8"; +} +.fa-umbrella:before { + content: "\f0e9"; +} +.fa-paste:before, +.fa-clipboard:before { + content: "\f0ea"; +} +.fa-lightbulb-o:before { + content: "\f0eb"; +} +.fa-exchange:before { + content: "\f0ec"; +} +.fa-cloud-download:before { + content: "\f0ed"; +} +.fa-cloud-upload:before { + content: "\f0ee"; +} +.fa-user-md:before { + content: "\f0f0"; +} +.fa-stethoscope:before { + content: "\f0f1"; +} +.fa-suitcase:before { + content: "\f0f2"; +} +.fa-bell-o:before { + content: "\f0a2"; +} +.fa-coffee:before { + content: "\f0f4"; +} +.fa-cutlery:before { + content: "\f0f5"; +} +.fa-file-text-o:before { + content: "\f0f6"; +} +.fa-building-o:before { + content: "\f0f7"; +} +.fa-hospital-o:before { + content: "\f0f8"; +} +.fa-ambulance:before { + content: "\f0f9"; +} +.fa-medkit:before { + content: "\f0fa"; +} +.fa-fighter-jet:before { + content: "\f0fb"; +} +.fa-beer:before { + content: "\f0fc"; +} +.fa-h-square:before { + content: "\f0fd"; +} +.fa-plus-square:before { + content: "\f0fe"; +} +.fa-angle-double-left:before { + content: "\f100"; +} +.fa-angle-double-right:before { + content: "\f101"; +} +.fa-angle-double-up:before { + content: "\f102"; +} +.fa-angle-double-down:before { + content: "\f103"; +} +.fa-angle-left:before { + content: "\f104"; +} +.fa-angle-right:before { + content: "\f105"; +} +.fa-angle-up:before { + content: "\f106"; +} +.fa-angle-down:before { + content: "\f107"; +} +.fa-desktop:before { + content: "\f108"; +} +.fa-laptop:before { + content: "\f109"; +} +.fa-tablet:before { + content: "\f10a"; +} +.fa-mobile-phone:before, +.fa-mobile:before { + content: "\f10b"; +} +.fa-circle-o:before { + content: "\f10c"; +} +.fa-quote-left:before { + content: "\f10d"; +} +.fa-quote-right:before { + content: "\f10e"; +} +.fa-spinner:before { + content: "\f110"; +} +.fa-circle:before { + content: "\f111"; +} +.fa-mail-reply:before, +.fa-reply:before { + content: "\f112"; +} +.fa-github-alt:before { + content: "\f113"; +} +.fa-folder-o:before { + content: "\f114"; +} +.fa-folder-open-o:before { + content: "\f115"; +} +.fa-smile-o:before { + content: "\f118"; +} +.fa-frown-o:before { + content: "\f119"; +} +.fa-meh-o:before { + content: "\f11a"; +} +.fa-gamepad:before { + content: "\f11b"; +} +.fa-keyboard-o:before { + content: "\f11c"; +} +.fa-flag-o:before { + content: "\f11d"; +} +.fa-flag-checkered:before { + content: "\f11e"; +} +.fa-terminal:before { + content: "\f120"; +} +.fa-code:before { + content: "\f121"; +} +.fa-mail-reply-all:before, +.fa-reply-all:before { + content: "\f122"; +} +.fa-star-half-empty:before, +.fa-star-half-full:before, +.fa-star-half-o:before { + content: "\f123"; +} +.fa-location-arrow:before { + content: "\f124"; +} +.fa-crop:before { + content: "\f125"; +} +.fa-code-fork:before { + content: "\f126"; +} +.fa-unlink:before, +.fa-chain-broken:before { + content: "\f127"; +} +.fa-question:before { + content: "\f128"; +} +.fa-info:before { + content: "\f129"; +} +.fa-exclamation:before { + content: "\f12a"; +} +.fa-superscript:before { + content: "\f12b"; +} +.fa-subscript:before { + content: "\f12c"; +} +.fa-eraser:before { + content: "\f12d"; +} +.fa-puzzle-piece:before { + content: "\f12e"; +} +.fa-microphone:before { + content: "\f130"; +} +.fa-microphone-slash:before { + content: "\f131"; +} +.fa-shield:before { + content: "\f132"; +} +.fa-calendar-o:before { + content: "\f133"; +} +.fa-fire-extinguisher:before { + content: "\f134"; +} +.fa-rocket:before { + content: "\f135"; +} +.fa-maxcdn:before { + content: "\f136"; +} +.fa-chevron-circle-left:before { + content: "\f137"; +} +.fa-chevron-circle-right:before { + content: "\f138"; +} +.fa-chevron-circle-up:before { + content: "\f139"; +} +.fa-chevron-circle-down:before { + content: "\f13a"; +} +.fa-html5:before { + content: "\f13b"; +} +.fa-css3:before { + content: "\f13c"; +} +.fa-anchor:before { + content: "\f13d"; +} +.fa-unlock-alt:before { + content: "\f13e"; +} +.fa-bullseye:before { + content: "\f140"; +} +.fa-ellipsis-h:before { + content: "\f141"; +} +.fa-ellipsis-v:before { + content: "\f142"; +} +.fa-rss-square:before { + content: "\f143"; +} +.fa-play-circle:before { + content: "\f144"; +} +.fa-ticket:before { + content: "\f145"; +} +.fa-minus-square:before { + content: "\f146"; +} +.fa-minus-square-o:before { + content: "\f147"; +} +.fa-level-up:before { + content: "\f148"; +} +.fa-level-down:before { + content: "\f149"; +} +.fa-check-square:before { + content: "\f14a"; +} +.fa-pencil-square:before { + content: "\f14b"; +} +.fa-external-link-square:before { + content: "\f14c"; +} +.fa-share-square:before { + content: "\f14d"; +} +.fa-compass:before { + content: "\f14e"; +} +.fa-toggle-down:before, +.fa-caret-square-o-down:before { + content: "\f150"; +} +.fa-toggle-up:before, +.fa-caret-square-o-up:before { + content: "\f151"; +} +.fa-toggle-right:before, +.fa-caret-square-o-right:before { + content: "\f152"; +} +.fa-euro:before, +.fa-eur:before { + content: "\f153"; +} +.fa-gbp:before { + content: "\f154"; +} +.fa-dollar:before, +.fa-usd:before { + content: "\f155"; +} +.fa-rupee:before, +.fa-inr:before { + content: "\f156"; +} +.fa-cny:before, +.fa-rmb:before, +.fa-yen:before, +.fa-jpy:before { + content: "\f157"; +} +.fa-ruble:before, +.fa-rouble:before, +.fa-rub:before { + content: "\f158"; +} +.fa-won:before, +.fa-krw:before { + content: "\f159"; +} +.fa-bitcoin:before, +.fa-btc:before { + content: "\f15a"; +} +.fa-file:before { + content: "\f15b"; +} +.fa-file-text:before { + content: "\f15c"; +} +.fa-sort-alpha-asc:before { + content: "\f15d"; +} +.fa-sort-alpha-desc:before { + content: "\f15e"; +} +.fa-sort-amount-asc:before { + content: "\f160"; +} +.fa-sort-amount-desc:before { + content: "\f161"; +} +.fa-sort-numeric-asc:before { + content: "\f162"; +} +.fa-sort-numeric-desc:before { + content: "\f163"; +} +.fa-thumbs-up:before { + content: "\f164"; +} +.fa-thumbs-down:before { + content: "\f165"; +} +.fa-youtube-square:before { + content: "\f166"; +} +.fa-youtube:before { + content: "\f167"; +} +.fa-xing:before { + content: "\f168"; +} +.fa-xing-square:before { + content: "\f169"; +} +.fa-youtube-play:before { + content: "\f16a"; +} +.fa-dropbox:before { + content: "\f16b"; +} +.fa-stack-overflow:before { + content: "\f16c"; +} +.fa-instagram:before { + content: "\f16d"; +} +.fa-flickr:before { + content: "\f16e"; +} +.fa-adn:before { + content: "\f170"; +} +.fa-bitbucket:before { + content: "\f171"; +} +.fa-bitbucket-square:before { + content: "\f172"; +} +.fa-tumblr:before { + content: "\f173"; +} +.fa-tumblr-square:before { + content: "\f174"; +} +.fa-long-arrow-down:before { + content: "\f175"; +} +.fa-long-arrow-up:before { + content: "\f176"; +} +.fa-long-arrow-left:before { + content: "\f177"; +} +.fa-long-arrow-right:before { + content: "\f178"; +} +.fa-apple:before { + content: "\f179"; +} +.fa-windows:before { + content: "\f17a"; +} +.fa-android:before { + content: "\f17b"; +} +.fa-linux:before { + content: "\f17c"; +} +.fa-dribbble:before { + content: "\f17d"; +} +.fa-skype:before { + content: "\f17e"; +} +.fa-foursquare:before { + content: "\f180"; +} +.fa-trello:before { + content: "\f181"; +} +.fa-female:before { + content: "\f182"; +} +.fa-male:before { + content: "\f183"; +} +.fa-gittip:before, +.fa-gratipay:before { + content: "\f184"; +} +.fa-sun-o:before { + content: "\f185"; +} +.fa-moon-o:before { + content: "\f186"; +} +.fa-archive:before { + content: "\f187"; +} +.fa-bug:before { + content: "\f188"; +} +.fa-vk:before { + content: "\f189"; +} +.fa-weibo:before { + content: "\f18a"; +} +.fa-renren:before { + content: "\f18b"; +} +.fa-pagelines:before { + content: "\f18c"; +} +.fa-stack-exchange:before { + content: "\f18d"; +} +.fa-arrow-circle-o-right:before { + content: "\f18e"; +} +.fa-arrow-circle-o-left:before { + content: "\f190"; +} +.fa-toggle-left:before, +.fa-caret-square-o-left:before { + content: "\f191"; +} +.fa-dot-circle-o:before { + content: "\f192"; +} +.fa-wheelchair:before { + content: "\f193"; +} +.fa-vimeo-square:before { + content: "\f194"; +} +.fa-turkish-lira:before, +.fa-try:before { + content: "\f195"; +} +.fa-plus-square-o:before { + content: "\f196"; +} +.fa-space-shuttle:before { + content: "\f197"; +} +.fa-slack:before { + content: "\f198"; +} +.fa-envelope-square:before { + content: "\f199"; +} +.fa-wordpress:before { + content: "\f19a"; +} +.fa-openid:before { + content: "\f19b"; +} +.fa-institution:before, +.fa-bank:before, +.fa-university:before { + content: "\f19c"; +} +.fa-mortar-board:before, +.fa-graduation-cap:before { + content: "\f19d"; +} +.fa-yahoo:before { + content: "\f19e"; +} +.fa-google:before { + content: "\f1a0"; +} +.fa-reddit:before { + content: "\f1a1"; +} +.fa-reddit-square:before { + content: "\f1a2"; +} +.fa-stumbleupon-circle:before { + content: "\f1a3"; +} +.fa-stumbleupon:before { + content: "\f1a4"; +} +.fa-delicious:before { + content: "\f1a5"; +} +.fa-digg:before { + content: "\f1a6"; +} +.fa-pied-piper:before { + content: "\f1a7"; +} +.fa-pied-piper-alt:before { + content: "\f1a8"; +} +.fa-drupal:before { + content: "\f1a9"; +} +.fa-joomla:before { + content: "\f1aa"; +} +.fa-language:before { + content: "\f1ab"; +} +.fa-fax:before { + content: "\f1ac"; +} +.fa-building:before { + content: "\f1ad"; +} +.fa-child:before { + content: "\f1ae"; +} +.fa-paw:before { + content: "\f1b0"; +} +.fa-spoon:before { + content: "\f1b1"; +} +.fa-cube:before { + content: "\f1b2"; +} +.fa-cubes:before { + content: "\f1b3"; +} +.fa-behance:before { + content: "\f1b4"; +} +.fa-behance-square:before { + content: "\f1b5"; +} +.fa-steam:before { + content: "\f1b6"; +} +.fa-steam-square:before { + content: "\f1b7"; +} +.fa-recycle:before { + content: "\f1b8"; +} +.fa-automobile:before, +.fa-car:before { + content: "\f1b9"; +} +.fa-cab:before, +.fa-taxi:before { + content: "\f1ba"; +} +.fa-tree:before { + content: "\f1bb"; +} +.fa-spotify:before { + content: "\f1bc"; +} +.fa-deviantart:before { + content: "\f1bd"; +} +.fa-soundcloud:before { + content: "\f1be"; +} +.fa-database:before { + content: "\f1c0"; +} +.fa-file-pdf-o:before { + content: "\f1c1"; +} +.fa-file-word-o:before { + content: "\f1c2"; +} +.fa-file-excel-o:before { + content: "\f1c3"; +} +.fa-file-powerpoint-o:before { + content: "\f1c4"; +} +.fa-file-photo-o:before, +.fa-file-picture-o:before, +.fa-file-image-o:before { + content: "\f1c5"; +} +.fa-file-zip-o:before, +.fa-file-archive-o:before { + content: "\f1c6"; +} +.fa-file-sound-o:before, +.fa-file-audio-o:before { + content: "\f1c7"; +} +.fa-file-movie-o:before, +.fa-file-video-o:before { + content: "\f1c8"; +} +.fa-file-code-o:before { + content: "\f1c9"; +} +.fa-vine:before { + content: "\f1ca"; +} +.fa-codepen:before { + content: "\f1cb"; +} +.fa-jsfiddle:before { + content: "\f1cc"; +} +.fa-life-bouy:before, +.fa-life-buoy:before, +.fa-life-saver:before, +.fa-support:before, +.fa-life-ring:before { + content: "\f1cd"; +} +.fa-circle-o-notch:before { + content: "\f1ce"; +} +.fa-ra:before, +.fa-rebel:before { + content: "\f1d0"; +} +.fa-ge:before, +.fa-empire:before { + content: "\f1d1"; +} +.fa-git-square:before { + content: "\f1d2"; +} +.fa-git:before { + content: "\f1d3"; +} +.fa-hacker-news:before { + content: "\f1d4"; +} +.fa-tencent-weibo:before { + content: "\f1d5"; +} +.fa-qq:before { + content: "\f1d6"; +} +.fa-wechat:before, +.fa-weixin:before { + content: "\f1d7"; +} +.fa-send:before, +.fa-paper-plane:before { + content: "\f1d8"; +} +.fa-send-o:before, +.fa-paper-plane-o:before { + content: "\f1d9"; +} +.fa-history:before { + content: "\f1da"; +} +.fa-genderless:before, +.fa-circle-thin:before { + content: "\f1db"; +} +.fa-header:before { + content: "\f1dc"; +} +.fa-paragraph:before { + content: "\f1dd"; +} +.fa-sliders:before { + content: "\f1de"; +} +.fa-share-alt:before { + content: "\f1e0"; +} +.fa-share-alt-square:before { + content: "\f1e1"; +} +.fa-bomb:before { + content: "\f1e2"; +} +.fa-soccer-ball-o:before, +.fa-futbol-o:before { + content: "\f1e3"; +} +.fa-tty:before { + content: "\f1e4"; +} +.fa-binoculars:before { + content: "\f1e5"; +} +.fa-plug:before { + content: "\f1e6"; +} +.fa-slideshare:before { + content: "\f1e7"; +} +.fa-twitch:before { + content: "\f1e8"; +} +.fa-yelp:before { + content: "\f1e9"; +} +.fa-newspaper-o:before { + content: "\f1ea"; +} +.fa-wifi:before { + content: "\f1eb"; +} +.fa-calculator:before { + content: "\f1ec"; +} +.fa-paypal:before { + content: "\f1ed"; +} +.fa-google-wallet:before { + content: "\f1ee"; +} +.fa-cc-visa:before { + content: "\f1f0"; +} +.fa-cc-mastercard:before { + content: "\f1f1"; +} +.fa-cc-discover:before { + content: "\f1f2"; +} +.fa-cc-amex:before { + content: "\f1f3"; +} +.fa-cc-paypal:before { + content: "\f1f4"; +} +.fa-cc-stripe:before { + content: "\f1f5"; +} +.fa-bell-slash:before { + content: "\f1f6"; +} +.fa-bell-slash-o:before { + content: "\f1f7"; +} +.fa-trash:before { + content: "\f1f8"; +} +.fa-copyright:before { + content: "\f1f9"; +} +.fa-at:before { + content: "\f1fa"; +} +.fa-eyedropper:before { + content: "\f1fb"; +} +.fa-paint-brush:before { + content: "\f1fc"; +} +.fa-birthday-cake:before { + content: "\f1fd"; +} +.fa-area-chart:before { + content: "\f1fe"; +} +.fa-pie-chart:before { + content: "\f200"; +} +.fa-line-chart:before { + content: "\f201"; +} +.fa-lastfm:before { + content: "\f202"; +} +.fa-lastfm-square:before { + content: "\f203"; +} +.fa-toggle-off:before { + content: "\f204"; +} +.fa-toggle-on:before { + content: "\f205"; +} +.fa-bicycle:before { + content: "\f206"; +} +.fa-bus:before { + content: "\f207"; +} +.fa-ioxhost:before { + content: "\f208"; +} +.fa-angellist:before { + content: "\f209"; +} +.fa-cc:before { + content: "\f20a"; +} +.fa-shekel:before, +.fa-sheqel:before, +.fa-ils:before { + content: "\f20b"; +} +.fa-meanpath:before { + content: "\f20c"; +} +.fa-buysellads:before { + content: "\f20d"; +} +.fa-connectdevelop:before { + content: "\f20e"; +} +.fa-dashcube:before { + content: "\f210"; +} +.fa-forumbee:before { + content: "\f211"; +} +.fa-leanpub:before { + content: "\f212"; +} +.fa-sellsy:before { + content: "\f213"; +} +.fa-shirtsinbulk:before { + content: "\f214"; +} +.fa-simplybuilt:before { + content: "\f215"; +} +.fa-skyatlas:before { + content: "\f216"; +} +.fa-cart-plus:before { + content: "\f217"; +} +.fa-cart-arrow-down:before { + content: "\f218"; +} +.fa-diamond:before { + content: "\f219"; +} +.fa-ship:before { + content: "\f21a"; +} +.fa-user-secret:before { + content: "\f21b"; +} +.fa-motorcycle:before { + content: "\f21c"; +} +.fa-street-view:before { + content: "\f21d"; +} +.fa-heartbeat:before { + content: "\f21e"; +} +.fa-venus:before { + content: "\f221"; +} +.fa-mars:before { + content: "\f222"; +} +.fa-mercury:before { + content: "\f223"; +} +.fa-transgender:before { + content: "\f224"; +} +.fa-transgender-alt:before { + content: "\f225"; +} +.fa-venus-double:before { + content: "\f226"; +} +.fa-mars-double:before { + content: "\f227"; +} +.fa-venus-mars:before { + content: "\f228"; +} +.fa-mars-stroke:before { + content: "\f229"; +} +.fa-mars-stroke-v:before { + content: "\f22a"; +} +.fa-mars-stroke-h:before { + content: "\f22b"; +} +.fa-neuter:before { + content: "\f22c"; +} +.fa-facebook-official:before { + content: "\f230"; +} +.fa-pinterest-p:before { + content: "\f231"; +} +.fa-whatsapp:before { + content: "\f232"; +} +.fa-server:before { + content: "\f233"; +} +.fa-user-plus:before { + content: "\f234"; +} +.fa-user-times:before { + content: "\f235"; +} +.fa-hotel:before, +.fa-bed:before { + content: "\f236"; +} +.fa-viacoin:before { + content: "\f237"; +} +.fa-train:before { + content: "\f238"; +} +.fa-subway:before { + content: "\f239"; +} +.fa-medium:before { + content: "\f23a"; +} diff --git a/css/fontawesome-webfont.woff2 b/css/fontawesome-webfont.woff2 new file mode 100644 index 000000000..3311d5851 Binary files /dev/null and b/css/fontawesome-webfont.woff2 differ diff --git a/css/import.css b/css/import.css new file mode 100644 index 000000000..3c3654e25 --- /dev/null +++ b/css/import.css @@ -0,0 +1,116 @@ +::-webkit-scrollbar { + width: 10px; + background: #EEE; +} + +::-webkit-scrollbar-thumb { + background-color: #AAA; + border: 2px solid #EEE; + border-radius: 5px; +} + +[v-cloak] { display: none } + +* { + font-family: arial, 'Microsoft YaHei'; +} + +#authenticator { + width: 600px; + position: relative; + margin: 0 auto; +} + +.import_tab { + text-align: center; + font-size: 0; +} + +.import_tab input { + display: none; +} + +.import_tab label { + width: 250px; + height: 50px; + font-size: 18px; + text-align: center; + display: inline-grid; + align-items: center; + margin: 20px; + cursor: pointer; + border-radius: 2px; +} + +.import_tab input:checked + label, +.import_tab label:hover { + background: #eee; +} + +.import_file { + text-align: center; +} + +.import_file input { + display: none; +} + +button, +.import_file label { + display: inline-grid; + width: 260px; + height: 60px; + border: #CCC 1px solid; + background: white; + border-radius: 2px; + position: relative; + text-align: center; + align-items: center; + font-size: 16px; + color: gray; + cursor: pointer; + outline: none; +} + +button:hover, +.import_file label:hover { + color: black; +} + +.import_encrypted { + margin-bottom: 20px; +} + +.import_encrypted input { + margin-left: 0; +} + +.import_code { + float: left; + margin-left: 30px; + margin-right: 40px; +} + +.import_code textarea { + width: 250px; + height: 400px; + padding: 10px; + outline: none; + resize: none; + box-sizing: border-box; +} + +.import_passphrase input { + padding: 10px; + margin-bottom: 20px; + width: 250px; + border: #CCC 1px solid; + background: white; + outline: none; +} + +.error_password { + font-size: 18px; + color: gray; + text-align: center; +} diff --git a/css/popup.css b/css/popup.css new file mode 100644 index 000000000..7dd3e018e --- /dev/null +++ b/css/popup.css @@ -0,0 +1,859 @@ +@font-face { + font-family: 'Droid Sans Mono'; + font-style: normal; + font-weight: 400; + src: url(DroidSansMono.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000; +} + +@keyframes twinkling{ + 0%{ + color:#DD4B39; + } + 100%{ + color:#EEA59C; + } +} + +@keyframes fadeshow{ + 0%{ + opacity:0; + } + 100%{ + opacity:1; + } +} + +@keyframes fadehide{ + 0%{ + opacity:1; + } + 100%{ + opacity:0; + } +} + +@keyframes fadein{ + 0%{ + opacity:0; + top:110px; + } + 100%{ + opacity:1; + top:10px; + } +} + +@keyframes fadeout{ + 0%{ + opacity:1; + top:10px; + } + 100%{ + opacity:0; + top:110px; + } +} + +@keyframes slidein{ + 0%{ + opacity:0; + left:-55px; + } + 100%{ + opacity:1; + left:0; + } +} + +@keyframes slideout{ + 0%{ + opacity:1; + left:0; + } + 100%{ + opacity:0; + left:-55px; + } +} + +@keyframes qrfadein{ + 0%{ + opacity:0; + } + 100%{ + opacity:1; + } +} + +@keyframes qrfadeout{ + 0%{ + opacity:1; + } + 100%{ + opacity:0; + } +} + +::-webkit-scrollbar { + width: 10px; + background: #EEE; +} + +::-webkit-scrollbar-thumb { + background-color: #AAA; + border: 2px solid #EEE; + border-radius: 5px; +} + +[v-cloak] { display: none } + +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +a { + color: #08C; +} + +body { + width: 320px; + height: 480px; + overflow: hidden; + font-family: arial, 'Microsoft YaHei'; + cursor: default; + user-select: none; + transform-origin: left top; +} + +#header, +#menuHead { + height: 38px; + line-height: 38px; + position: relative; + text-align: center; + font-size: 16px; + border-bottom: #CCC 1px solid; + user-select: none; + -moz-user-select: none; +} + +#notification { + position: absolute; + left: 60px; + top: -1000px; + width: 200px; + height: 60px; + line-height: 60px; + text-align: center; + background: rgba(0,0,0,0.5); + color: #FFF; + font-size: 20px; + border-radius: 2px; +} + +#notification.fadein { + top: 190px; + animation: fadeshow 0.2s 1 ease-out; +} + +#notification.fadeout { + top: 190px; + animation: fadehide 0.2s 1 ease-in; +} + +#codes { + height: 442px; + overflow-x: hidden; + overflow-y: hidden; + background: #EEE; + padding-right:10px; +} + +#codes:hover { + padding-right: 0; + overflow-y: scroll; +} + +#codeClipboard { + position: absolute; + top: -1000px; +} + +.entry { + margin: 10px; + margin-right: 0; + padding: 10px; + border: #CCC 1px solid; + background: white; + border-radius: 2px; + position: relative; +} + +.entry[unencrypted="true"] .warning { + position: absolute; + height: 0; + line-height: 12px; + font-size: 12px; + padding: 0 10px; + margin: 0 4px; + width: 250px; + bottom: 4px; + left: 0; + background: #EC6959; + color: #FFF; + cursor: pointer; + overflow: hidden; + border-radius: 2px; + transition: height 0.2s; +} + +#codes.filter .entry[filtered] { + display: none; +} + +#filter { + background: #fff4cc; + padding: 0 10px; + margin-left: 10px; + font-size: 12px; + height: 24px; + line-height: 24px; + cursor: pointer; + display: none; +} + +#filter:hover { + background: #fff1ba; +} + +#codes.filter #filter { + display: block; +} + +#codes:not(.edit) .entry[unencrypted="true"]:hover .warning { + height: 24px; +} + +.entry[dropOver="true"] { + border: gray 1px dashed; +} + +.issuer { + font-size: 12px; + color: black; + width: 80%; + text-overflow: ellipsis; + overflow: hidden; +} + +.code { + font-size: 36px; + color: #08C; + width: 80%; + user-select: text; + font-family: 'Droid Sans Mono'; + cursor: pointer; +} + +#codes.edit .code { + color: #CCC!important; + user-select: none; + cursor: default; +} + +#codes.edit .account, +#codes.edit .issuer { + display: none; +} + +.accountEdit, +.issuerEdit { + display: none; +} + +.accountEdit input, +.issuerEdit input { + border: none; + height: 14px; + width: 70%; + font-size: 12px; + font-family: arial, 'Microsoft YaHei'; + outline: none; + background: #eee; +} + +#codes.edit .accountEdit, +#codes.edit .issuerEdit { + display: block; +} + +#codes.timeout .code:not(.hotp) { + animation: twinkling 1s infinite ease-in-out; +} + +.hotp { + color: #555; + cursor: default; +} + +.hotp:not(.no-copy) { + color: #08C; + cursor: pointer; +} + +.movehandle { + height: 98px; + line-height: 98px; + right: 10px; + top: 0; + position: absolute; + font-size: 24px; + color: #CCC; + cursor: move; + display: none; +} + +#codes.edit .movehandle { + display: block; +} + +.showqr { + right: 10px; + top: 10px; + position: absolute; + font-size: 20px; + color: #CCC; + cursor: pointer; + opacity: 0; +} + +.entry:hover .showqr { + opacity: 1; +} + +#codes.edit .showqr, +.showqr.hidden { + display: none; +} + +.account { + font-size: 12px; + color: gray; + width: 80%; + text-overflow: ellipsis; + overflow: hidden; +} + +#add, +#add_qr, +#add_secret, +#add_button, +#download_backup, +#import_backup, +#upload_backup, +#security_save, +#passphrase_ok, +#dropbox_ok, +#message_close, +#exportButton, +#resize_save { + margin: 10px; + padding: 20px; + border: #CCC 1px solid; + background: white; + border-radius: 2px; + position: relative; + text-align: center; + font-size: 16px; + color: gray; + cursor: pointer; +} + +.buttons { + text-align: center; +} + +#confirm_ok, +#confirm_cancel { + display: inline-block; + margin: 10px; + padding: 5px 20px; + border: #CCC 1px solid; + background: white; + border-radius: 2px; + position: relative; + text-align: center; + font-size: 16px; + color: gray; + cursor: pointer; +} + +#add { + margin-right: 0; +} + +#message_close, +#add_button, +#exportButton, +#security_save, +#passphrase_ok, +#dropbox_ok, +#resize_save { + font-size: 12px; + margin: 20px 100px; + padding: 10px; + cursor: pointer; +} + +#codes #add { + font-size: 16px; + line-height: 56px; + display: none; +} + +#codes.edit #add { + display: block; +} + +#codes .deleteAction { + font-size: 20px; + color: #DD4B39; + position: absolute; + top: -10px; + left: -10px; + z-index: 10; + display: none; +} + +#codes.edit .deleteAction { + display: block; + cursor: pointer; +} + +#infoAction { + position: absolute; + left: 20px; + bottom: 0; + height: 38px; + line-height: 38px; + font-size: 16px; + color: gray; + cursor: pointer; +} + +#infoAction.hidden { + display: none; +} + +#dropbox { + position: absolute; + left: 50px; + bottom: 0; + height: 38px; + line-height: 38px; + font-size: 16px; + color: #ccc; +} + +#editAction { + position: absolute; + right: 20px; + bottom: 0; + height: 38px; + line-height: 38px; + font-size: 16px; + color: gray; + cursor: pointer; +} + +#scan { + position: absolute; + right: 50px; + bottom: 0; + height: 38px; + line-height: 41px; + font-size: 16px; + color: gray; + cursor: pointer; +} + +.counter { + color: #888; + font-size: 18px; + text-align: center; + cursor: pointer; +} + +.counter:not(.disabled):hover { + color: #000; +} + +.counter.disabled { + color: #CCC; + cursor: default; +} + +.sector, +.counter { + width: 20px; + height: 20px; + position: absolute; + right: 10px; + bottom: 10px; +} + +#codes.edit .sector, +#codes.edit .counter { + display: none; +} + +#menu { + width: 320px; + height: 480px; + position: absolute; + left: -1000px; + top: 0; +} + +#menuBody { + overflow-y: auto; + height: 442px; + width: inherit; + background: #EEE; + position: absolute; +} + +#menu.slidein { + left: 0; + animation: slidein 0.2s 1 ease-out; + opacity: 1; +} + +#menu.slideout { + left: -55px; + animation: slideout 0.2s 1 ease-in; + opacity: 0; +} + +#menuHead { + background: #FFF; +} + +#menu .menuList { + margin: 10px; + border: #CCC 1px solid; + border-radius: 2px; + background: #FFF; +} + +#menu .menuList p { + position: relative; + border-bottom: #CCC 1px solid; + padding: 10px; + font-size: 16px; + color: gray; + cursor: pointer; + display: grid; + grid-template-columns: 30px auto; +} + +#menu .menuList p:hover { + background: #F4FCFF; + color: black; +} + + +#menu .menuList p:last-child { + border-bottom: none; +} + +#menu .menuList p a { + color: gray; + text-decoration: none; + display: line-block; +} + +#menu .menuList p i.fa { + font-size: 14px; + display: line-block; + width: 30px; + display: flex; + align-items: center; +} + +#version { + text-align: center; + color: gray; + margin: 10px; +} + +#info { + position: absolute; + height: 460px; + width: 300px; + padding: 10px; + border: gray; + background: white; + left: 10px; + top: -1000px; + box-shadow: 1px 1px 3px gray; + z-index: 100; +} + +#info.fadein { + top: 10px; + animation: fadein 0.2s 1 ease-out; +} + +#info.fadeout { + top: 110px; + animation: fadeout 0.2s 1 ease-in; +} + +#infoClose { + height: 20px; + width: 20px; + font-size: 14px; + color: gray; + cursor: pointer; +} + +#menuClose { + position: absolute; + height: 38px; + line-height: 38px; + left: 20px; + font-size: 16px; + color: gray; + bottom: 0; + cursor: pointer; +} + +#menuClose:hover, +#exportButton:hover, +#message_close:hover, +#add_button:hover, +#add_secret:hover, +#add_qr:hover, +#upload_backup:hover, +#download_backup:hover, +#import_backup:hover, +#editAction:hover, +#infoAction:hover, +#scan:hover, +#codes #add:hover, +#infoClose:hover, +#addAccountClose:hover, +#securityClose:hover, +#passphraseClose:hover, +#security_save:hover, +#passphrase_ok:hover, +#dropbox_ok:hover, +#export:hover, +#resizeClose:hover, +#resize_save:hover, +#confirm_cancel:hover, +#confirm_ok:hover, +#menu .menuList p:hover:after, +.entry:hover .movehandle, +.showqr:hover { + color: black; +} + +#infoContent, +#addAccountContent, +#exportContent { + height: 420px; + overflow-y: auto; + overflow-x: hidden; +} + +#exportData { + height: 320px; + width: 100%; + word-break: break-all; + resize: none; + outline: none; +} + +#infoContent p { + font-size: 12px; + margin-bottom: 20px; +} + +#qr { + width: 100%; + height: 100%; + top: -1000px; + left: 0; + position: absolute; + z-index: 10; + background-color: rgba(0, 0, 0, 0.5); + background-repeat: no-repeat; + background-position: center; +} + +#qr canvas { + display: none; +} + +#qr.qrfadein { + top: 0; + animation: qrfadein 0.2s 1 ease-out; +} + +#qr.qrfadeout { + top: 0; + animation: qrfadeout 0.2s 1 ease-in; +} + +#dropbox_box input, +#secret_box input, +#security input, +#passphrase input { + display: block; + margin: 0 10px 10px 10px; + padding: 10px; + width: 260px; + border: #CCC 1px solid; + background: white; + outline: none; +} + +#dropbox_box input:disabled { + background: #eee; + cursor: not-allowed; +} + +.checkbox_group input[type="checkbox"], +.radio_group input[type="radio"] { + display: inline-block !important; + width: auto !important; +} + +.checkbox_group label, +.radio_group label { + display: inline-block !important; + margin-left: 0 !important; +} + +#secret_box select { + margin: 20px; + font-size: 12px; + padding: 5px; +} + +#dropbox_box label, +#secret_box label, +#security label, +#passphrase label, +#security_warning, +#dropbox_risk, +#export_info, +#passphrase_info { + display: block; + margin: 10px 0 0 10px; +} + +#security_warning, +#export_info, +#dropbox_risk, +#passphrase_info { + color: gray; +} + +#resize_list_label, +#resize_list { + margin: 20px; + font-size: 16px; +} + +#message, +#confirm { + position: absolute; + width: 300px; + padding: 10px; + border: gray 1px solid; + border-radius: 2px; + background: white; + left: 10px; + top: 150px; + box-shadow: 1px 1px 3px gray; + z-index: 1000; +} + +#download_backup, +#import_backup { + text-decoration: none; + color: gray; + display: block; +} + +#import_file { + display: none; +} + +#upload_backup { + display: block; +} + +.gu-mirror { + display: none; +} + +.no-copy { + cursor: default; +} + +#dropbox_box .dropbox_code_input { + width: 260px; + margin: 0 10px 10px 10px; + border: #CCC 1px solid; + background: white; + font-size: 0; + height: 42px; + display: grid; + grid-template-columns: auto auto; +} + +#dropbox_box .dropbox_code_input input { + border: none; + margin: 0; + font-size: 12px; + width: 188px; + display: inline-block; + height: 40px; + padding: 0px 0px 0px 10px; + vertical-align: top; +} + +#dropbox_authorization { + display: inline-flex; + font-size: 12px; + border-left: 1px solid #ccc; + padding: 3px; + text-decoration: none; + text-align: center; + overflow: hidden; + vertical-align: top; + margin: 7px 0; + align-items: center; + padding-left: 5px; + color: gray; +} + +#dropbox_authorization:hover { + color: black; +} + +#overlay { + position: absolute; + width: 100%; + height: 100%; + top: 0; + left: 0; + z-index: 900; +} diff --git a/ensureDir.js b/ensureDir.js new file mode 100644 index 000000000..42fa5e182 --- /dev/null +++ b/ensureDir.js @@ -0,0 +1,18 @@ +const fs = require('fs-extra'); +const path = require('path'); +const argv = process.argv; +if (argv.length < 2) { + console.log('No path specific.'); + process.exit(); +} + +const pathName = argv[2]; + +try { + const absolutePath = path.join(__dirname, pathName); + fs.emptyDirSync(absolutePath); + process.exit(); +} catch(error) { + console.error(error); + process.exit(); +} diff --git a/images/icon128.png b/images/icon128.png new file mode 100644 index 000000000..6a4a18e36 Binary files /dev/null and b/images/icon128.png differ diff --git a/images/icon16.png b/images/icon16.png new file mode 100644 index 000000000..fe84e4249 Binary files /dev/null and b/images/icon16.png differ diff --git a/images/icon19.png b/images/icon19.png new file mode 100644 index 000000000..e3335f57a Binary files /dev/null and b/images/icon19.png differ diff --git a/images/icon38.png b/images/icon38.png new file mode 100644 index 000000000..7d5174b4b Binary files /dev/null and b/images/icon38.png differ diff --git a/images/icon48.png b/images/icon48.png new file mode 100644 index 000000000..059a7ccc2 Binary files /dev/null and b/images/icon48.png differ diff --git a/images/scan.gif b/images/scan.gif new file mode 100644 index 000000000..ae5698b01 Binary files /dev/null and b/images/scan.gif differ diff --git a/import.html b/import.html new file mode 100644 index 000000000..41b132853 --- /dev/null +++ b/import.html @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + + + +
+
+ + +
+
+
+ +
+
+ + +
+
+ + +
+ +
+
+
{{ i18n.import_error_password }}
+
+ + + + + + + + + + + + + diff --git a/js/aes.js b/js/aes.js new file mode 100644 index 000000000..827503cbd --- /dev/null +++ b/js/aes.js @@ -0,0 +1,35 @@ +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +var CryptoJS=CryptoJS||function(u,p){var d={},l=d.lib={},s=function(){},t=l.Base={extend:function(a){s.prototype=this;var c=new s;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}, +r=l.WordArray=t.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=p?c:4*a.length},toString:function(a){return(a||v).stringify(this)},concat:function(a){var c=this.words,e=a.words,j=this.sigBytes;a=a.sigBytes;this.clamp();if(j%4)for(var k=0;k>>2]|=(e[k>>>2]>>>24-8*(k%4)&255)<<24-8*((j+k)%4);else if(65535>>2]=e[k>>>2];else c.push.apply(c,e);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< +32-8*(c%4);a.length=u.ceil(c/4)},clone:function(){var a=t.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],e=0;e>>2]>>>24-8*(j%4)&255;e.push((k>>>4).toString(16));e.push((k&15).toString(16))}return e.join("")},parse:function(a){for(var c=a.length,e=[],j=0;j>>3]|=parseInt(a.substr(j, +2),16)<<24-4*(j%8);return new r.init(e,c/2)}},b=w.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var e=[],j=0;j>>2]>>>24-8*(j%4)&255));return e.join("")},parse:function(a){for(var c=a.length,e=[],j=0;j>>2]|=(a.charCodeAt(j)&255)<<24-8*(j%4);return new r.init(e,c)}},x=w.Utf8={stringify:function(a){try{return decodeURIComponent(escape(b.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return b.parse(unescape(encodeURIComponent(a)))}}, +q=l.BufferedBlockAlgorithm=t.extend({reset:function(){this._data=new r.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=x.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,e=c.words,j=c.sigBytes,k=this.blockSize,b=j/(4*k),b=a?u.ceil(b):u.max((b|0)-this._minBufferSize,0);a=b*k;j=u.min(4*a,j);if(a){for(var q=0;q>>2]>>>24-8*(r%4)&255)<<16|(l[r+1>>>2]>>>24-8*((r+1)%4)&255)<<8|l[r+2>>>2]>>>24-8*((r+2)%4)&255,v=0;4>v&&r+0.75*v>>6*(3-v)&63));if(l=t.charAt(64))for(;d.length%4;)d.push(l);return d.join("")},parse:function(d){var l=d.length,s=this._map,t=s.charAt(64);t&&(t=d.indexOf(t),-1!=t&&(l=t));for(var t=[],r=0,w=0;w< +l;w++)if(w%4){var v=s.indexOf(d.charAt(w-1))<<2*(w%4),b=s.indexOf(d.charAt(w))>>>6-2*(w%4);t[r>>>2]|=(v|b)<<24-8*(r%4);r++}return p.create(t,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})(); +(function(u){function p(b,n,a,c,e,j,k){b=b+(n&a|~n&c)+e+k;return(b<>>32-j)+n}function d(b,n,a,c,e,j,k){b=b+(n&c|a&~c)+e+k;return(b<>>32-j)+n}function l(b,n,a,c,e,j,k){b=b+(n^a^c)+e+k;return(b<>>32-j)+n}function s(b,n,a,c,e,j,k){b=b+(a^(n|~c))+e+k;return(b<>>32-j)+n}for(var t=CryptoJS,r=t.lib,w=r.WordArray,v=r.Hasher,r=t.algo,b=[],x=0;64>x;x++)b[x]=4294967296*u.abs(u.sin(x+1))|0;r=r.MD5=v.extend({_doReset:function(){this._hash=new w.init([1732584193,4023233417,2562383102,271733878])}, +_doProcessBlock:function(q,n){for(var a=0;16>a;a++){var c=n+a,e=q[c];q[c]=(e<<8|e>>>24)&16711935|(e<<24|e>>>8)&4278255360}var a=this._hash.words,c=q[n+0],e=q[n+1],j=q[n+2],k=q[n+3],z=q[n+4],r=q[n+5],t=q[n+6],w=q[n+7],v=q[n+8],A=q[n+9],B=q[n+10],C=q[n+11],u=q[n+12],D=q[n+13],E=q[n+14],x=q[n+15],f=a[0],m=a[1],g=a[2],h=a[3],f=p(f,m,g,h,c,7,b[0]),h=p(h,f,m,g,e,12,b[1]),g=p(g,h,f,m,j,17,b[2]),m=p(m,g,h,f,k,22,b[3]),f=p(f,m,g,h,z,7,b[4]),h=p(h,f,m,g,r,12,b[5]),g=p(g,h,f,m,t,17,b[6]),m=p(m,g,h,f,w,22,b[7]), +f=p(f,m,g,h,v,7,b[8]),h=p(h,f,m,g,A,12,b[9]),g=p(g,h,f,m,B,17,b[10]),m=p(m,g,h,f,C,22,b[11]),f=p(f,m,g,h,u,7,b[12]),h=p(h,f,m,g,D,12,b[13]),g=p(g,h,f,m,E,17,b[14]),m=p(m,g,h,f,x,22,b[15]),f=d(f,m,g,h,e,5,b[16]),h=d(h,f,m,g,t,9,b[17]),g=d(g,h,f,m,C,14,b[18]),m=d(m,g,h,f,c,20,b[19]),f=d(f,m,g,h,r,5,b[20]),h=d(h,f,m,g,B,9,b[21]),g=d(g,h,f,m,x,14,b[22]),m=d(m,g,h,f,z,20,b[23]),f=d(f,m,g,h,A,5,b[24]),h=d(h,f,m,g,E,9,b[25]),g=d(g,h,f,m,k,14,b[26]),m=d(m,g,h,f,v,20,b[27]),f=d(f,m,g,h,D,5,b[28]),h=d(h,f, +m,g,j,9,b[29]),g=d(g,h,f,m,w,14,b[30]),m=d(m,g,h,f,u,20,b[31]),f=l(f,m,g,h,r,4,b[32]),h=l(h,f,m,g,v,11,b[33]),g=l(g,h,f,m,C,16,b[34]),m=l(m,g,h,f,E,23,b[35]),f=l(f,m,g,h,e,4,b[36]),h=l(h,f,m,g,z,11,b[37]),g=l(g,h,f,m,w,16,b[38]),m=l(m,g,h,f,B,23,b[39]),f=l(f,m,g,h,D,4,b[40]),h=l(h,f,m,g,c,11,b[41]),g=l(g,h,f,m,k,16,b[42]),m=l(m,g,h,f,t,23,b[43]),f=l(f,m,g,h,A,4,b[44]),h=l(h,f,m,g,u,11,b[45]),g=l(g,h,f,m,x,16,b[46]),m=l(m,g,h,f,j,23,b[47]),f=s(f,m,g,h,c,6,b[48]),h=s(h,f,m,g,w,10,b[49]),g=s(g,h,f,m, +E,15,b[50]),m=s(m,g,h,f,r,21,b[51]),f=s(f,m,g,h,u,6,b[52]),h=s(h,f,m,g,k,10,b[53]),g=s(g,h,f,m,B,15,b[54]),m=s(m,g,h,f,e,21,b[55]),f=s(f,m,g,h,v,6,b[56]),h=s(h,f,m,g,x,10,b[57]),g=s(g,h,f,m,t,15,b[58]),m=s(m,g,h,f,D,21,b[59]),f=s(f,m,g,h,z,6,b[60]),h=s(h,f,m,g,C,10,b[61]),g=s(g,h,f,m,j,15,b[62]),m=s(m,g,h,f,A,21,b[63]);a[0]=a[0]+f|0;a[1]=a[1]+m|0;a[2]=a[2]+g|0;a[3]=a[3]+h|0},_doFinalize:function(){var b=this._data,n=b.words,a=8*this._nDataBytes,c=8*b.sigBytes;n[c>>>5]|=128<<24-c%32;var e=u.floor(a/ +4294967296);n[(c+64>>>9<<4)+15]=(e<<8|e>>>24)&16711935|(e<<24|e>>>8)&4278255360;n[(c+64>>>9<<4)+14]=(a<<8|a>>>24)&16711935|(a<<24|a>>>8)&4278255360;b.sigBytes=4*(n.length+1);this._process();b=this._hash;n=b.words;for(a=0;4>a;a++)c=n[a],n[a]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360;return b},clone:function(){var b=v.clone.call(this);b._hash=this._hash.clone();return b}});t.MD5=v._createHelper(r);t.HmacMD5=v._createHmacHelper(r)})(Math); +(function(){var u=CryptoJS,p=u.lib,d=p.Base,l=p.WordArray,p=u.algo,s=p.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:p.MD5,iterations:1}),init:function(d){this.cfg=this.cfg.extend(d)},compute:function(d,r){for(var p=this.cfg,s=p.hasher.create(),b=l.create(),u=b.words,q=p.keySize,p=p.iterations;u.length>>2]&255}};d.BlockCipher=v.extend({cfg:v.cfg.extend({mode:b,padding:q}),reset:function(){v.reset.call(this);var a=this.cfg,b=a.iv,a=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var c=a.createEncryptor;else c=a.createDecryptor,this._minBufferSize=1;this._mode=c.call(a, +this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else b=this._process(!0),a.unpad(b);return b},blockSize:4});var n=d.CipherParams=l.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}}),b=(p.format={}).OpenSSL={stringify:function(a){var b=a.ciphertext;a=a.salt;return(a?s.create([1398893684, +1701076831]).concat(a).concat(b):b).toString(r)},parse:function(a){a=r.parse(a);var b=a.words;if(1398893684==b[0]&&1701076831==b[1]){var c=s.create(b.slice(2,4));b.splice(0,4);a.sigBytes-=16}return n.create({ciphertext:a,salt:c})}},a=d.SerializableCipher=l.extend({cfg:l.extend({format:b}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var l=a.createEncryptor(c,d);b=l.finalize(b);l=l.cfg;return n.create({ciphertext:b,key:c,iv:l.iv,algorithm:a,mode:l.mode,padding:l.padding,blockSize:a.blockSize,formatter:d.format})}, +decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);return a.createDecryptor(c,d).finalize(b.ciphertext)},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),p=(p.kdf={}).OpenSSL={execute:function(a,b,c,d){d||(d=s.random(8));a=w.create({keySize:b+c}).compute(a,d);c=s.create(a.words.slice(b),4*c);a.sigBytes=4*b;return n.create({key:a,iv:c,salt:d})}},c=d.PasswordBasedCipher=a.extend({cfg:a.cfg.extend({kdf:p}),encrypt:function(b,c,d,l){l=this.cfg.extend(l);d=l.kdf.execute(d, +b.keySize,b.ivSize);l.iv=d.iv;b=a.encrypt.call(this,b,c,d.key,l);b.mixIn(d);return b},decrypt:function(b,c,d,l){l=this.cfg.extend(l);c=this._parse(c,l.format);d=l.kdf.execute(d,b.keySize,b.ivSize,c.salt);l.iv=d.iv;return a.decrypt.call(this,b,c,d.key,l)}})}(); +(function(){for(var u=CryptoJS,p=u.lib.BlockCipher,d=u.algo,l=[],s=[],t=[],r=[],w=[],v=[],b=[],x=[],q=[],n=[],a=[],c=0;256>c;c++)a[c]=128>c?c<<1:c<<1^283;for(var e=0,j=0,c=0;256>c;c++){var k=j^j<<1^j<<2^j<<3^j<<4,k=k>>>8^k&255^99;l[e]=k;s[k]=e;var z=a[e],F=a[z],G=a[F],y=257*a[k]^16843008*k;t[e]=y<<24|y>>>8;r[e]=y<<16|y>>>16;w[e]=y<<8|y>>>24;v[e]=y;y=16843009*G^65537*F^257*z^16843008*e;b[k]=y<<24|y>>>8;x[k]=y<<16|y>>>16;q[k]=y<<8|y>>>24;n[k]=y;e?(e=z^a[a[a[G^z]]],j^=a[a[j]]):e=j=1}var H=[0,1,2,4,8, +16,32,64,128,27,54],d=d.AES=p.extend({_doReset:function(){for(var a=this._key,c=a.words,d=a.sigBytes/4,a=4*((this._nRounds=d+6)+1),e=this._keySchedule=[],j=0;j>>24]<<24|l[k>>>16&255]<<16|l[k>>>8&255]<<8|l[k&255]):(k=k<<8|k>>>24,k=l[k>>>24]<<24|l[k>>>16&255]<<16|l[k>>>8&255]<<8|l[k&255],k^=H[j/d|0]<<24);e[j]=e[j-d]^k}c=this._invKeySchedule=[];for(d=0;dd||4>=j?k:b[l[k>>>24]]^x[l[k>>>16&255]]^q[l[k>>> +8&255]]^n[l[k&255]]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,t,r,w,v,l)},decryptBlock:function(a,c){var d=a[c+1];a[c+1]=a[c+3];a[c+3]=d;this._doCryptBlock(a,c,this._invKeySchedule,b,x,q,n,s);d=a[c+1];a[c+1]=a[c+3];a[c+3]=d},_doCryptBlock:function(a,b,c,d,e,j,l,f){for(var m=this._nRounds,g=a[b]^c[0],h=a[b+1]^c[1],k=a[b+2]^c[2],n=a[b+3]^c[3],p=4,r=1;r>>24]^e[h>>>16&255]^j[k>>>8&255]^l[n&255]^c[p++],s=d[h>>>24]^e[k>>>16&255]^j[n>>>8&255]^l[g&255]^c[p++],t= +d[k>>>24]^e[n>>>16&255]^j[g>>>8&255]^l[h&255]^c[p++],n=d[n>>>24]^e[g>>>16&255]^j[h>>>8&255]^l[k&255]^c[p++],g=q,h=s,k=t;q=(f[g>>>24]<<24|f[h>>>16&255]<<16|f[k>>>8&255]<<8|f[n&255])^c[p++];s=(f[h>>>24]<<24|f[k>>>16&255]<<16|f[n>>>8&255]<<8|f[g&255])^c[p++];t=(f[k>>>24]<<24|f[n>>>16&255]<<16|f[g>>>8&255]<<8|f[h&255])^c[p++];n=(f[n>>>24]<<24|f[g>>>16&255]<<16|f[h>>>8&255]<<8|f[k&255])^c[p++];a[b]=q;a[b+1]=s;a[b+2]=t;a[b+3]=n},keySize:8});u.AES=p._createHelper(d)})(); diff --git a/js/import.js b/js/import.js new file mode 100644 index 000000000..8beb28690 --- /dev/null +++ b/js/import.js @@ -0,0 +1 @@ +document.title = chrome.i18n.getMessage('import_backup'); \ No newline at end of file diff --git a/js/jsqrcode/COPYING b/js/jsqrcode/COPYING new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/js/jsqrcode/COPYING @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/js/jsqrcode/alignpat.js b/js/jsqrcode/alignpat.js new file mode 100644 index 000000000..967473f39 --- /dev/null +++ b/js/jsqrcode/alignpat.js @@ -0,0 +1,279 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +function AlignmentPattern(posX, posY, estimatedModuleSize) +{ + this.x=posX; + this.y=posY; + this.count = 1; + this.estimatedModuleSize = estimatedModuleSize; + + this.__defineGetter__("EstimatedModuleSize", function() + { + return this.estimatedModuleSize; + }); + this.__defineGetter__("Count", function() + { + return this.count; + }); + this.__defineGetter__("X", function() + { + return Math.floor(this.x); + }); + this.__defineGetter__("Y", function() + { + return Math.floor(this.y); + }); + this.incrementCount = function() + { + this.count++; + } + this.aboutEquals=function( moduleSize, i, j) + { + if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize) + { + var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize); + return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0; + } + return false; + } + +} + +function AlignmentPatternFinder( image, startX, startY, width, height, moduleSize, resultPointCallback) +{ + this.image = image; + this.possibleCenters = new Array(); + this.startX = startX; + this.startY = startY; + this.width = width; + this.height = height; + this.moduleSize = moduleSize; + this.crossCheckStateCount = new Array(0,0,0); + this.resultPointCallback = resultPointCallback; + + this.centerFromEnd=function(stateCount, end) + { + return (end - stateCount[2]) - stateCount[1] / 2.0; + } + this.foundPatternCross = function(stateCount) + { + var moduleSize = this.moduleSize; + var maxVariance = moduleSize / 2.0; + for (var i = 0; i < 3; i++) + { + if (Math.abs(moduleSize - stateCount[i]) >= maxVariance) + { + return false; + } + } + return true; + } + + this.crossCheckVertical=function( startI, centerJ, maxCount, originalStateCountTotal) + { + var image = this.image; + + var maxI = qrcode.height; + var stateCount = this.crossCheckStateCount; + stateCount[0] = 0; + stateCount[1] = 0; + stateCount[2] = 0; + + // Start counting up from center + var i = startI; + while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[1] <= maxCount) + { + stateCount[1]++; + i--; + } + // If already too many modules in this state or ran off the edge: + if (i < 0 || stateCount[1] > maxCount) + { + return NaN; + } + while (i >= 0 && !image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount) + { + stateCount[0]++; + i--; + } + if (stateCount[0] > maxCount) + { + return NaN; + } + + // Now also count down from center + i = startI + 1; + while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[1] <= maxCount) + { + stateCount[1]++; + i++; + } + if (i == maxI || stateCount[1] > maxCount) + { + return NaN; + } + while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[2] <= maxCount) + { + stateCount[2]++; + i++; + } + if (stateCount[2] > maxCount) + { + return NaN; + } + + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; + if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) + { + return NaN; + } + + return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN; + } + + this.handlePossibleCenter=function( stateCount, i, j) + { + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; + var centerJ = this.centerFromEnd(stateCount, j); + var centerI = this.crossCheckVertical(i, Math.floor (centerJ), 2 * stateCount[1], stateCountTotal); + if (!isNaN(centerI)) + { + var estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0; + var max = this.possibleCenters.length; + for (var index = 0; index < max; index++) + { + var center = this.possibleCenters[index]; + // Look for about the same center and module size: + if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) + { + return new AlignmentPattern(centerJ, centerI, estimatedModuleSize); + } + } + // Hadn't found this before; save it + var point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize); + this.possibleCenters.push(point); + if (this.resultPointCallback != null) + { + this.resultPointCallback.foundPossibleResultPoint(point); + } + } + return null; + } + + this.find = function() + { + var startX = this.startX; + var height = this.height; + var maxJ = startX + width; + var middleI = startY + (height >> 1); + // We are looking for black/white/black modules in 1:1:1 ratio; + // this tracks the number of black/white/black modules seen so far + var stateCount = new Array(0,0,0); + for (var iGen = 0; iGen < height; iGen++) + { + // Search from middle outwards + var i = middleI + ((iGen & 0x01) == 0?((iGen + 1) >> 1):- ((iGen + 1) >> 1)); + stateCount[0] = 0; + stateCount[1] = 0; + stateCount[2] = 0; + var j = startX; + // Burn off leading white pixels before anything else; if we start in the middle of + // a white run, it doesn't make sense to count its length, since we don't know if the + // white run continued to the left of the start point + while (j < maxJ && !image[j + qrcode.width* i]) + { + j++; + } + var currentState = 0; + while (j < maxJ) + { + if (image[j + i*qrcode.width]) + { + // Black pixel + if (currentState == 1) + { + // Counting black pixels + stateCount[currentState]++; + } + else + { + // Counting white pixels + if (currentState == 2) + { + // A winner? + if (this.foundPatternCross(stateCount)) + { + // Yes + var confirmed = this.handlePossibleCenter(stateCount, i, j); + if (confirmed != null) + { + return confirmed; + } + } + stateCount[0] = stateCount[2]; + stateCount[1] = 1; + stateCount[2] = 0; + currentState = 1; + } + else + { + stateCount[++currentState]++; + } + } + } + else + { + // White pixel + if (currentState == 1) + { + // Counting black pixels + currentState++; + } + stateCount[currentState]++; + } + j++; + } + if (this.foundPatternCross(stateCount)) + { + var confirmed = this.handlePossibleCenter(stateCount, i, maxJ); + if (confirmed != null) + { + return confirmed; + } + } + } + + // Hmm, nothing we saw was observed and confirmed twice. If we had + // any guess at all, return it. + if (!(this.possibleCenters.length == 0)) + { + return this.possibleCenters[0]; + } + + throw "Couldn't find enough alignment patterns"; + } + +} \ No newline at end of file diff --git a/js/jsqrcode/bitmat.js b/js/jsqrcode/bitmat.js new file mode 100644 index 000000000..5b0078429 --- /dev/null +++ b/js/jsqrcode/bitmat.js @@ -0,0 +1,111 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +function BitMatrix( width, height) +{ + if(!height) + height=width; + if (width < 1 || height < 1) + { + throw "Both dimensions must be greater than 0"; + } + this.width = width; + this.height = height; + var rowSize = width >> 5; + if ((width & 0x1f) != 0) + { + rowSize++; + } + this.rowSize = rowSize; + this.bits = new Array(rowSize * height); + for(var i=0;i> 5); + return ((URShift(this.bits[offset], (x & 0x1f))) & 1) != 0; + } + this.set_Renamed=function( x, y) + { + var offset = y * this.rowSize + (x >> 5); + this.bits[offset] |= 1 << (x & 0x1f); + } + this.flip=function( x, y) + { + var offset = y * this.rowSize + (x >> 5); + this.bits[offset] ^= 1 << (x & 0x1f); + } + this.clear=function() + { + var max = this.bits.length; + for (var i = 0; i < max; i++) + { + this.bits[i] = 0; + } + } + this.setRegion=function( left, top, width, height) + { + if (top < 0 || left < 0) + { + throw "Left and top must be nonnegative"; + } + if (height < 1 || width < 1) + { + throw "Height and width must be at least 1"; + } + var right = left + width; + var bottom = top + height; + if (bottom > this.height || right > this.width) + { + throw "The region must fit inside the matrix"; + } + for (var y = top; y < bottom; y++) + { + var offset = y * this.rowSize; + for (var x = left; x < right; x++) + { + this.bits[offset + (x >> 5)] |= 1 << (x & 0x1f); + } + } + } +} \ No newline at end of file diff --git a/js/jsqrcode/bmparser.js b/js/jsqrcode/bmparser.js new file mode 100644 index 000000000..51c6e85dd --- /dev/null +++ b/js/jsqrcode/bmparser.js @@ -0,0 +1,203 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +function BitMatrixParser(bitMatrix) +{ + var dimension = bitMatrix.Dimension; + if (dimension < 21 || (dimension & 0x03) != 1) + { + throw "Error BitMatrixParser"; + } + this.bitMatrix = bitMatrix; + this.parsedVersion = null; + this.parsedFormatInfo = null; + + this.copyBit=function( i, j, versionBits) + { + return this.bitMatrix.get_Renamed(i, j)?(versionBits << 1) | 0x1:versionBits << 1; + } + + this.readFormatInformation=function() + { + if (this.parsedFormatInfo != null) + { + return this.parsedFormatInfo; + } + + // Read top-left format info bits + var formatInfoBits = 0; + for (var i = 0; i < 6; i++) + { + formatInfoBits = this.copyBit(i, 8, formatInfoBits); + } + // .. and skip a bit in the timing pattern ... + formatInfoBits = this.copyBit(7, 8, formatInfoBits); + formatInfoBits = this.copyBit(8, 8, formatInfoBits); + formatInfoBits = this.copyBit(8, 7, formatInfoBits); + // .. and skip a bit in the timing pattern ... + for (var j = 5; j >= 0; j--) + { + formatInfoBits = this.copyBit(8, j, formatInfoBits); + } + + this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); + if (this.parsedFormatInfo != null) + { + return this.parsedFormatInfo; + } + + // Hmm, failed. Try the top-right/bottom-left pattern + var dimension = this.bitMatrix.Dimension; + formatInfoBits = 0; + var iMin = dimension - 8; + for (var i = dimension - 1; i >= iMin; i--) + { + formatInfoBits = this.copyBit(i, 8, formatInfoBits); + } + for (var j = dimension - 7; j < dimension; j++) + { + formatInfoBits = this.copyBit(8, j, formatInfoBits); + } + + this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); + if (this.parsedFormatInfo != null) + { + return this.parsedFormatInfo; + } + throw "Error readFormatInformation"; + } + this.readVersion=function() + { + + if (this.parsedVersion != null) + { + return this.parsedVersion; + } + + var dimension = this.bitMatrix.Dimension; + + var provisionalVersion = (dimension - 17) >> 2; + if (provisionalVersion <= 6) + { + return Version.getVersionForNumber(provisionalVersion); + } + + // Read top-right version info: 3 wide by 6 tall + var versionBits = 0; + var ijMin = dimension - 11; + for (var j = 5; j >= 0; j--) + { + for (var i = dimension - 9; i >= ijMin; i--) + { + versionBits = this.copyBit(i, j, versionBits); + } + } + + this.parsedVersion = Version.decodeVersionInformation(versionBits); + if (this.parsedVersion != null && this.parsedVersion.DimensionForVersion == dimension) + { + return this.parsedVersion; + } + + // Hmm, failed. Try bottom left: 6 wide by 3 tall + versionBits = 0; + for (var i = 5; i >= 0; i--) + { + for (var j = dimension - 9; j >= ijMin; j--) + { + versionBits = this.copyBit(i, j, versionBits); + } + } + + this.parsedVersion = Version.decodeVersionInformation(versionBits); + if (this.parsedVersion != null && this.parsedVersion.DimensionForVersion == dimension) + { + return this.parsedVersion; + } + throw "Error readVersion"; + } + this.readCodewords=function() + { + + var formatInfo = this.readFormatInformation(); + var version = this.readVersion(); + + // Get the data mask for the format used in this QR Code. This will exclude + // some bits from reading as we wind through the bit matrix. + var dataMask = DataMask.forReference( formatInfo.DataMask); + var dimension = this.bitMatrix.Dimension; + dataMask.unmaskBitMatrix(this.bitMatrix, dimension); + + var functionPattern = version.buildFunctionPattern(); + + var readingUp = true; + var result = new Array(version.TotalCodewords); + var resultOffset = 0; + var currentByte = 0; + var bitsRead = 0; + // Read columns in pairs, from right to left + for (var j = dimension - 1; j > 0; j -= 2) + { + if (j == 6) + { + // Skip whole column with vertical alignment pattern; + // saves time and makes the other code proceed more cleanly + j--; + } + // Read alternatingly from bottom to top then top to bottom + for (var count = 0; count < dimension; count++) + { + var i = readingUp?dimension - 1 - count:count; + for (var col = 0; col < 2; col++) + { + // Ignore bits covered by the function pattern + if (!functionPattern.get_Renamed(j - col, i)) + { + // Read a bit + bitsRead++; + currentByte <<= 1; + if (this.bitMatrix.get_Renamed(j - col, i)) + { + currentByte |= 1; + } + // If we've made a whole byte, save it off + if (bitsRead == 8) + { + result[resultOffset++] = currentByte; + bitsRead = 0; + currentByte = 0; + } + } + } + } + readingUp ^= true; // readingUp = !readingUp; // switch directions + } + if (resultOffset != version.TotalCodewords) + { + throw "Error readCodewords"; + } + return result; + } +} \ No newline at end of file diff --git a/js/jsqrcode/datablock.js b/js/jsqrcode/datablock.js new file mode 100644 index 000000000..3cb277a89 --- /dev/null +++ b/js/jsqrcode/datablock.js @@ -0,0 +1,117 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +function DataBlock(numDataCodewords, codewords) +{ + this.numDataCodewords = numDataCodewords; + this.codewords = codewords; + + this.__defineGetter__("NumDataCodewords", function() + { + return this.numDataCodewords; + }); + this.__defineGetter__("Codewords", function() + { + return this.codewords; + }); +} + +DataBlock.getDataBlocks=function(rawCodewords, version, ecLevel) +{ + + if (rawCodewords.length != version.TotalCodewords) + { + throw "ArgumentException"; + } + + // Figure out the number and size of data blocks used by this version and + // error correction level + var ecBlocks = version.getECBlocksForLevel(ecLevel); + + // First count the total number of data blocks + var totalBlocks = 0; + var ecBlockArray = ecBlocks.getECBlocks(); + for (var i = 0; i < ecBlockArray.length; i++) + { + totalBlocks += ecBlockArray[i].Count; + } + + // Now establish DataBlocks of the appropriate size and number of data codewords + var result = new Array(totalBlocks); + var numResultBlocks = 0; + for (var j = 0; j < ecBlockArray.length; j++) + { + var ecBlock = ecBlockArray[j]; + for (var i = 0; i < ecBlock.Count; i++) + { + var numDataCodewords = ecBlock.DataCodewords; + var numBlockCodewords = ecBlocks.ECCodewordsPerBlock + numDataCodewords; + result[numResultBlocks++] = new DataBlock(numDataCodewords, new Array(numBlockCodewords)); + } + } + + // All blocks have the same amount of data, except that the last n + // (where n may be 0) have 1 more byte. Figure out where these start. + var shorterBlocksTotalCodewords = result[0].codewords.length; + var longerBlocksStartAt = result.length - 1; + while (longerBlocksStartAt >= 0) + { + var numCodewords = result[longerBlocksStartAt].codewords.length; + if (numCodewords == shorterBlocksTotalCodewords) + { + break; + } + longerBlocksStartAt--; + } + longerBlocksStartAt++; + + var shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.ECCodewordsPerBlock; + // The last elements of result may be 1 element longer; + // first fill out as many elements as all of them have + var rawCodewordsOffset = 0; + for (var i = 0; i < shorterBlocksNumDataCodewords; i++) + { + for (var j = 0; j < numResultBlocks; j++) + { + result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; + } + } + // Fill out the last data block in the longer ones + for (var j = longerBlocksStartAt; j < numResultBlocks; j++) + { + result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++]; + } + // Now add in error correction blocks + var max = result[0].codewords.length; + for (var i = shorterBlocksNumDataCodewords; i < max; i++) + { + for (var j = 0; j < numResultBlocks; j++) + { + var iOffset = j < longerBlocksStartAt?i:i + 1; + result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; + } + } + return result; +} diff --git a/js/jsqrcode/databr.js b/js/jsqrcode/databr.js new file mode 100644 index 000000000..66279c41d --- /dev/null +++ b/js/jsqrcode/databr.js @@ -0,0 +1,325 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +function QRCodeDataBlockReader(blocks, version, numErrorCorrectionCode) +{ + this.blockPointer = 0; + this.bitPointer = 7; + this.dataLength = 0; + this.blocks = blocks; + this.numErrorCorrectionCode = numErrorCorrectionCode; + if (version <= 9) + this.dataLengthMode = 0; + else if (version >= 10 && version <= 26) + this.dataLengthMode = 1; + else if (version >= 27 && version <= 40) + this.dataLengthMode = 2; + + this.getNextBits = function( numBits) + { + var bits = 0; + if (numBits < this.bitPointer + 1) + { + // next word fits into current data block + var mask = 0; + for (var i = 0; i < numBits; i++) + { + mask += (1 << i); + } + mask <<= (this.bitPointer - numBits + 1); + + bits = (this.blocks[this.blockPointer] & mask) >> (this.bitPointer - numBits + 1); + this.bitPointer -= numBits; + return bits; + } + else if (numBits < this.bitPointer + 1 + 8) + { + // next word crosses 2 data blocks + var mask1 = 0; + for (var i = 0; i < this.bitPointer + 1; i++) + { + mask1 += (1 << i); + } + bits = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1)); + this.blockPointer++; + bits += ((this.blocks[this.blockPointer]) >> (8 - (numBits - (this.bitPointer + 1)))); + + this.bitPointer = this.bitPointer - numBits % 8; + if (this.bitPointer < 0) + { + this.bitPointer = 8 + this.bitPointer; + } + return bits; + } + else if (numBits < this.bitPointer + 1 + 16) + { + // next word crosses 3 data blocks + var mask1 = 0; // mask of first block + var mask3 = 0; // mask of 3rd block + //bitPointer + 1 : number of bits of the 1st block + //8 : number of the 2nd block (note that use already 8bits because next word uses 3 data blocks) + //numBits - (bitPointer + 1 + 8) : number of bits of the 3rd block + for (var i = 0; i < this.bitPointer + 1; i++) + { + mask1 += (1 << i); + } + var bitsFirstBlock = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1)); + this.blockPointer++; + + var bitsSecondBlock = this.blocks[this.blockPointer] << (numBits - (this.bitPointer + 1 + 8)); + this.blockPointer++; + + for (var i = 0; i < numBits - (this.bitPointer + 1 + 8); i++) + { + mask3 += (1 << i); + } + mask3 <<= 8 - (numBits - (this.bitPointer + 1 + 8)); + var bitsThirdBlock = (this.blocks[this.blockPointer] & mask3) >> (8 - (numBits - (this.bitPointer + 1 + 8))); + + bits = bitsFirstBlock + bitsSecondBlock + bitsThirdBlock; + this.bitPointer = this.bitPointer - (numBits - 8) % 8; + if (this.bitPointer < 0) + { + this.bitPointer = 8 + this.bitPointer; + } + return bits; + } + else + { + return 0; + } + } + this.NextMode=function() + { + if ((this.blockPointer > this.blocks.length - this.numErrorCorrectionCode - 2)) + return 0; + else + return this.getNextBits(4); + } + this.getDataLength=function( modeIndicator) + { + var index = 0; + while (true) + { + if ((modeIndicator >> index) == 1) + break; + index++; + } + + return this.getNextBits(qrcode.sizeOfDataLengthInfo[this.dataLengthMode][index]); + } + this.getRomanAndFigureString=function( dataLength) + { + var length = dataLength; + var intData = 0; + var strData = ""; + var tableRomanAndFigure = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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', ' ', '$', '%', '*', '+', '-', '.', '/', ':'); + do + { + if (length > 1) + { + intData = this.getNextBits(11); + var firstLetter = Math.floor(intData / 45); + var secondLetter = intData % 45; + strData += tableRomanAndFigure[firstLetter]; + strData += tableRomanAndFigure[secondLetter]; + length -= 2; + } + else if (length == 1) + { + intData = this.getNextBits(6); + strData += tableRomanAndFigure[intData]; + length -= 1; + } + } + while (length > 0); + + return strData; + } + this.getFigureString=function( dataLength) + { + var length = dataLength; + var intData = 0; + var strData = ""; + do + { + if (length >= 3) + { + intData = this.getNextBits(10); + if (intData < 100) + strData += "0"; + if (intData < 10) + strData += "0"; + length -= 3; + } + else if (length == 2) + { + intData = this.getNextBits(7); + if (intData < 10) + strData += "0"; + length -= 2; + } + else if (length == 1) + { + intData = this.getNextBits(4); + length -= 1; + } + strData += intData; + } + while (length > 0); + + return strData; + } + this.get8bitByteArray=function( dataLength) + { + var length = dataLength; + var intData = 0; + var output = new Array(); + + do + { + intData = this.getNextBits(8); + output.push( intData); + length--; + } + while (length > 0); + return output; + } + this.getKanjiString=function( dataLength) + { + var length = dataLength; + var intData = 0; + var unicodeString = ""; + do + { + intData = getNextBits(13); + var lowerByte = intData % 0xC0; + var higherByte = intData / 0xC0; + + var tempWord = (higherByte << 8) + lowerByte; + var shiftjisWord = 0; + if (tempWord + 0x8140 <= 0x9FFC) + { + // between 8140 - 9FFC on Shift_JIS character set + shiftjisWord = tempWord + 0x8140; + } + else + { + // between E040 - EBBF on Shift_JIS character set + shiftjisWord = tempWord + 0xC140; + } + + //var tempByte = new Array(0,0); + //tempByte[0] = (sbyte) (shiftjisWord >> 8); + //tempByte[1] = (sbyte) (shiftjisWord & 0xFF); + //unicodeString += new String(SystemUtils.ToCharArray(SystemUtils.ToByteArray(tempByte))); + unicodeString += String.fromCharCode(shiftjisWord); + length--; + } + while (length > 0); + + + return unicodeString; + } + + this.__defineGetter__("DataByte", function() + { + var output = new Array(); + var MODE_NUMBER = 1; + var MODE_ROMAN_AND_NUMBER = 2; + var MODE_8BIT_BYTE = 4; + var MODE_KANJI = 8; + do + { + var mode = this.NextMode(); + //canvas.println("mode: " + mode); + if (mode == 0) + { + if (output.length > 0) + break; + else + throw "Empty data block"; + } + //if (mode != 1 && mode != 2 && mode != 4 && mode != 8) + // break; + //} + if (mode != MODE_NUMBER && mode != MODE_ROMAN_AND_NUMBER && mode != MODE_8BIT_BYTE && mode != MODE_KANJI) + { + /* canvas.println("Invalid mode: " + mode); + mode = guessMode(mode); + canvas.println("Guessed mode: " + mode); */ + throw "Invalid mode: " + mode + " in (block:" + this.blockPointer + " bit:" + this.bitPointer + ")"; + } + dataLength = this.getDataLength(mode); + if (dataLength < 1) + throw "Invalid data length: " + dataLength; + //canvas.println("length: " + dataLength); + switch (mode) + { + + case MODE_NUMBER: + //canvas.println("Mode: Figure"); + var temp_str = this.getFigureString(dataLength); + var ta = new Array(temp_str.length); + for(var j=0;j 7) + { + throw "System.ArgumentException"; + } + return DataMask.DATA_MASKS[reference]; +} + +function DataMask000() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return ((i + j) & 0x01) == 0; + } +} + +function DataMask001() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return (i & 0x01) == 0; + } +} + +function DataMask010() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return j % 3 == 0; + } +} + +function DataMask011() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return (i + j) % 3 == 0; + } +} + +function DataMask100() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return (((URShift(i, 1)) + (j / 3)) & 0x01) == 0; + } +} + +function DataMask101() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + var temp = i * j; + return (temp & 0x01) + (temp % 3) == 0; + } +} + +function DataMask110() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + var temp = i * j; + return (((temp & 0x01) + (temp % 3)) & 0x01) == 0; + } +} +function DataMask111() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return ((((i + j) & 0x01) + ((i * j) % 3)) & 0x01) == 0; + } +} + +DataMask.DATA_MASKS = new Array(new DataMask000(), new DataMask001(), new DataMask010(), new DataMask011(), new DataMask100(), new DataMask101(), new DataMask110(), new DataMask111()); + diff --git a/js/jsqrcode/decoder.js b/js/jsqrcode/decoder.js new file mode 100644 index 000000000..58467c3d5 --- /dev/null +++ b/js/jsqrcode/decoder.js @@ -0,0 +1,95 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +Decoder={}; +Decoder.rsDecoder = new ReedSolomonDecoder(GF256.QR_CODE_FIELD); + +Decoder.correctErrors=function( codewordBytes, numDataCodewords) +{ + var numCodewords = codewordBytes.length; + // First read into an array of ints + var codewordsInts = new Array(numCodewords); + for (var i = 0; i < numCodewords; i++) + { + codewordsInts[i] = codewordBytes[i] & 0xFF; + } + var numECCodewords = codewordBytes.length - numDataCodewords; + try + { + Decoder.rsDecoder.decode(codewordsInts, numECCodewords); + //var corrector = new ReedSolomon(codewordsInts, numECCodewords); + //corrector.correct(); + } + catch ( rse) + { + throw rse; + } + // Copy back into array of bytes -- only need to worry about the bytes that were data + // We don't care about errors in the error-correction codewords + for (var i = 0; i < numDataCodewords; i++) + { + codewordBytes[i] = codewordsInts[i]; + } +} + +Decoder.decode=function(bits) +{ + var parser = new BitMatrixParser(bits); + var version = parser.readVersion(); + var ecLevel = parser.readFormatInformation().ErrorCorrectionLevel; + + // Read codewords + var codewords = parser.readCodewords(); + + // Separate into data blocks + var dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel); + + // Count total number of data bytes + var totalBytes = 0; + for (var i = 0; i < dataBlocks.length; i++) + { + totalBytes += dataBlocks[i].NumDataCodewords; + } + var resultBytes = new Array(totalBytes); + var resultOffset = 0; + + // Error-correct and copy data blocks together into a stream of bytes + for (var j = 0; j < dataBlocks.length; j++) + { + var dataBlock = dataBlocks[j]; + var codewordBytes = dataBlock.Codewords; + var numDataCodewords = dataBlock.NumDataCodewords; + Decoder.correctErrors(codewordBytes, numDataCodewords); + for (var i = 0; i < numDataCodewords; i++) + { + resultBytes[resultOffset++] = codewordBytes[i]; + } + } + + // Decode the contents of that stream of bytes + var reader = new QRCodeDataBlockReader(resultBytes, version.VersionNumber, ecLevel.Bits); + return reader; + //return DecodedBitStreamParser.decode(resultBytes, version, ecLevel); +} diff --git a/js/jsqrcode/detector.js b/js/jsqrcode/detector.js new file mode 100644 index 000000000..012f8c5d1 --- /dev/null +++ b/js/jsqrcode/detector.js @@ -0,0 +1,413 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +function PerspectiveTransform( a11, a21, a31, a12, a22, a32, a13, a23, a33) +{ + this.a11 = a11; + this.a12 = a12; + this.a13 = a13; + this.a21 = a21; + this.a22 = a22; + this.a23 = a23; + this.a31 = a31; + this.a32 = a32; + this.a33 = a33; + this.transformPoints1=function( points) + { + var max = points.length; + var a11 = this.a11; + var a12 = this.a12; + var a13 = this.a13; + var a21 = this.a21; + var a22 = this.a22; + var a23 = this.a23; + var a31 = this.a31; + var a32 = this.a32; + var a33 = this.a33; + for (var i = 0; i < max; i += 2) + { + var x = points[i]; + var y = points[i + 1]; + var denominator = a13 * x + a23 * y + a33; + points[i] = (a11 * x + a21 * y + a31) / denominator; + points[i + 1] = (a12 * x + a22 * y + a32) / denominator; + } + } + this. transformPoints2=function(xValues, yValues) + { + var n = xValues.length; + for (var i = 0; i < n; i++) + { + var x = xValues[i]; + var y = yValues[i]; + var denominator = this.a13 * x + this.a23 * y + this.a33; + xValues[i] = (this.a11 * x + this.a21 * y + this.a31) / denominator; + yValues[i] = (this.a12 * x + this.a22 * y + this.a32) / denominator; + } + } + + this.buildAdjoint=function() + { + // Adjoint is the transpose of the cofactor matrix: + return new PerspectiveTransform(this.a22 * this.a33 - this.a23 * this.a32, this.a23 * this.a31 - this.a21 * this.a33, this.a21 * this.a32 - this.a22 * this.a31, this.a13 * this.a32 - this.a12 * this.a33, this.a11 * this.a33 - this.a13 * this.a31, this.a12 * this.a31 - this.a11 * this.a32, this.a12 * this.a23 - this.a13 * this.a22, this.a13 * this.a21 - this.a11 * this.a23, this.a11 * this.a22 - this.a12 * this.a21); + } + this.times=function( other) + { + return new PerspectiveTransform(this.a11 * other.a11 + this.a21 * other.a12 + this.a31 * other.a13, this.a11 * other.a21 + this.a21 * other.a22 + this.a31 * other.a23, this.a11 * other.a31 + this.a21 * other.a32 + this.a31 * other.a33, this.a12 * other.a11 + this.a22 * other.a12 + this.a32 * other.a13, this.a12 * other.a21 + this.a22 * other.a22 + this.a32 * other.a23, this.a12 * other.a31 + this.a22 * other.a32 + this.a32 * other.a33, this.a13 * other.a11 + this.a23 * other.a12 +this.a33 * other.a13, this.a13 * other.a21 + this.a23 * other.a22 + this.a33 * other.a23, this.a13 * other.a31 + this.a23 * other.a32 + this.a33 * other.a33); + } + +} + +PerspectiveTransform.quadrilateralToQuadrilateral=function( x0, y0, x1, y1, x2, y2, x3, y3, x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p) +{ + + var qToS = this.quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); + var sToQ = this.squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); + return sToQ.times(qToS); +} + +PerspectiveTransform.squareToQuadrilateral=function( x0, y0, x1, y1, x2, y2, x3, y3) +{ + dy2 = y3 - y2; + dy3 = y0 - y1 + y2 - y3; + if (dy2 == 0.0 && dy3 == 0.0) + { + return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0, 0.0, 1.0); + } + else + { + dx1 = x1 - x2; + dx2 = x3 - x2; + dx3 = x0 - x1 + x2 - x3; + dy1 = y1 - y2; + denominator = dx1 * dy2 - dx2 * dy1; + a13 = (dx3 * dy2 - dx2 * dy3) / denominator; + a23 = (dx1 * dy3 - dx3 * dy1) / denominator; + return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0); + } +} + +PerspectiveTransform.quadrilateralToSquare=function( x0, y0, x1, y1, x2, y2, x3, y3) +{ + // Here, the adjoint serves as the inverse: + return this.squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint(); +} + +function DetectorResult(bits, points) +{ + this.bits = bits; + this.points = points; +} + + +function Detector(image) +{ + this.image=image; + this.resultPointCallback = null; + + this.sizeOfBlackWhiteBlackRun=function( fromX, fromY, toX, toY) + { + // Mild variant of Bresenham's algorithm; + // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm + var steep = Math.abs(toY - fromY) > Math.abs(toX - fromX); + if (steep) + { + var temp = fromX; + fromX = fromY; + fromY = temp; + temp = toX; + toX = toY; + toY = temp; + } + + var dx = Math.abs(toX - fromX); + var dy = Math.abs(toY - fromY); + var error = - dx >> 1; + var ystep = fromY < toY?1:- 1; + var xstep = fromX < toX?1:- 1; + var state = 0; // In black pixels, looking for white, first or second time + for (var x = fromX, y = fromY; x != toX; x += xstep) + { + + var realX = steep?y:x; + var realY = steep?x:y; + if (state == 1) + { + // In white pixels, looking for black + if (this.image[realX + realY*qrcode.width]) + { + state++; + } + } + else + { + if (!this.image[realX + realY*qrcode.width]) + { + state++; + } + } + + if (state == 3) + { + // Found black, white, black, and stumbled back onto white; done + var diffX = x - fromX; + var diffY = y - fromY; + return Math.sqrt( (diffX * diffX + diffY * diffY)); + } + error += dy; + if (error > 0) + { + if (y == toY) + { + break; + } + y += ystep; + error -= dx; + } + } + var diffX2 = toX - fromX; + var diffY2 = toY - fromY; + return Math.sqrt( (diffX2 * diffX2 + diffY2 * diffY2)); + } + + + this.sizeOfBlackWhiteBlackRunBothWays=function( fromX, fromY, toX, toY) + { + + var result = this.sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); + + // Now count other way -- don't run off image though of course + var scale = 1.0; + var otherToX = fromX - (toX - fromX); + if (otherToX < 0) + { + scale = fromX / (fromX - otherToX); + otherToX = 0; + } + else if (otherToX >= qrcode.width) + { + scale = (qrcode.width - 1 - fromX) / (otherToX - fromX); + otherToX = qrcode.width - 1; + } + var otherToY = Math.floor (fromY - (toY - fromY) * scale); + + scale = 1.0; + if (otherToY < 0) + { + scale = fromY / (fromY - otherToY); + otherToY = 0; + } + else if (otherToY >= qrcode.height) + { + scale = (qrcode.height - 1 - fromY) / (otherToY - fromY); + otherToY = qrcode.height - 1; + } + otherToX = Math.floor (fromX + (otherToX - fromX) * scale); + + result += this.sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); + return result - 1.0; // -1 because we counted the middle pixel twice + } + + + + this.calculateModuleSizeOneWay=function( pattern, otherPattern) + { + var moduleSizeEst1 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor( pattern.X), Math.floor( pattern.Y), Math.floor( otherPattern.X), Math.floor(otherPattern.Y)); + var moduleSizeEst2 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(otherPattern.X), Math.floor(otherPattern.Y), Math.floor( pattern.X), Math.floor(pattern.Y)); + if (isNaN(moduleSizeEst1)) + { + return moduleSizeEst2 / 7.0; + } + if (isNaN(moduleSizeEst2)) + { + return moduleSizeEst1 / 7.0; + } + // Average them, and divide by 7 since we've counted the width of 3 black modules, + // and 1 white and 1 black module on either side. Ergo, divide sum by 14. + return (moduleSizeEst1 + moduleSizeEst2) / 14.0; + } + + + this.calculateModuleSize=function( topLeft, topRight, bottomLeft) + { + // Take the average + return (this.calculateModuleSizeOneWay(topLeft, topRight) + this.calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0; + } + + this.distance=function( pattern1, pattern2) + { + xDiff = pattern1.X - pattern2.X; + yDiff = pattern1.Y - pattern2.Y; + return Math.sqrt( (xDiff * xDiff + yDiff * yDiff)); + } + this.computeDimension=function( topLeft, topRight, bottomLeft, moduleSize) + { + + var tltrCentersDimension = Math.round(this.distance(topLeft, topRight) / moduleSize); + var tlblCentersDimension = Math.round(this.distance(topLeft, bottomLeft) / moduleSize); + var dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; + switch (dimension & 0x03) + { + + // mod 4 + case 0: + dimension++; + break; + // 1? do nothing + + case 2: + dimension--; + break; + + case 3: + throw "Error"; + } + return dimension; + } + + this.findAlignmentInRegion=function( overallEstModuleSize, estAlignmentX, estAlignmentY, allowanceFactor) + { + // Look for an alignment pattern (3 modules in size) around where it + // should be + var allowance = Math.floor (allowanceFactor * overallEstModuleSize); + var alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance); + var alignmentAreaRightX = Math.min(qrcode.width - 1, estAlignmentX + allowance); + if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) + { + throw "Error"; + } + + var alignmentAreaTopY = Math.max(0, estAlignmentY - allowance); + var alignmentAreaBottomY = Math.min(qrcode.height - 1, estAlignmentY + allowance); + + var alignmentFinder = new AlignmentPatternFinder(this.image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, this.resultPointCallback); + return alignmentFinder.find(); + } + + this.createTransform=function( topLeft, topRight, bottomLeft, alignmentPattern, dimension) + { + var dimMinusThree = dimension - 3.5; + var bottomRightX; + var bottomRightY; + var sourceBottomRightX; + var sourceBottomRightY; + if (alignmentPattern != null) + { + bottomRightX = alignmentPattern.X; + bottomRightY = alignmentPattern.Y; + sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0; + } + else + { + // Don't have an alignment pattern, just make up the bottom-right point + bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X; + bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y; + sourceBottomRightX = sourceBottomRightY = dimMinusThree; + } + + var transform = PerspectiveTransform.quadrilateralToQuadrilateral(3.5, 3.5, dimMinusThree, 3.5, sourceBottomRightX, sourceBottomRightY, 3.5, dimMinusThree, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRightX, bottomRightY, bottomLeft.X, bottomLeft.Y); + + return transform; + } + + this.sampleGrid=function( image, transform, dimension) + { + + var sampler = GridSampler; + return sampler.sampleGrid3(image, dimension, transform); + } + + this.processFinderPatternInfo = function( info) + { + + var topLeft = info.TopLeft; + var topRight = info.TopRight; + var bottomLeft = info.BottomLeft; + + var moduleSize = this.calculateModuleSize(topLeft, topRight, bottomLeft); + if (moduleSize < 1.0) + { + throw "Error"; + } + var dimension = this.computeDimension(topLeft, topRight, bottomLeft, moduleSize); + var provisionalVersion = Version.getProvisionalVersionForDimension(dimension); + var modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7; + + var alignmentPattern = null; + // Anything above version 1 has an alignment pattern + if (provisionalVersion.AlignmentPatternCenters.length > 0) + { + + // Guess where a "bottom right" finder pattern would have been + var bottomRightX = topRight.X - topLeft.X + bottomLeft.X; + var bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y; + + // Estimate that alignment pattern is closer by 3 modules + // from "bottom right" to known top left location + var correctionToTopLeft = 1.0 - 3.0 / modulesBetweenFPCenters; + var estAlignmentX = Math.floor (topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X)); + var estAlignmentY = Math.floor (topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y)); + + // Kind of arbitrary -- expand search radius before giving up + for (var i = 4; i <= 16; i <<= 1) + { + //try + //{ + alignmentPattern = this.findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, i); + break; + //} + //catch (re) + //{ + // try next round + //} + } + // If we didn't find alignment pattern... well try anyway without it + } + + var transform = this.createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension); + + var bits = this.sampleGrid(this.image, transform, dimension); + + var points; + if (alignmentPattern == null) + { + points = new Array(bottomLeft, topLeft, topRight); + } + else + { + points = new Array(bottomLeft, topLeft, topRight, alignmentPattern); + } + return new DetectorResult(bits, points); + } + + + + this.detect=function() + { + var info = new FinderPatternFinder().findFinderPattern(this.image); + + return this.processFinderPatternInfo(info); + } +} \ No newline at end of file diff --git a/js/jsqrcode/errorlevel.js b/js/jsqrcode/errorlevel.js new file mode 100644 index 000000000..222398ecd --- /dev/null +++ b/js/jsqrcode/errorlevel.js @@ -0,0 +1,58 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +function ErrorCorrectionLevel(ordinal, bits, name) +{ + this.ordinal_Renamed_Field = ordinal; + this.bits = bits; + this.name = name; + this.__defineGetter__("Bits", function() + { + return this.bits; + }); + this.__defineGetter__("Name", function() + { + return this.name; + }); + this.ordinal=function() + { + return this.ordinal_Renamed_Field; + } +} + +ErrorCorrectionLevel.forBits=function( bits) +{ + if (bits < 0 || bits >= FOR_BITS.length) + { + throw "ArgumentException"; + } + return FOR_BITS[bits]; +} + +var L = new ErrorCorrectionLevel(0, 0x01, "L"); +var M = new ErrorCorrectionLevel(1, 0x00, "M"); +var Q = new ErrorCorrectionLevel(2, 0x03, "Q"); +var H = new ErrorCorrectionLevel(3, 0x02, "H"); +var FOR_BITS = new Array( M, L, H, Q); diff --git a/js/jsqrcode/findpat.js b/js/jsqrcode/findpat.js new file mode 100644 index 000000000..a2e4b8363 --- /dev/null +++ b/js/jsqrcode/findpat.js @@ -0,0 +1,649 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +var MIN_SKIP = 3; +var MAX_MODULES = 57; +var INTEGER_MATH_SHIFT = 8; +var CENTER_QUORUM = 2; + +qrcode.orderBestPatterns=function(patterns) + { + + function distance( pattern1, pattern2) + { + xDiff = pattern1.X - pattern2.X; + yDiff = pattern1.Y - pattern2.Y; + return Math.sqrt( (xDiff * xDiff + yDiff * yDiff)); + } + + /// Returns the z component of the cross product between vectors BC and BA. + function crossProductZ( pointA, pointB, pointC) + { + var bX = pointB.x; + var bY = pointB.y; + return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX)); + } + + + // Find distances between pattern centers + var zeroOneDistance = distance(patterns[0], patterns[1]); + var oneTwoDistance = distance(patterns[1], patterns[2]); + var zeroTwoDistance = distance(patterns[0], patterns[2]); + + var pointA, pointB, pointC; + // Assume one closest to other two is B; A and C will just be guesses at first + if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) + { + pointB = patterns[0]; + pointA = patterns[1]; + pointC = patterns[2]; + } + else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) + { + pointB = patterns[1]; + pointA = patterns[0]; + pointC = patterns[2]; + } + else + { + pointB = patterns[2]; + pointA = patterns[0]; + pointC = patterns[1]; + } + + // Use cross product to figure out whether A and C are correct or flipped. + // This asks whether BC x BA has a positive z component, which is the arrangement + // we want for A, B, C. If it's negative, then we've got it flipped around and + // should swap A and C. + if (crossProductZ(pointA, pointB, pointC) < 0.0) + { + var temp = pointA; + pointA = pointC; + pointC = temp; + } + + patterns[0] = pointA; + patterns[1] = pointB; + patterns[2] = pointC; + } + + +function FinderPattern(posX, posY, estimatedModuleSize) +{ + this.x=posX; + this.y=posY; + this.count = 1; + this.estimatedModuleSize = estimatedModuleSize; + + this.__defineGetter__("EstimatedModuleSize", function() + { + return this.estimatedModuleSize; + }); + this.__defineGetter__("Count", function() + { + return this.count; + }); + this.__defineGetter__("X", function() + { + return this.x; + }); + this.__defineGetter__("Y", function() + { + return this.y; + }); + this.incrementCount = function() + { + this.count++; + } + this.aboutEquals=function( moduleSize, i, j) + { + if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize) + { + var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize); + return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0; + } + return false; + } + +} + +function FinderPatternInfo(patternCenters) +{ + this.bottomLeft = patternCenters[0]; + this.topLeft = patternCenters[1]; + this.topRight = patternCenters[2]; + this.__defineGetter__("BottomLeft", function() + { + return this.bottomLeft; + }); + this.__defineGetter__("TopLeft", function() + { + return this.topLeft; + }); + this.__defineGetter__("TopRight", function() + { + return this.topRight; + }); +} + +function FinderPatternFinder() +{ + this.image=null; + this.possibleCenters = []; + this.hasSkipped = false; + this.crossCheckStateCount = new Array(0,0,0,0,0); + this.resultPointCallback = null; + + this.__defineGetter__("CrossCheckStateCount", function() + { + this.crossCheckStateCount[0] = 0; + this.crossCheckStateCount[1] = 0; + this.crossCheckStateCount[2] = 0; + this.crossCheckStateCount[3] = 0; + this.crossCheckStateCount[4] = 0; + return this.crossCheckStateCount; + }); + + this.foundPatternCross=function( stateCount) + { + var totalModuleSize = 0; + for (var i = 0; i < 5; i++) + { + var count = stateCount[i]; + if (count == 0) + { + return false; + } + totalModuleSize += count; + } + if (totalModuleSize < 7) + { + return false; + } + var moduleSize = Math.floor((totalModuleSize << INTEGER_MATH_SHIFT) / 7); + var maxVariance = Math.floor(moduleSize / 2); + // Allow less than 50% variance from 1-1-3-1-1 proportions + return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; + } + this.centerFromEnd=function( stateCount, end) + { + return (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0; + } + this.crossCheckVertical=function( startI, centerJ, maxCount, originalStateCountTotal) + { + var image = this.image; + + var maxI = qrcode.height; + var stateCount = this.CrossCheckStateCount; + + // Start counting up from center + var i = startI; + while (i >= 0 && image[centerJ + i*qrcode.width]) + { + stateCount[2]++; + i--; + } + if (i < 0) + { + return NaN; + } + while (i >= 0 && !image[centerJ +i*qrcode.width] && stateCount[1] <= maxCount) + { + stateCount[1]++; + i--; + } + // If already too many modules in this state or ran off the edge: + if (i < 0 || stateCount[1] > maxCount) + { + return NaN; + } + while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount) + { + stateCount[0]++; + i--; + } + if (stateCount[0] > maxCount) + { + return NaN; + } + + // Now also count down from center + i = startI + 1; + while (i < maxI && image[centerJ +i*qrcode.width]) + { + stateCount[2]++; + i++; + } + if (i == maxI) + { + return NaN; + } + while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[3] < maxCount) + { + stateCount[3]++; + i++; + } + if (i == maxI || stateCount[3] >= maxCount) + { + return NaN; + } + while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[4] < maxCount) + { + stateCount[4]++; + i++; + } + if (stateCount[4] >= maxCount) + { + return NaN; + } + + // If we found a finder-pattern-like section, but its size is more than 40% different than + // the original, assume it's a false positive + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; + if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) + { + return NaN; + } + + return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN; + } + this.crossCheckHorizontal=function( startJ, centerI, maxCount, originalStateCountTotal) + { + var image = this.image; + + var maxJ = qrcode.width; + var stateCount = this.CrossCheckStateCount; + + var j = startJ; + while (j >= 0 && image[j+ centerI*qrcode.width]) + { + stateCount[2]++; + j--; + } + if (j < 0) + { + return NaN; + } + while (j >= 0 && !image[j+ centerI*qrcode.width] && stateCount[1] <= maxCount) + { + stateCount[1]++; + j--; + } + if (j < 0 || stateCount[1] > maxCount) + { + return NaN; + } + while (j >= 0 && image[j+ centerI*qrcode.width] && stateCount[0] <= maxCount) + { + stateCount[0]++; + j--; + } + if (stateCount[0] > maxCount) + { + return NaN; + } + + j = startJ + 1; + while (j < maxJ && image[j+ centerI*qrcode.width]) + { + stateCount[2]++; + j++; + } + if (j == maxJ) + { + return NaN; + } + while (j < maxJ && !image[j+ centerI*qrcode.width] && stateCount[3] < maxCount) + { + stateCount[3]++; + j++; + } + if (j == maxJ || stateCount[3] >= maxCount) + { + return NaN; + } + while (j < maxJ && image[j+ centerI*qrcode.width] && stateCount[4] < maxCount) + { + stateCount[4]++; + j++; + } + if (stateCount[4] >= maxCount) + { + return NaN; + } + + // If we found a finder-pattern-like section, but its size is significantly different than + // the original, assume it's a false positive + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; + if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) + { + return NaN; + } + + return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, j):NaN; + } + this.handlePossibleCenter=function( stateCount, i, j) + { + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; + var centerJ = this.centerFromEnd(stateCount, j); //float + var centerI = this.crossCheckVertical(i, Math.floor( centerJ), stateCount[2], stateCountTotal); //float + if (!isNaN(centerI)) + { + // Re-cross check + centerJ = this.crossCheckHorizontal(Math.floor( centerJ), Math.floor( centerI), stateCount[2], stateCountTotal); + if (!isNaN(centerJ)) + { + var estimatedModuleSize = stateCountTotal / 7.0; + var found = false; + var max = this.possibleCenters.length; + for (var index = 0; index < max; index++) + { + var center = this.possibleCenters[index]; + // Look for about the same center and module size: + if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) + { + center.incrementCount(); + found = true; + break; + } + } + if (!found) + { + var point = new FinderPattern(centerJ, centerI, estimatedModuleSize); + this.possibleCenters.push(point); + if (this.resultPointCallback != null) + { + this.resultPointCallback.foundPossibleResultPoint(point); + } + } + return true; + } + } + return false; + } + + this.selectBestPatterns=function() + { + + var startSize = this.possibleCenters.length; + if (startSize < 3) + { + // Couldn't find enough finder patterns + throw "Couldn't find enough finder patterns"; + } + + // Filter outlier possibilities whose module size is too different + if (startSize > 3) + { + // But we can only afford to do so if we have at least 4 possibilities to choose from + var totalModuleSize = 0.0; + var square = 0.0; + for (var i = 0; i < startSize; i++) + { + //totalModuleSize += this.possibleCenters[i].EstimatedModuleSize; + var centerValue=this.possibleCenters[i].EstimatedModuleSize; + totalModuleSize += centerValue; + square += (centerValue * centerValue); + } + var average = totalModuleSize / startSize; + this.possibleCenters.sort(function(center1,center2) { + var dA=Math.abs(center2.EstimatedModuleSize - average); + var dB=Math.abs(center1.EstimatedModuleSize - average); + if (dA < dB) { + return (-1); + } else if (dA == dB) { + return 0; + } else { + return 1; + } + }); + + var stdDev = Math.sqrt(square / startSize - average * average); + var limit = Math.max(0.1 * average, stdDev); + for (var i = 0; i < this.possibleCenters.length && this.possibleCenters.length > 3; i++) + { + var pattern = this.possibleCenters[i]; + //if (Math.abs(pattern.EstimatedModuleSize - average) > 0.2 * average) + if (Math.abs(pattern.EstimatedModuleSize - average) > limit) + { + this.possibleCenters.remove(i); + i--; + } + } + } + + if (this.possibleCenters.length > 3) + { + // Throw away all but those first size candidate points we found. + this.possibleCenters.sort(function(a, b){ + if (a.count > b.count){return -1;} + if (a.count < b.count){return 1;} + return 0; + }); + } + + return new Array( this.possibleCenters[0], this.possibleCenters[1], this.possibleCenters[2]); + } + + this.findRowSkip=function() + { + var max = this.possibleCenters.length; + if (max <= 1) + { + return 0; + } + var firstConfirmedCenter = null; + for (var i = 0; i < max; i++) + { + var center = this.possibleCenters[i]; + if (center.Count >= CENTER_QUORUM) + { + if (firstConfirmedCenter == null) + { + firstConfirmedCenter = center; + } + else + { + // We have two confirmed centers + // How far down can we skip before resuming looking for the next + // pattern? In the worst case, only the difference between the + // difference in the x / y coordinates of the two centers. + // This is the case where you find top left last. + this.hasSkipped = true; + return Math.floor ((Math.abs(firstConfirmedCenter.X - center.X) - Math.abs(firstConfirmedCenter.Y - center.Y)) / 2); + } + } + } + return 0; + } + + this.haveMultiplyConfirmedCenters=function() + { + var confirmedCount = 0; + var totalModuleSize = 0.0; + var max = this.possibleCenters.length; + for (var i = 0; i < max; i++) + { + var pattern = this.possibleCenters[i]; + if (pattern.Count >= CENTER_QUORUM) + { + confirmedCount++; + totalModuleSize += pattern.EstimatedModuleSize; + } + } + if (confirmedCount < 3) + { + return false; + } + // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" + // and that we need to keep looking. We detect this by asking if the estimated module sizes + // vary too much. We arbitrarily say that when the total deviation from average exceeds + // 5% of the total module size estimates, it's too much. + var average = totalModuleSize / max; + var totalDeviation = 0.0; + for (var i = 0; i < max; i++) + { + pattern = this.possibleCenters[i]; + totalDeviation += Math.abs(pattern.EstimatedModuleSize - average); + } + return totalDeviation <= 0.05 * totalModuleSize; + } + + this.findFinderPattern = function(image){ + var tryHarder = false; + this.image=image; + var maxI = qrcode.height; + var maxJ = qrcode.width; + var iSkip = Math.floor((3 * maxI) / (4 * MAX_MODULES)); + if (iSkip < MIN_SKIP || tryHarder) + { + iSkip = MIN_SKIP; + } + + var done = false; + var stateCount = new Array(5); + for (var i = iSkip - 1; i < maxI && !done; i += iSkip) + { + // Get a row of black/white values + stateCount[0] = 0; + stateCount[1] = 0; + stateCount[2] = 0; + stateCount[3] = 0; + stateCount[4] = 0; + var currentState = 0; + for (var j = 0; j < maxJ; j++) + { + if (image[j+i*qrcode.width] ) + { + // Black pixel + if ((currentState & 1) == 1) + { + // Counting white pixels + currentState++; + } + stateCount[currentState]++; + } + else + { + // White pixel + if ((currentState & 1) == 0) + { + // Counting black pixels + if (currentState == 4) + { + // A winner? + if (this.foundPatternCross(stateCount)) + { + // Yes + var confirmed = this.handlePossibleCenter(stateCount, i, j); + if (confirmed) + { + // Start examining every other line. Checking each line turned out to be too + // expensive and didn't improve performance. + iSkip = 2; + if (this.hasSkipped) + { + done = this.haveMultiplyConfirmedCenters(); + } + else + { + var rowSkip = this.findRowSkip(); + if (rowSkip > stateCount[2]) + { + // Skip rows between row of lower confirmed center + // and top of presumed third confirmed center + // but back up a bit to get a full chance of detecting + // it, entire width of center of finder pattern + + // Skip by rowSkip, but back off by stateCount[2] (size of last center + // of pattern we saw) to be conservative, and also back off by iSkip which + // is about to be re-added + i += rowSkip - stateCount[2] - iSkip; + j = maxJ - 1; + } + } + } + else + { + // Advance to next black pixel + do + { + j++; + } + while (j < maxJ && !image[j + i*qrcode.width]); + j--; // back up to that last white pixel + } + // Clear state to start looking again + currentState = 0; + stateCount[0] = 0; + stateCount[1] = 0; + stateCount[2] = 0; + stateCount[3] = 0; + stateCount[4] = 0; + } + else + { + // No, shift counts back by two + stateCount[0] = stateCount[2]; + stateCount[1] = stateCount[3]; + stateCount[2] = stateCount[4]; + stateCount[3] = 1; + stateCount[4] = 0; + currentState = 3; + } + } + else + { + stateCount[++currentState]++; + } + } + else + { + // Counting white pixels + stateCount[currentState]++; + } + } + } + if (this.foundPatternCross(stateCount)) + { + var confirmed = this.handlePossibleCenter(stateCount, i, maxJ); + if (confirmed) + { + iSkip = stateCount[0]; + if (this.hasSkipped) + { + // Found a third one + done = haveMultiplyConfirmedCenters(); + } + } + } + } + + var patternInfo = this.selectBestPatterns(); + qrcode.orderBestPatterns(patternInfo); + + return new FinderPatternInfo(patternInfo); + }; +} diff --git a/js/jsqrcode/formatinf.js b/js/jsqrcode/formatinf.js new file mode 100644 index 000000000..7e4b59268 --- /dev/null +++ b/js/jsqrcode/formatinf.js @@ -0,0 +1,104 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +var FORMAT_INFO_MASK_QR = 0x5412; +var FORMAT_INFO_DECODE_LOOKUP = new Array(new Array(0x5412, 0x00), new Array(0x5125, 0x01), new Array(0x5E7C, 0x02), new Array(0x5B4B, 0x03), new Array(0x45F9, 0x04), new Array(0x40CE, 0x05), new Array(0x4F97, 0x06), new Array(0x4AA0, 0x07), new Array(0x77C4, 0x08), new Array(0x72F3, 0x09), new Array(0x7DAA, 0x0A), new Array(0x789D, 0x0B), new Array(0x662F, 0x0C), new Array(0x6318, 0x0D), new Array(0x6C41, 0x0E), new Array(0x6976, 0x0F), new Array(0x1689, 0x10), new Array(0x13BE, 0x11), new Array(0x1CE7, 0x12), new Array(0x19D0, 0x13), new Array(0x0762, 0x14), new Array(0x0255, 0x15), new Array(0x0D0C, 0x16), new Array(0x083B, 0x17), new Array(0x355F, 0x18), new Array(0x3068, 0x19), new Array(0x3F31, 0x1A), new Array(0x3A06, 0x1B), new Array(0x24B4, 0x1C), new Array(0x2183, 0x1D), new Array(0x2EDA, 0x1E), new Array(0x2BED, 0x1F)); +var BITS_SET_IN_HALF_BYTE = new Array(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); + + +function FormatInformation(formatInfo) +{ + this.errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03); + this.dataMask = (formatInfo & 0x07); + + this.__defineGetter__("ErrorCorrectionLevel", function() + { + return this.errorCorrectionLevel; + }); + this.__defineGetter__("DataMask", function() + { + return this.dataMask; + }); + this.GetHashCode=function() + { + return (this.errorCorrectionLevel.ordinal() << 3) | dataMask; + } + this.Equals=function( o) + { + var other = o; + return this.errorCorrectionLevel == other.errorCorrectionLevel && this.dataMask == other.dataMask; + } +} + +FormatInformation.numBitsDiffering=function( a, b) +{ + a ^= b; // a now has a 1 bit exactly where its bit differs with b's + // Count bits set quickly with a series of lookups: + return BITS_SET_IN_HALF_BYTE[a & 0x0F] + BITS_SET_IN_HALF_BYTE[(URShift(a, 4) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 8) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 12) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 16) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 20) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 24) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 28) & 0x0F)]; +} + +FormatInformation.decodeFormatInformation=function( maskedFormatInfo) +{ + var formatInfo = FormatInformation.doDecodeFormatInformation(maskedFormatInfo); + if (formatInfo != null) + { + return formatInfo; + } + // Should return null, but, some QR codes apparently + // do not mask this info. Try again by actually masking the pattern + // first + return FormatInformation.doDecodeFormatInformation(maskedFormatInfo ^ FORMAT_INFO_MASK_QR); +} +FormatInformation.doDecodeFormatInformation=function( maskedFormatInfo) +{ + // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing + var bestDifference = 0xffffffff; + var bestFormatInfo = 0; + for (var i = 0; i < FORMAT_INFO_DECODE_LOOKUP.length; i++) + { + var decodeInfo = FORMAT_INFO_DECODE_LOOKUP[i]; + var targetInfo = decodeInfo[0]; + if (targetInfo == maskedFormatInfo) + { + // Found an exact match + return new FormatInformation(decodeInfo[1]); + } + var bitsDifference = this.numBitsDiffering(maskedFormatInfo, targetInfo); + if (bitsDifference < bestDifference) + { + bestFormatInfo = decodeInfo[1]; + bestDifference = bitsDifference; + } + } + // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits + // differing means we found a match + if (bestDifference <= 3) + { + return new FormatInformation(bestFormatInfo); + } + return null; +} + + \ No newline at end of file diff --git a/js/jsqrcode/gf256.js b/js/jsqrcode/gf256.js new file mode 100644 index 000000000..97658627d --- /dev/null +++ b/js/jsqrcode/gf256.js @@ -0,0 +1,117 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +function GF256( primitive) +{ + this.expTable = new Array(256); + this.logTable = new Array(256); + var x = 1; + for (var i = 0; i < 256; i++) + { + this.expTable[i] = x; + x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 + if (x >= 0x100) + { + x ^= primitive; + } + } + for (var i = 0; i < 255; i++) + { + this.logTable[this.expTable[i]] = i; + } + // logTable[0] == 0 but this should never be used + var at0=new Array(1);at0[0]=0; + this.zero = new GF256Poly(this, new Array(at0)); + var at1=new Array(1);at1[0]=1; + this.one = new GF256Poly(this, new Array(at1)); + + this.__defineGetter__("Zero", function() + { + return this.zero; + }); + this.__defineGetter__("One", function() + { + return this.one; + }); + this.buildMonomial=function( degree, coefficient) + { + if (degree < 0) + { + throw "System.ArgumentException"; + } + if (coefficient == 0) + { + return zero; + } + var coefficients = new Array(degree + 1); + for(var i=0;i 1 && coefficients[0] == 0) + { + // Leading term must be non-zero for anything except the constant polynomial "0" + var firstNonZero = 1; + while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) + { + firstNonZero++; + } + if (firstNonZero == coefficientsLength) + { + this.coefficients = field.Zero.coefficients; + } + else + { + this.coefficients = new Array(coefficientsLength - firstNonZero); + for(var i=0;i largerCoefficients.length) + { + var temp = smallerCoefficients; + smallerCoefficients = largerCoefficients; + largerCoefficients = temp; + } + var sumDiff = new Array(largerCoefficients.length); + var lengthDiff = largerCoefficients.length - smallerCoefficients.length; + // Copy high-order terms only found in higher-degree polynomial's coefficients + //Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff); + for(var ci=0;ci= other.Degree && !remainder.Zero) + { + var degreeDifference = remainder.Degree - other.Degree; + var scale = this.field.multiply(remainder.getCoefficient(remainder.Degree), inverseDenominatorLeadingTerm); + var term = other.multiplyByMonomial(degreeDifference, scale); + var iterationQuotient = this.field.buildMonomial(degreeDifference, scale); + quotient = quotient.addOrSubtract(iterationQuotient); + remainder = remainder.addOrSubtract(term); + } + + return new Array(quotient, remainder); + } +} \ No newline at end of file diff --git a/js/jsqrcode/grid.js b/js/jsqrcode/grid.js new file mode 100644 index 000000000..cf9150ea5 --- /dev/null +++ b/js/jsqrcode/grid.js @@ -0,0 +1,152 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +GridSampler = {}; + +GridSampler.checkAndNudgePoints=function( image, points) + { + var width = qrcode.width; + var height = qrcode.height; + // Check and nudge points from start until we see some that are OK: + var nudged = true; + for (var offset = 0; offset < points.length && nudged; offset += 2) + { + var x = Math.floor (points[offset]); + var y = Math.floor( points[offset + 1]); + if (x < - 1 || x > width || y < - 1 || y > height) + { + throw "Error.checkAndNudgePoints "; + } + nudged = false; + if (x == - 1) + { + points[offset] = 0.0; + nudged = true; + } + else if (x == width) + { + points[offset] = width - 1; + nudged = true; + } + if (y == - 1) + { + points[offset + 1] = 0.0; + nudged = true; + } + else if (y == height) + { + points[offset + 1] = height - 1; + nudged = true; + } + } + // Check and nudge points from end: + nudged = true; + for (var offset = points.length - 2; offset >= 0 && nudged; offset -= 2) + { + var x = Math.floor( points[offset]); + var y = Math.floor( points[offset + 1]); + if (x < - 1 || x > width || y < - 1 || y > height) + { + throw "Error.checkAndNudgePoints "; + } + nudged = false; + if (x == - 1) + { + points[offset] = 0.0; + nudged = true; + } + else if (x == width) + { + points[offset] = width - 1; + nudged = true; + } + if (y == - 1) + { + points[offset + 1] = 0.0; + nudged = true; + } + else if (y == height) + { + points[offset + 1] = height - 1; + nudged = true; + } + } + } + + + +GridSampler.sampleGrid3=function( image, dimension, transform) + { + var bits = new BitMatrix(dimension); + var points = new Array(dimension << 1); + for (var y = 0; y < dimension; y++) + { + var max = points.length; + var iValue = y + 0.5; + for (var x = 0; x < max; x += 2) + { + points[x] = (x >> 1) + 0.5; + points[x + 1] = iValue; + } + transform.transformPoints1(points); + // Quick check to see if points transformed to something inside the image; + // sufficient to check the endpoints + GridSampler.checkAndNudgePoints(image, points); + try + { + for (var x = 0; x < max; x += 2) + { + var xpoint = (Math.floor( points[x]) * 4) + (Math.floor( points[x + 1]) * qrcode.width * 4); + var bit = image[Math.floor( points[x])+ qrcode.width* Math.floor( points[x + 1])]; + qrcode.imagedata.data[xpoint] = bit?255:0; + qrcode.imagedata.data[xpoint+1] = bit?255:0; + qrcode.imagedata.data[xpoint+2] = 0; + qrcode.imagedata.data[xpoint+3] = 255; + //bits[x >> 1][ y]=bit; + if(bit) + bits.set_Renamed(x >> 1, y); + } + } + catch ( aioobe) + { + // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting + // transform gets "twisted" such that it maps a straight line of points to a set of points + // whose endpoints are in bounds, but others are not. There is probably some mathematical + // way to detect this about the transformation that I don't know yet. + // This results in an ugly runtime exception despite our clever checks above -- can't have + // that. We could check each point's coordinates but that feels duplicative. We settle for + // catching and wrapping ArrayIndexOutOfBoundsException. + throw "Error.checkAndNudgePoints"; + } + } + return bits; + } + +GridSampler.sampleGridx=function( image, dimension, p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY) +{ + var transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY); + + return GridSampler.sampleGrid3(image, dimension, transform); +} diff --git a/js/jsqrcode/index.d.ts b/js/jsqrcode/index.d.ts new file mode 100644 index 000000000..e7768d593 --- /dev/null +++ b/js/jsqrcode/index.d.ts @@ -0,0 +1,500 @@ +// Type definitions for jsqrcode 1.0 +// Project: https://github.com/LazarSoft/jsqrcode +// Definitions by: Ricardo Azzi Silva +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function URShift(number: number, bits: number): number; + +interface ResultPointCallback { + foundPossibleResultPoint(point: FinderPattern): void; +} + +declare class AlignmentPattern { + private x: number; + private y: number; + private count: number; + private estimatedModuleSize: number; + + readonly X: number; + readonly Y: number; + readonly EstimatedModuleSize: number; + readonly Count: number; + + constructor(posX: number, posY: number, estimatedModuleSize: number); + + incrementCount(): void; + + aboutEquals(moduleSize: number, i: number, j: number): boolean; +} + +declare class AlignmentPatternFinder { + possibleCenters: AlignmentPattern[]; + crossCheckStateCount: [number, number, number]; + image: Uint8Array; + startX: number; + startY: number; + width: number; + height: number; + moduleSize: number; + resultPointCallback: ResultPointCallback; + + constructor( + image: Uint8Array, startX: number, startY: number, + width: number, height: number, + moduleSize: number, resultPointCallback: ResultPointCallback + ); + + private centerFromEnd(stateCount: number, end: number): number; + + private foundPatternCross(stateCount: number): boolean; + + private handlePossibleCenter(stateCount: number, i: number, j: number): AlignmentPattern; + + find(): AlignmentPattern; +} + +declare class BitMatrix { + private width: number; + private height: number; + + readonly Width: number; + readonly Height: number; + readonly Dimension: number; + + rowSize: number; + bits: number[]; + + constructor(width: number, height?: number); + + get_Renamed(x: number, y: number): boolean; + set_Renamed(x: number, y: number): void; + flip(x: number, y: number): void; + clear(): void; + setRegion(left: number, top: number, width: number, height: number): void; +} + +declare class BitMatrixParser { + bitMatrix: BitMatrix; + parsedVersion: Version; + parsedFormatInfo: FormatInformation; + + constructor(bitMatrix: BitMatrix); + + copyBit(i: number, j: number, versionBits: number): number; + readFormatInformation(): FormatInformation; + readVersion(): Version; + readCodewords(): number[]; +} + +declare class DataBlock { + static getDataBlocks( + rawCodewords: number[], version: Version, ecLevel: ErrorCorrectionLevel + ): DataBlock[]; + + private numDataCodewords: number; + private codewords: number[]; + + readonly NumDataCodewords: number; + readonly Codewords: number[]; + + constructor(numDataCodewords: number, codewords: number[]); +} + +declare class QRCodeDataBlockReader { + blockPointer: number; + bitPointer: number; + dataLength: number; + dataLengthMode: number; + blocks: number[]; + numErrorCorrectionCode: number; + + readonly DataByte: Array; + + constructor(blocks: number[], version: number, numErrorCorrectionCode: number); + + getNextBits(numBits: number): number; + NextMode(): number; + getDataLength(modeIndicator: number): number; + getRomanAndFigureString(dataLength: number): string; + getFigureString(dataLength: number): string; + get8bitByteArray(dataLength: number): number[]; + getKanjiString(dataLength: number): string; + parseECIValue(): number; +} + +declare abstract class DataMask { + private static DATA_MASKS: DataMask[]; + + static forReference(reference: number): DataMask; + + abstract unmaskBitMatrix(bits: number[], dimension: number): void; + + abstract isMasked(i: number, j: number): boolean; +} + +declare class DataMask000 extends DataMask { + unmaskBitMatrix(bits: number[], dimension: number): void; + + isMasked(i: number, j: number): boolean; +} + +declare class DataMask001 extends DataMask { + unmaskBitMatrix(bits: number[], dimension: number): void; + + isMasked(i: number, j: number): boolean; +} + +declare class DataMask010 extends DataMask { + unmaskBitMatrix(bits: number[], dimension: number): void; + + isMasked(i: number, j: number): boolean; +} + +declare class DataMask011 extends DataMask { + unmaskBitMatrix(bits: number[], dimension: number): void; + + isMasked(i: number, j: number): boolean; +} + +declare class DataMask100 extends DataMask { + unmaskBitMatrix(bits: number[], dimension: number): void; + + isMasked(i: number, j: number): boolean; +} + +declare class DataMask101 extends DataMask { + unmaskBitMatrix(bits: number[], dimension: number): void; + + isMasked(i: number, j: number): boolean; +} + +declare class DataMask110 extends DataMask { + unmaskBitMatrix(bits: number[], dimension: number): void; + + isMasked(i: number, j: number): boolean; +} + +declare class DataMask111 extends DataMask { + unmaskBitMatrix(bits: number[], dimension: number): void; + + isMasked(i: number, j: number): boolean; +} + +declare const Decoder: { + rsDecoder: ReedSolomonDecoder, + + correctErrors(codewordBytes: number[], numDataCodewords: number): void; + + decode(bits: BitMatrix): QRCodeDataBlockReader; +}; + +declare class PerspectiveTransform { + a11: number; + a12: number; + a13: number; + a21: number; + a22: number; + a23: number; + a31: number; + a32: number; + a33: number; + + static quadrilateralToQuadrilateral( + x0: number, y0: number, x1: number, y1: number, + x2: number, y2: number, x3: number, y3: number, + x0p: number, y0p: number, x1p: number, y1p: number, + x2p: number, y2p: number, x3p: number, y3p: number + ): PerspectiveTransform; + static squareToQuadrilateral( + x0: number, y0: number, x1: number, y1: number, + x2: number, y2: number, x3: number, y3: number + ): PerspectiveTransform; + static quadrilateralToSquare( + x0: number, y0: number, x1: number, y1: number, + x2: number, y2: number, x3: number, y3: number + ): PerspectiveTransform; + + constructor( + a11: number, a21: number, a31: number, + a12: number, a22: number, a32: number, + a13: number, a23: number, a33: number + ); + + transformPoints1(points: number[]): void; + transformPoints2(xValues: number[], yValues: number[]): void; + buildAdjoint(): PerspectiveTransform; + times(other: PerspectiveTransform): PerspectiveTransform; +} + +declare class DetectorResult { + bits: BitMatrix; + points: [DetectorResult, DetectorResult, DetectorResult] | + [DetectorResult, DetectorResult, DetectorResult, DetectorResult]; + + constructor( + bits: BitMatrix, + points: [DetectorResult, DetectorResult, DetectorResult] | + [DetectorResult, DetectorResult, DetectorResult, DetectorResult] + ); +} + +declare class Detector { + image: Uint8Array; + resultPointCallback: ResultPointCallback; + + constructor(image: Uint8Array); + + sizeOfBlackWhiteBlackRun(fromX: number, fromY: number, toX: number, toY: number): number; + sizeOfBlackWhiteBlackRunBothWays(fromX: number, fromY: number, toX: number, toY: number): number; + calculateModuleSizeOneWay(pattern: AlignmentPattern, otherPattern: AlignmentPattern): number; + calculateModuleSize(topLeft: AlignmentPattern, topRight: AlignmentPattern, bottomLeft: AlignmentPattern): number; + distance(pattern1: AlignmentPattern, pattern2: AlignmentPattern): number; + computeDimension(topLeft: AlignmentPattern, topRight: AlignmentPattern, bottomLeft: AlignmentPattern, moduleSize: number): number; + findAlignmentInRegion(overallEstModuleSize: number, estAlignmentX: number, estAlignmentY: number, allowanceFactor: number): AlignmentPattern; + createTransform(topLeft: AlignmentPattern, topRight: AlignmentPattern, bottomLeft: AlignmentPattern, alignmentPattern: AlignmentPattern, dimension: number): PerspectiveTransform; + sampleGrid(image: Uint8Array, transform: PerspectiveTransform, dimension: number): BitMatrix; + processFinderPatternInfo(info: FinderPatternInfo): DetectorResult; + detect(): DetectorResult; +} + +declare const L: ErrorCorrectionLevel; +declare const M: ErrorCorrectionLevel; +declare const Q: ErrorCorrectionLevel; +declare const H: ErrorCorrectionLevel; +declare const FOR_BITS: ErrorCorrectionLevel[]; + +declare class ErrorCorrectionLevel { + private ordinal_Renamed_Field: number; + private bits: number; + private name: string; + + readonly Bits: number; + readonly Name: string; + + static forBits(bits: number): ErrorCorrectionLevel; + + constructor(ordinal: number, bits: number, name: string); +} +declare const MIN_SKIP: number; +declare const MAX_MODULES: number; +declare const INTEGER_MATH_SHIFT: number; +declare const CENTER_QUORUM: number; + +declare class FinderPattern { + private x: number; + private y: number; + private count: number; + private estimatedModuleSize: number; + + readonly X: number; + readonly Y: number; + readonly Count: number; + readonly EstimatedModuleSize: number; + + constructor(posX: number, posY: number, estimatedModuleSize: number); + + incrementCount(): void; + aboutEquals(moduleSize: number, i: number, j: number): boolean; +} + +declare class FinderPatternInfo { + readonly BottomLeft: AlignmentPattern; + readonly TopLeft: AlignmentPattern; + readonly TopRight: AlignmentPattern; + + constructor(patternCenters: [AlignmentPattern, AlignmentPattern, AlignmentPattern]); +} + +declare class FinderPatternFinder { + image: Uint8Array; + possibleCenters: FinderPattern[]; + hasSkipped: boolean; + resultPointCallback: ResultPointCallback; + + private crossCheckStateCount: [number, number, number, number, number]; + readonly CrossCheckStateCount: [number, number, number, number, number]; + + foundPatternCross(stateCount: [number, number, number, number, number]): boolean; + centerFromEnd(stateCount: [number, number, number, number, number], end: number): number; + crossCheckVertical(startI: number, centerJ: number, maxCount: number, originalStateCountTotal: number): number; + crossCheckHorizontal(startJ: number, centerI: number, maxCount: number, originalStateCountTotal: number): number; + handlePossibleCenter(stateCount: [number, number, number, number, number], i: number, j: number): boolean; + selectBestPatterns(): number; + findRowSkip(): number; + haveMultiplyConfirmedCenters(): boolean; + findFinderPattern(image: Uint8Array): FinderPatternInfo; +} + +declare const FORMAT_INFO_MASK_QR: 0x5412; +declare const FORMAT_INFO_DECODE_LOOKUP: [ + [0x5412, 0x00], [0x5125, 0x01], [0x5E7C, 0x02], [0x5B4B, 0x03], [0x45F9, 0x04], [0x40CE, 0x05], [0x4F97, 0x06], + [0x4AA0, 0x07], [0x77C4, 0x08], [0x72F3, 0x09], [0x7DAA, 0x0A], [0x789D, 0x0B], [0x662F, 0x0C], [0x6318, 0x0D], + [0x6C41, 0x0E], [0x6976, 0x0F], [0x1689, 0x10], [0x13BE, 0x11], [0x1CE7, 0x12], [0x19D0, 0x13], [0x0762, 0x14], + [0x0255, 0x15], [0x0D0C, 0x16], [0x083B, 0x17], [0x355F, 0x18], [0x3068, 0x19], [0x3F31, 0x1A], [0x3A06, 0x1B], + [0x24B4, 0x1C], [0x2183, 0x1D], [0x2EDA, 0x1E], [0x2BED, 0x1F] +]; +declare const BITS_SET_IN_HALF_BYTE: [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]; + +declare class FormatInformation { + static numBitsDiffering(a: number, b: [number, number]): number; + static decodeFormatInformation(maskedFormatInfo: number): FormatInformation; + private static doDecodeFormatInformation(maskedFormatInfo: number): FormatInformation; + + private errorCorrectionLevel: ErrorCorrectionLevel; + private dataMask: number; + + readonly ErrorCorrectionLevel: ErrorCorrectionLevel; + readonly DataMask: number; + + GetHashCode(): number; + Equals(other: FormatInformation): boolean; +} + +declare class GF256 { + static readonly QR_CODE_FIELD: GF256; + static readonly DATA_MATRIX_FIELD: GF256; + + private zero: GF256Poly; + private one: GF256Poly; + + expTable: number[]; + logTable: number[]; + readonly Zero: GF256Poly; + readonly One: GF256Poly; + + static addOrSubtract(a: number, b: number): number; + + constructor(primitive: number); + + buildMonomial(degree: number, coefficient: number): GF256Poly; + exp(a: number): number; + log(a: number): number; + inverse(a: number): number; + multiply(a: number, b: number): number; +} + +declare class GF256Poly { + field: GF256; + private coefficients: number[]; + + readonly Zero: boolean; + readonly Degree: number; + readonly Coefficients: number[]; + + constructor(field: GF256, coefficients: number[]); + + getCoefficient(degree: number): number; + evaluateAt(a: number): number; + addOrSubtract(other: GF256Poly): GF256Poly; + multiply1(other: GF256Poly): GF256Poly; + multiply2(scalar: number): GF256Poly; + multiplyByMonomial(degree: number, coefficient: number): GF256Poly; + divide(other: GF256Poly): [GF256Poly, GF256Poly]; +} + +declare const GridSampler: { + checkAndNudgePoints(image: Uint8Array, points: number[]): void; + sampleGrid3(image: Uint8Array, dimension: number, transform: PerspectiveTransform): BitMatrix; + sampleGridx( + image: Uint8Array, dimension: number, p1ToX: number, + p1ToY: number, p2ToX: number, p2ToY: number, p3ToX: number, + p3ToY: number, p4ToX: number, p4ToY: number, p1FromX: number, + p1FromY: number, p2FromX: number, p2FromY: number, p3FromX: number, + p3FromY: number, p4FromX: number, p4FromY: number + ): BitMatrix; +}; + +declare class ReedSolomonDecoder { + field: GF256; + + constructor(field: GF256); + + decode(received: GF256, twoS: number[]): void; + runEuclideanAlgorithm(a: GF256Poly, b: GF256Poly, R: number): [GF256Poly, GF256Poly]; + findErrorLocations(errorLocator: GF256Poly): number[]; + findErrorMagnitudes(errorEvaluator: GF256Poly, errorLocations: number[], dataMatrix: boolean): number[]; +} +declare function buildVersions(): Version[]; + +declare class ECB { + private count: number; + private dataCodewords: number; + + readonly Count: number; + readonly DataCodewords: number; + + constructor(count: number, dataCodewords: number); +} + +declare class ECBlocks { + private ecCodewordsPerBlock: number; + private ecBlocks: [ECB] | [ECB, ECB]; + + readonly ECCodewordsPerBlock: number; + readonly TotalECCodewords: number; + readonly NumBlocks: number; + + constructor(ecCodewordsPerBlock: number, ecBlocks1: ECB, ecBlocks2?: ECB); + + getECBlocks(): [ECB] | [ECB, ECB]; +} + +declare class Version { + static readonly VERSION_DECODE_INFO: [ + 0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, 0x0F928, + 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, 0x177EC, 0x18EC4, + 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, 0x209D5, 0x216F0, + 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, 0x27541, 0x28C69 + ]; + static readonly VERSIONS: Version[]; + + static getVersionForNumber(versionNumber: number): Version; + static getProvisionalVersionForDimension(dimension: number): Version; + static decodeVersionInformation(versionBits: number): Version; + + versionNumber: number; + alignmentPatternCenters: number[]; + ecBlocks: ECBlocks[]; + + readonly VersionNumber: number; + readonly AlignmentPatternCenters: number[]; + readonly TotalCodewords: number; + readonly DimensionForVersion: number; + + constructor(versionNumber: number, alignmentPatternCenters: number[], + ecBlocks1: ECBlocks, ecBlocks2: ECBlocks, + ecBlocks3: ECBlocks, ecBlocks4: ECBlocks); + + buildFunctionPattern(): BitMatrix; + + getECBlocksForLevel(ecLevel: ErrorCorrectionLevel): ECBlocks; +} + +declare const qrcode: { + imagedata: ImageData, + width: number, + height: number, + qrCodeSymbol: any, + debug: boolean, + maxImgSize: number, + readonly sizeOfDataLengthInfo: [[10, 9, 8, 8], [12, 11, 16, 10], [14, 13, 16, 12]], + + // tslint:disable-next-line:prefer-method-signature + callback: (result: string) => void, + + orderBestPatterns(patterns: AlignmentPattern[]): void, + + vidError(error?: any): void, + captureToCanvas(): void, + setWebcam(videoId: string): void, + decode(src?: string): void, + isUrl(s: string): boolean, + decode_url(s: string): string, + decode_utf8(s: string): string, + process(ctx: CanvasRenderingContext2D): string, + getPixel(x: number, y: number): number, + binarize(th: number): boolean[], + getMiddleBrightnessPerArea(image: number[]): number[][], + grayScaleToBitmap(grayScale: number[]): Uint8Array, + grayscale(): Uint8Array +}; diff --git a/js/jsqrcode/qrcode.js b/js/jsqrcode/qrcode.js new file mode 100644 index 000000000..8644c66c5 --- /dev/null +++ b/js/jsqrcode/qrcode.js @@ -0,0 +1,319 @@ +/* + Copyright 2011 Lazar Laszlo (lazarsoft@gmail.com, www.lazarsoft.info) + + 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. +*/ + + +qrcode = {}; +qrcode.imagedata = null; +qrcode.width = 0; +qrcode.height = 0; +qrcode.qrCodeSymbol = null; +qrcode.debug = false; +qrcode.maxImgSize = 1024*1024; + +qrcode.sizeOfDataLengthInfo = [ [ 10, 9, 8, 8 ], [ 12, 11, 16, 10 ], [ 14, 13, 16, 12 ] ]; + +qrcode.callback = null; + +qrcode.decode = function(src){ + + if(arguments.length==0) + { + var canvas_qr = document.getElementById("qr-canvas"); + var context = canvas_qr.getContext('2d'); + qrcode.width = canvas_qr.width; + qrcode.height = canvas_qr.height; + qrcode.imagedata = context.getImageData(0, 0, qrcode.width, qrcode.height); + qrcode.result = qrcode.process(context); + if(qrcode.callback!=null) + qrcode.callback(qrcode.result); + return qrcode.result; + } + else + { + var image = new Image(); + image.onload=function(){ + //var canvas_qr = document.getElementById("qr-canvas"); + var canvas_qr = document.createElement('canvas'); + var context = canvas_qr.getContext('2d'); + var nheight = image.height; + var nwidth = image.width; + if(image.width*image.height>qrcode.maxImgSize) + { + var ir = image.width / image.height; + nheight = Math.sqrt(qrcode.maxImgSize/ir); + nwidth=ir*nheight; + } + + canvas_qr.width = nwidth; + canvas_qr.height = nheight; + + context.drawImage(image, 0, 0, canvas_qr.width, canvas_qr.height ); + qrcode.width = canvas_qr.width; + qrcode.height = canvas_qr.height; + try{ + qrcode.imagedata = context.getImageData(0, 0, canvas_qr.width, canvas_qr.height); + }catch(e){ + qrcode.result = "Cross domain image reading not supported in your browser! Save it to your computer then drag and drop the file!"; + if(qrcode.callback!=null) + qrcode.callback(qrcode.result); + return; + } + + try + { + qrcode.result = qrcode.process(context); + } + catch(e) + { + console.log(e); + qrcode.result = "error decoding QR Code"; + } + if(qrcode.callback!=null) + qrcode.callback(qrcode.result); + } + image.src = src; + } +} + +qrcode.isUrl = function(s) +{ + var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; + return regexp.test(s); +} + +qrcode.decode_url = function (s) +{ + var escaped = ""; + try{ + escaped = escape( s ); + } + catch(e) + { + console.log(e); + escaped = s; + } + var ret = ""; + try{ + ret = decodeURIComponent( escaped ); + } + catch(e) + { + console.log(e); + ret = escaped; + } + return ret; +} + +qrcode.decode_utf8 = function ( s ) +{ + if(qrcode.isUrl(s)) + return qrcode.decode_url(s); + else + return s; +} + +qrcode.process = function(ctx){ + + var start = new Date().getTime(); + + var image = qrcode.grayScaleToBitmap(qrcode.grayscale()); + //var image = qrcode.binarize(128); + + if(qrcode.debug) + { + for (var y = 0; y < qrcode.height; y++) + { + for (var x = 0; x < qrcode.width; x++) + { + var point = (x * 4) + (y * qrcode.width * 4); + qrcode.imagedata.data[point] = image[x+y*qrcode.width]?0:0; + qrcode.imagedata.data[point+1] = image[x+y*qrcode.width]?0:0; + qrcode.imagedata.data[point+2] = image[x+y*qrcode.width]?255:0; + } + } + ctx.putImageData(qrcode.imagedata, 0, 0); + } + + //var finderPatternInfo = new FinderPatternFinder().findFinderPattern(image); + + var detector = new Detector(image); + + var qRCodeMatrix = detector.detect(); + + /*for (var y = 0; y < qRCodeMatrix.bits.Height; y++) + { + for (var x = 0; x < qRCodeMatrix.bits.Width; x++) + { + var point = (x * 4*2) + (y*2 * qrcode.width * 4); + qrcode.imagedata.data[point] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0; + qrcode.imagedata.data[point+1] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0; + qrcode.imagedata.data[point+2] = qRCodeMatrix.bits.get_Renamed(x,y)?255:0; + } + }*/ + if(qrcode.debug) + ctx.putImageData(qrcode.imagedata, 0, 0); + + var reader = Decoder.decode(qRCodeMatrix.bits); + var data = reader.DataByte; + var str=""; + for(var i=0;i minmax[ax][ay][1]) + minmax[ax][ay][1] = target; + } + } + //minmax[ax][ay][0] = (minmax[ax][ay][0] + minmax[ax][ay][1]) / 2; + } + } + var middle = new Array(numSqrtArea); + for (var i3 = 0; i3 < numSqrtArea; i3++) + { + middle[i3] = new Array(numSqrtArea); + } + for (var ay = 0; ay < numSqrtArea; ay++) + { + for (var ax = 0; ax < numSqrtArea; ax++) + { + middle[ax][ay] = Math.floor((minmax[ax][ay][0] + minmax[ax][ay][1]) / 2); + //Console.out.print(middle[ax][ay] + ","); + } + //Console.out.println(""); + } + //Console.out.println(""); + + return middle; +} + +qrcode.grayScaleToBitmap=function(grayScale) +{ + var middle = qrcode.getMiddleBrightnessPerArea(grayScale); + var sqrtNumArea = middle.length; + var areaWidth = Math.floor(qrcode.width / sqrtNumArea); + var areaHeight = Math.floor(qrcode.height / sqrtNumArea); + var bitmap = new Array(qrcode.height*qrcode.width); + + for (var ay = 0; ay < sqrtNumArea; ay++) + { + for (var ax = 0; ax < sqrtNumArea; ax++) + { + for (var dy = 0; dy < areaHeight; dy++) + { + for (var dx = 0; dx < areaWidth; dx++) + { + bitmap[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] = (grayScale[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] < middle[ax][ay])?true:false; + } + } + } + } + return bitmap; +} + +qrcode.grayscale = function(){ + var ret = new Array(qrcode.width*qrcode.height); + for (var y = 0; y < qrcode.height; y++) + { + for (var x = 0; x < qrcode.width; x++) + { + var gray = qrcode.getPixel(x, y); + + ret[x+y*qrcode.width] = gray; + } + } + return ret; +} + + + + +function URShift( number, bits) +{ + if (number >= 0) + return number >> bits; + else + return (number >> bits) + (2 << ~bits); +} + + +Array.prototype.remove = function(from, to) { + var rest = this.slice((to || from) + 1 || this.length); + this.length = from < 0 ? this.length + from : from; + return this.push.apply(this, rest); +}; diff --git a/js/jsqrcode/rsdecoder.js b/js/jsqrcode/rsdecoder.js new file mode 100644 index 000000000..640769a5d --- /dev/null +++ b/js/jsqrcode/rsdecoder.js @@ -0,0 +1,178 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + +function ReedSolomonDecoder(field) +{ + this.field = field; + this.decode=function(received, twoS) + { + var poly = new GF256Poly(this.field, received); + var syndromeCoefficients = new Array(twoS); + for(var i=0;i= b's + if (a.Degree < b.Degree) + { + var temp = a; + a = b; + b = temp; + } + + var rLast = a; + var r = b; + var sLast = this.field.One; + var s = this.field.Zero; + var tLast = this.field.Zero; + var t = this.field.One; + + // Run Euclidean algorithm until r's degree is less than R/2 + while (r.Degree >= Math.floor(R / 2)) + { + var rLastLast = rLast; + var sLastLast = sLast; + var tLastLast = tLast; + rLast = r; + sLast = s; + tLast = t; + + // Divide rLastLast by rLast, with quotient in q and remainder in r + if (rLast.Zero) + { + // Oops, Euclidean algorithm already terminated? + throw "r_{i-1} was zero"; + } + r = rLastLast; + var q = this.field.Zero; + var denominatorLeadingTerm = rLast.getCoefficient(rLast.Degree); + var dltInverse = this.field.inverse(denominatorLeadingTerm); + while (r.Degree >= rLast.Degree && !r.Zero) + { + var degreeDiff = r.Degree - rLast.Degree; + var scale = this.field.multiply(r.getCoefficient(r.Degree), dltInverse); + q = q.addOrSubtract(this.field.buildMonomial(degreeDiff, scale)); + r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale)); + //r.EXE(); + } + + s = q.multiply1(sLast).addOrSubtract(sLastLast); + t = q.multiply1(tLast).addOrSubtract(tLastLast); + } + + var sigmaTildeAtZero = t.getCoefficient(0); + if (sigmaTildeAtZero == 0) + { + throw "ReedSolomonException sigmaTilde(0) was zero"; + } + + var inverse = this.field.inverse(sigmaTildeAtZero); + var sigma = t.multiply2(inverse); + var omega = r.multiply2(inverse); + return new Array(sigma, omega); + } + this.findErrorLocations=function( errorLocator) + { + // This is a direct application of Chien's search + var numErrors = errorLocator.Degree; + if (numErrors == 1) + { + // shortcut + return new Array(errorLocator.getCoefficient(1)); + } + var result = new Array(numErrors); + var e = 0; + for (var i = 1; i < 256 && e < numErrors; i++) + { + if (errorLocator.evaluateAt(i) == 0) + { + result[e] = this.field.inverse(i); + e++; + } + } + if (e != numErrors) + { + throw "Error locator degree does not match number of roots"; + } + return result; + } + this.findErrorMagnitudes=function( errorEvaluator, errorLocations, dataMatrix) + { + // This is directly applying Forney's Formula + var s = errorLocations.length; + var result = new Array(s); + for (var i = 0; i < s; i++) + { + var xiInverse = this.field.inverse(errorLocations[i]); + var denominator = 1; + for (var j = 0; j < s; j++) + { + if (i != j) + { + denominator = this.field.multiply(denominator, GF256.addOrSubtract(1, this.field.multiply(errorLocations[j], xiInverse))); + } + } + result[i] = this.field.multiply(errorEvaluator.evaluateAt(xiInverse), this.field.inverse(denominator)); + // Thanks to sanfordsquires for this fix: + if (dataMatrix) + { + result[i] = this.field.multiply(result[i], xiInverse); + } + } + return result; + } +} \ No newline at end of file diff --git a/js/jsqrcode/version.js b/js/jsqrcode/version.js new file mode 100644 index 000000000..4e19c7f1a --- /dev/null +++ b/js/jsqrcode/version.js @@ -0,0 +1,261 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* 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. +*/ + + + +function ECB(count, dataCodewords) +{ + this.count = count; + this.dataCodewords = dataCodewords; + + this.__defineGetter__("Count", function() + { + return this.count; + }); + this.__defineGetter__("DataCodewords", function() + { + return this.dataCodewords; + }); +} + +function ECBlocks( ecCodewordsPerBlock, ecBlocks1, ecBlocks2) +{ + this.ecCodewordsPerBlock = ecCodewordsPerBlock; + if(ecBlocks2) + this.ecBlocks = new Array(ecBlocks1, ecBlocks2); + else + this.ecBlocks = new Array(ecBlocks1); + + this.__defineGetter__("ECCodewordsPerBlock", function() + { + return this.ecCodewordsPerBlock; + }); + + this.__defineGetter__("TotalECCodewords", function() + { + return this.ecCodewordsPerBlock * this.NumBlocks; + }); + + this.__defineGetter__("NumBlocks", function() + { + var total = 0; + for (var i = 0; i < this.ecBlocks.length; i++) + { + total += this.ecBlocks[i].length; + } + return total; + }); + + this.getECBlocks=function() + { + return this.ecBlocks; + } +} + +function Version( versionNumber, alignmentPatternCenters, ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4) +{ + this.versionNumber = versionNumber; + this.alignmentPatternCenters = alignmentPatternCenters; + this.ecBlocks = new Array(ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4); + + var total = 0; + var ecCodewords = ecBlocks1.ECCodewordsPerBlock; + var ecbArray = ecBlocks1.getECBlocks(); + for (var i = 0; i < ecbArray.length; i++) + { + var ecBlock = ecbArray[i]; + total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords); + } + this.totalCodewords = total; + + this.__defineGetter__("VersionNumber", function() + { + return this.versionNumber; + }); + + this.__defineGetter__("AlignmentPatternCenters", function() + { + return this.alignmentPatternCenters; + }); + this.__defineGetter__("TotalCodewords", function() + { + return this.totalCodewords; + }); + this.__defineGetter__("DimensionForVersion", function() + { + return 17 + 4 * this.versionNumber; + }); + + this.buildFunctionPattern=function() + { + var dimension = this.DimensionForVersion; + var bitMatrix = new BitMatrix(dimension); + + // Top left finder pattern + separator + format + bitMatrix.setRegion(0, 0, 9, 9); + // Top right finder pattern + separator + format + bitMatrix.setRegion(dimension - 8, 0, 8, 9); + // Bottom left finder pattern + separator + format + bitMatrix.setRegion(0, dimension - 8, 9, 8); + + // Alignment patterns + var max = this.alignmentPatternCenters.length; + for (var x = 0; x < max; x++) + { + var i = this.alignmentPatternCenters[x] - 2; + for (var y = 0; y < max; y++) + { + if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) + { + // No alignment patterns near the three finder paterns + continue; + } + bitMatrix.setRegion(this.alignmentPatternCenters[y] - 2, i, 5, 5); + } + } + + // Vertical timing pattern + bitMatrix.setRegion(6, 9, 1, dimension - 17); + // Horizontal timing pattern + bitMatrix.setRegion(9, 6, dimension - 17, 1); + + if (this.versionNumber > 6) + { + // Version info, top right + bitMatrix.setRegion(dimension - 11, 0, 3, 6); + // Version info, bottom left + bitMatrix.setRegion(0, dimension - 11, 6, 3); + } + + return bitMatrix; + } + this.getECBlocksForLevel=function( ecLevel) + { + return this.ecBlocks[ecLevel.ordinal()]; + } +} + +Version.VERSION_DECODE_INFO = new Array(0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, 0x27541, 0x28C69); + +Version.VERSIONS = buildVersions(); + +Version.getVersionForNumber=function( versionNumber) +{ + if (versionNumber < 1 || versionNumber > 40) + { + throw "ArgumentException"; + } + return Version.VERSIONS[versionNumber - 1]; +} + +Version.getProvisionalVersionForDimension=function(dimension) +{ + if (dimension % 4 != 1) + { + throw "Error getProvisionalVersionForDimension"; + } + try + { + return Version.getVersionForNumber((dimension - 17) >> 2); + } + catch ( iae) + { + throw "Error getVersionForNumber"; + } +} + +Version.decodeVersionInformation=function( versionBits) +{ + var bestDifference = 0xffffffff; + var bestVersion = 0; + for (var i = 0; i < Version.VERSION_DECODE_INFO.length; i++) + { + var targetVersion = Version.VERSION_DECODE_INFO[i]; + // Do the version info bits match exactly? done. + if (targetVersion == versionBits) + { + return this.getVersionForNumber(i + 7); + } + // Otherwise see if this is the closest to a real version info bit string + // we have seen so far + var bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion); + if (bitsDifference < bestDifference) + { + bestVersion = i + 7; + bestDifference = bitsDifference; + } + } + // We can tolerate up to 3 bits of error since no two version info codewords will + // differ in less than 4 bits. + if (bestDifference <= 3) + { + return this.getVersionForNumber(bestVersion); + } + // If we didn't find a close enough match, fail + return null; +} + +function buildVersions() +{ + return new Array(new Version(1, new Array(), new ECBlocks(7, new ECB(1, 19)), new ECBlocks(10, new ECB(1, 16)), new ECBlocks(13, new ECB(1, 13)), new ECBlocks(17, new ECB(1, 9))), + new Version(2, new Array(6, 18), new ECBlocks(10, new ECB(1, 34)), new ECBlocks(16, new ECB(1, 28)), new ECBlocks(22, new ECB(1, 22)), new ECBlocks(28, new ECB(1, 16))), + new Version(3, new Array(6, 22), new ECBlocks(15, new ECB(1, 55)), new ECBlocks(26, new ECB(1, 44)), new ECBlocks(18, new ECB(2, 17)), new ECBlocks(22, new ECB(2, 13))), + new Version(4, new Array(6, 26), new ECBlocks(20, new ECB(1, 80)), new ECBlocks(18, new ECB(2, 32)), new ECBlocks(26, new ECB(2, 24)), new ECBlocks(16, new ECB(4, 9))), + new Version(5, new Array(6, 30), new ECBlocks(26, new ECB(1, 108)), new ECBlocks(24, new ECB(2, 43)), new ECBlocks(18, new ECB(2, 15), new ECB(2, 16)), new ECBlocks(22, new ECB(2, 11), new ECB(2, 12))), + new Version(6, new Array(6, 34), new ECBlocks(18, new ECB(2, 68)), new ECBlocks(16, new ECB(4, 27)), new ECBlocks(24, new ECB(4, 19)), new ECBlocks(28, new ECB(4, 15))), + new Version(7, new Array(6, 22, 38), new ECBlocks(20, new ECB(2, 78)), new ECBlocks(18, new ECB(4, 31)), new ECBlocks(18, new ECB(2, 14), new ECB(4, 15)), new ECBlocks(26, new ECB(4, 13), new ECB(1, 14))), + new Version(8, new Array(6, 24, 42), new ECBlocks(24, new ECB(2, 97)), new ECBlocks(22, new ECB(2, 38), new ECB(2, 39)), new ECBlocks(22, new ECB(4, 18), new ECB(2, 19)), new ECBlocks(26, new ECB(4, 14), new ECB(2, 15))), + new Version(9, new Array(6, 26, 46), new ECBlocks(30, new ECB(2, 116)), new ECBlocks(22, new ECB(3, 36), new ECB(2, 37)), new ECBlocks(20, new ECB(4, 16), new ECB(4, 17)), new ECBlocks(24, new ECB(4, 12), new ECB(4, 13))), + new Version(10, new Array(6, 28, 50), new ECBlocks(18, new ECB(2, 68), new ECB(2, 69)), new ECBlocks(26, new ECB(4, 43), new ECB(1, 44)), new ECBlocks(24, new ECB(6, 19), new ECB(2, 20)), new ECBlocks(28, new ECB(6, 15), new ECB(2, 16))), + new Version(11, new Array(6, 30, 54), new ECBlocks(20, new ECB(4, 81)), new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))), + new Version(12, new Array(6, 32, 58), new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))), + new Version(13, new Array(6, 34, 62), new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))), + new Version(14, new Array(6, 26, 46, 66), new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))), + new Version(15, new Array(6, 26, 48, 70), new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))), + new Version(16, new Array(6, 26, 50, 74), new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))), + new Version(17, new Array(6, 30, 54, 78), new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))), + new Version(18, new Array(6, 30, 56, 82), new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))), + new Version(19, new Array(6, 30, 58, 86), new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))), + new Version(20, new Array(6, 34, 62, 90), new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))), + new Version(21, new Array(6, 28, 50, 72, 94), new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))), + new Version(22, new Array(6, 26, 50, 74, 98), new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))), + new Version(23, new Array(6, 30, 54, 74, 102), new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))), + new Version(24, new Array(6, 28, 54, 80, 106), new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))), + new Version(25, new Array(6, 32, 58, 84, 110), new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))), + new Version(26, new Array(6, 30, 58, 86, 114), new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))), + new Version(27, new Array(6, 34, 62, 90, 118), new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), new ECB(28, 16))), + new Version(28, new Array(6, 26, 50, 74, 98, 122), new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))), + new Version(29, new Array(6, 30, 54, 78, 102, 126), new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))), + new Version(30, new Array(6, 26, 52, 78, 104, 130), new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))), + new Version(31, new Array(6, 30, 56, 82, 108, 134), new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))), + new Version(32, new Array(6, 34, 60, 86, 112, 138), new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))), + new Version(33, new Array(6, 30, 58, 86, 114, 142), new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))), + new Version(34, new Array(6, 34, 62, 90, 118, 146), new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))), + new Version(35, new Array(6, 30, 54, 78, 102, 126, 150), new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new ECB(14, 25)),new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))), + new Version(36, new Array(6, 24, 50, 76, 102, 128, 154), new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))), + new Version(37, new Array(6, 28, 54, 80, 106, 132, 158), new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))), + new Version(38, new Array(6, 32, 58, 84, 110, 136, 162), new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))), + new Version(39, new Array(6, 26, 54, 82, 110, 138, 166), new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))), + new Version(40, new Array(6, 30, 58, 86, 114, 142, 170), new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16)))); +} \ No newline at end of file diff --git a/js/md5.js b/js/md5.js new file mode 100644 index 000000000..0fae5ca1d --- /dev/null +++ b/js/md5.js @@ -0,0 +1,19 @@ +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +var CryptoJS=CryptoJS||function(s,p){var m={},l=m.lib={},n=function(){},r=l.Base={extend:function(b){n.prototype=this;var h=new n;b&&h.mixIn(b);h.hasOwnProperty("init")||(h.init=function(){h.$super.init.apply(this,arguments)});h.init.prototype=h;h.$super=this;return h},create:function(){var b=this.extend();b.init.apply(b,arguments);return b},init:function(){},mixIn:function(b){for(var h in b)b.hasOwnProperty(h)&&(this[h]=b[h]);b.hasOwnProperty("toString")&&(this.toString=b.toString)},clone:function(){return this.init.prototype.extend(this)}}, +q=l.WordArray=r.extend({init:function(b,h){b=this.words=b||[];this.sigBytes=h!=p?h:4*b.length},toString:function(b){return(b||t).stringify(this)},concat:function(b){var h=this.words,a=b.words,j=this.sigBytes;b=b.sigBytes;this.clamp();if(j%4)for(var g=0;g>>2]|=(a[g>>>2]>>>24-8*(g%4)&255)<<24-8*((j+g)%4);else if(65535>>2]=a[g>>>2];else h.push.apply(h,a);this.sigBytes+=b;return this},clamp:function(){var b=this.words,h=this.sigBytes;b[h>>>2]&=4294967295<< +32-8*(h%4);b.length=s.ceil(h/4)},clone:function(){var b=r.clone.call(this);b.words=this.words.slice(0);return b},random:function(b){for(var h=[],a=0;a>>2]>>>24-8*(j%4)&255;g.push((k>>>4).toString(16));g.push((k&15).toString(16))}return g.join("")},parse:function(b){for(var a=b.length,g=[],j=0;j>>3]|=parseInt(b.substr(j, +2),16)<<24-4*(j%8);return new q.init(g,a/2)}},a=v.Latin1={stringify:function(b){var a=b.words;b=b.sigBytes;for(var g=[],j=0;j>>2]>>>24-8*(j%4)&255));return g.join("")},parse:function(b){for(var a=b.length,g=[],j=0;j>>2]|=(b.charCodeAt(j)&255)<<24-8*(j%4);return new q.init(g,a)}},u=v.Utf8={stringify:function(b){try{return decodeURIComponent(escape(a.stringify(b)))}catch(g){throw Error("Malformed UTF-8 data");}},parse:function(b){return a.parse(unescape(encodeURIComponent(b)))}}, +g=l.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(b){"string"==typeof b&&(b=u.parse(b));this._data.concat(b);this._nDataBytes+=b.sigBytes},_process:function(b){var a=this._data,g=a.words,j=a.sigBytes,k=this.blockSize,m=j/(4*k),m=b?s.ceil(m):s.max((m|0)-this._minBufferSize,0);b=m*k;j=s.min(4*b,j);if(b){for(var l=0;l>>32-j)+k}function m(a,k,b,h,l,j,m){a=a+(k&h|b&~h)+l+m;return(a<>>32-j)+k}function l(a,k,b,h,l,j,m){a=a+(k^b^h)+l+m;return(a<>>32-j)+k}function n(a,k,b,h,l,j,m){a=a+(b^(k|~h))+l+m;return(a<>>32-j)+k}for(var r=CryptoJS,q=r.lib,v=q.WordArray,t=q.Hasher,q=r.algo,a=[],u=0;64>u;u++)a[u]=4294967296*s.abs(s.sin(u+1))|0;q=q.MD5=t.extend({_doReset:function(){this._hash=new v.init([1732584193,4023233417,2562383102,271733878])}, +_doProcessBlock:function(g,k){for(var b=0;16>b;b++){var h=k+b,w=g[h];g[h]=(w<<8|w>>>24)&16711935|(w<<24|w>>>8)&4278255360}var b=this._hash.words,h=g[k+0],w=g[k+1],j=g[k+2],q=g[k+3],r=g[k+4],s=g[k+5],t=g[k+6],u=g[k+7],v=g[k+8],x=g[k+9],y=g[k+10],z=g[k+11],A=g[k+12],B=g[k+13],C=g[k+14],D=g[k+15],c=b[0],d=b[1],e=b[2],f=b[3],c=p(c,d,e,f,h,7,a[0]),f=p(f,c,d,e,w,12,a[1]),e=p(e,f,c,d,j,17,a[2]),d=p(d,e,f,c,q,22,a[3]),c=p(c,d,e,f,r,7,a[4]),f=p(f,c,d,e,s,12,a[5]),e=p(e,f,c,d,t,17,a[6]),d=p(d,e,f,c,u,22,a[7]), +c=p(c,d,e,f,v,7,a[8]),f=p(f,c,d,e,x,12,a[9]),e=p(e,f,c,d,y,17,a[10]),d=p(d,e,f,c,z,22,a[11]),c=p(c,d,e,f,A,7,a[12]),f=p(f,c,d,e,B,12,a[13]),e=p(e,f,c,d,C,17,a[14]),d=p(d,e,f,c,D,22,a[15]),c=m(c,d,e,f,w,5,a[16]),f=m(f,c,d,e,t,9,a[17]),e=m(e,f,c,d,z,14,a[18]),d=m(d,e,f,c,h,20,a[19]),c=m(c,d,e,f,s,5,a[20]),f=m(f,c,d,e,y,9,a[21]),e=m(e,f,c,d,D,14,a[22]),d=m(d,e,f,c,r,20,a[23]),c=m(c,d,e,f,x,5,a[24]),f=m(f,c,d,e,C,9,a[25]),e=m(e,f,c,d,q,14,a[26]),d=m(d,e,f,c,v,20,a[27]),c=m(c,d,e,f,B,5,a[28]),f=m(f,c, +d,e,j,9,a[29]),e=m(e,f,c,d,u,14,a[30]),d=m(d,e,f,c,A,20,a[31]),c=l(c,d,e,f,s,4,a[32]),f=l(f,c,d,e,v,11,a[33]),e=l(e,f,c,d,z,16,a[34]),d=l(d,e,f,c,C,23,a[35]),c=l(c,d,e,f,w,4,a[36]),f=l(f,c,d,e,r,11,a[37]),e=l(e,f,c,d,u,16,a[38]),d=l(d,e,f,c,y,23,a[39]),c=l(c,d,e,f,B,4,a[40]),f=l(f,c,d,e,h,11,a[41]),e=l(e,f,c,d,q,16,a[42]),d=l(d,e,f,c,t,23,a[43]),c=l(c,d,e,f,x,4,a[44]),f=l(f,c,d,e,A,11,a[45]),e=l(e,f,c,d,D,16,a[46]),d=l(d,e,f,c,j,23,a[47]),c=n(c,d,e,f,h,6,a[48]),f=n(f,c,d,e,u,10,a[49]),e=n(e,f,c,d, +C,15,a[50]),d=n(d,e,f,c,s,21,a[51]),c=n(c,d,e,f,A,6,a[52]),f=n(f,c,d,e,q,10,a[53]),e=n(e,f,c,d,y,15,a[54]),d=n(d,e,f,c,w,21,a[55]),c=n(c,d,e,f,v,6,a[56]),f=n(f,c,d,e,D,10,a[57]),e=n(e,f,c,d,t,15,a[58]),d=n(d,e,f,c,B,21,a[59]),c=n(c,d,e,f,r,6,a[60]),f=n(f,c,d,e,z,10,a[61]),e=n(e,f,c,d,j,15,a[62]),d=n(d,e,f,c,x,21,a[63]);b[0]=b[0]+c|0;b[1]=b[1]+d|0;b[2]=b[2]+e|0;b[3]=b[3]+f|0},_doFinalize:function(){var a=this._data,k=a.words,b=8*this._nDataBytes,h=8*a.sigBytes;k[h>>>5]|=128<<24-h%32;var l=s.floor(b/ +4294967296);k[(h+64>>>9<<4)+15]=(l<<8|l>>>24)&16711935|(l<<24|l>>>8)&4278255360;k[(h+64>>>9<<4)+14]=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360;a.sigBytes=4*(k.length+1);this._process();a=this._hash;k=a.words;for(b=0;4>b;b++)h=k[b],k[b]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360;return a},clone:function(){var a=t.clone.call(this);a._hash=this._hash.clone();return a}});r.MD5=t._createHelper(q);r.HmacMD5=t._createHmacHelper(q)})(Math); diff --git a/js/qr.js b/js/qr.js new file mode 100644 index 000000000..bb8167c96 --- /dev/null +++ b/js/qr.js @@ -0,0 +1,4 @@ +var text = location.search.substr(1); +text = decodeURIComponent(text); +document.title = chrome.i18n.getMessage('extName'); +document.body.innerText = text; \ No newline at end of file diff --git a/js/qrcode.js b/js/qrcode.js new file mode 100644 index 000000000..83566a8e1 --- /dev/null +++ b/js/qrcode.js @@ -0,0 +1,618 @@ +/** + * @fileoverview + * - Using the 'QRCode for Javascript library' + * - Fixed dataset of 'QRCode for Javascript library' for support full-spec. + * - this library has no dependencies. + * + * @author davidshimjs + * @see http://www.d-project.com/ + * @see http://jeromeetienne.github.com/jquery-qrcode/ + */ +var QRCode; + +(function () { + //--------------------------------------------------------------------- + // QRCode for JavaScript + // + // Copyright (c) 2009 Kazuhiko Arase + // + // URL: http://www.d-project.com/ + // + // Licensed under the MIT license: + // http://www.opensource.org/licenses/mit-license.php + // + // The word "QR Code" is registered trademark of + // DENSO WAVE INCORPORATED + // http://www.denso-wave.com/qrcode/faqpatent-e.html + // + //--------------------------------------------------------------------- + function QR8bitByte(data) { + this.mode = QRMode.MODE_8BIT_BYTE; + this.data = data; + this.parsedData = []; + + // Added to support UTF-8 Characters + for (var i = 0, l = this.data.length; i < l; i++) { + var byteArray = []; + var code = this.data.charCodeAt(i); + + if (code > 0x10000) { + byteArray[0] = 0xF0 | ((code & 0x1C0000) >>> 18); + byteArray[1] = 0x80 | ((code & 0x3F000) >>> 12); + byteArray[2] = 0x80 | ((code & 0xFC0) >>> 6); + byteArray[3] = 0x80 | (code & 0x3F); + } else if (code > 0x800) { + byteArray[0] = 0xE0 | ((code & 0xF000) >>> 12); + byteArray[1] = 0x80 | ((code & 0xFC0) >>> 6); + byteArray[2] = 0x80 | (code & 0x3F); + } else if (code > 0x80) { + byteArray[0] = 0xC0 | ((code & 0x7C0) >>> 6); + byteArray[1] = 0x80 | (code & 0x3F); + } else { + byteArray[0] = code; + } + + this.parsedData.push(byteArray); + } + + this.parsedData = Array.prototype.concat.apply([], this.parsedData); + + if (this.parsedData.length != this.data.length) { + this.parsedData.unshift(191); + this.parsedData.unshift(187); + this.parsedData.unshift(239); + } + } + + QR8bitByte.prototype = { + getLength: function (buffer) { + return this.parsedData.length; + }, + write: function (buffer) { + for (var i = 0, l = this.parsedData.length; i < l; i++) { + buffer.put(this.parsedData[i], 8); + } + } + }; + + function QRCodeModel(typeNumber, errorCorrectLevel) { + this.typeNumber = typeNumber; + this.errorCorrectLevel = errorCorrectLevel; + this.modules = null; + this.moduleCount = 0; + this.dataCache = null; + this.dataList = []; + } + + QRCodeModel.prototype={addData:function(data){var newData=new QR8bitByte(data);this.dataList.push(newData);this.dataCache=null;},isDark:function(row,col){if(row<0||this.moduleCount<=row||col<0||this.moduleCount<=col){throw new Error(row+","+col);} + return this.modules[row][col];},getModuleCount:function(){return this.moduleCount;},make:function(){this.makeImpl(false,this.getBestMaskPattern());},makeImpl:function(test,maskPattern){this.moduleCount=this.typeNumber*4+17;this.modules=new Array(this.moduleCount);for(var row=0;row=7){this.setupTypeNumber(test);} + if(this.dataCache==null){this.dataCache=QRCodeModel.createData(this.typeNumber,this.errorCorrectLevel,this.dataList);} + this.mapData(this.dataCache,maskPattern);},setupPositionProbePattern:function(row,col){for(var r=-1;r<=7;r++){if(row+r<=-1||this.moduleCount<=row+r)continue;for(var c=-1;c<=7;c++){if(col+c<=-1||this.moduleCount<=col+c)continue;if((0<=r&&r<=6&&(c==0||c==6))||(0<=c&&c<=6&&(r==0||r==6))||(2<=r&&r<=4&&2<=c&&c<=4)){this.modules[row+r][col+c]=true;}else{this.modules[row+r][col+c]=false;}}}},getBestMaskPattern:function(){var minLostPoint=0;var pattern=0;for(var i=0;i<8;i++){this.makeImpl(true,i);var lostPoint=QRUtil.getLostPoint(this);if(i==0||minLostPoint>lostPoint){minLostPoint=lostPoint;pattern=i;}} + return pattern;},createMovieClip:function(target_mc,instance_name,depth){var qr_mc=target_mc.createEmptyMovieClip(instance_name,depth);var cs=1;this.make();for(var row=0;row>i)&1)==1);this.modules[Math.floor(i/3)][i%3+this.moduleCount-8-3]=mod;} + for(var i=0;i<18;i++){var mod=(!test&&((bits>>i)&1)==1);this.modules[i%3+this.moduleCount-8-3][Math.floor(i/3)]=mod;}},setupTypeInfo:function(test,maskPattern){var data=(this.errorCorrectLevel<<3)|maskPattern;var bits=QRUtil.getBCHTypeInfo(data);for(var i=0;i<15;i++){var mod=(!test&&((bits>>i)&1)==1);if(i<6){this.modules[i][8]=mod;}else if(i<8){this.modules[i+1][8]=mod;}else{this.modules[this.moduleCount-15+i][8]=mod;}} + for(var i=0;i<15;i++){var mod=(!test&&((bits>>i)&1)==1);if(i<8){this.modules[8][this.moduleCount-i-1]=mod;}else if(i<9){this.modules[8][15-i-1+1]=mod;}else{this.modules[8][15-i-1]=mod;}} + this.modules[this.moduleCount-8][8]=(!test);},mapData:function(data,maskPattern){var inc=-1;var row=this.moduleCount-1;var bitIndex=7;var byteIndex=0;for(var col=this.moduleCount-1;col>0;col-=2){if(col==6)col--;while(true){for(var c=0;c<2;c++){if(this.modules[row][col-c]==null){var dark=false;if(byteIndex>>bitIndex)&1)==1);} + var mask=QRUtil.getMask(maskPattern,row,col-c);if(mask){dark=!dark;} + this.modules[row][col-c]=dark;bitIndex--;if(bitIndex==-1){byteIndex++;bitIndex=7;}}} + row+=inc;if(row<0||this.moduleCount<=row){row-=inc;inc=-inc;break;}}}}};QRCodeModel.PAD0=0xEC;QRCodeModel.PAD1=0x11;QRCodeModel.createData=function(typeNumber,errorCorrectLevel,dataList){var rsBlocks=QRRSBlock.getRSBlocks(typeNumber,errorCorrectLevel);var buffer=new QRBitBuffer();for(var i=0;itotalDataCount*8){throw new Error("code length overflow. (" + +buffer.getLengthInBits() + +">" + +totalDataCount*8 + +")");} + if(buffer.getLengthInBits()+4<=totalDataCount*8){buffer.put(0,4);} + while(buffer.getLengthInBits()%8!=0){buffer.putBit(false);} + while(true){if(buffer.getLengthInBits()>=totalDataCount*8){break;} + buffer.put(QRCodeModel.PAD0,8);if(buffer.getLengthInBits()>=totalDataCount*8){break;} + buffer.put(QRCodeModel.PAD1,8);} + return QRCodeModel.createBytes(buffer,rsBlocks);};QRCodeModel.createBytes=function(buffer,rsBlocks){var offset=0;var maxDcCount=0;var maxEcCount=0;var dcdata=new Array(rsBlocks.length);var ecdata=new Array(rsBlocks.length);for(var r=0;r=0)?modPoly.get(modIndex):0;}} + var totalCodeCount=0;for(var i=0;i=0){d^=(QRUtil.G15<<(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G15)));} + return((data<<10)|d)^QRUtil.G15_MASK;},getBCHTypeNumber:function(data){var d=data<<12;while(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G18)>=0){d^=(QRUtil.G18<<(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G18)));} + return(data<<12)|d;},getBCHDigit:function(data){var digit=0;while(data!=0){digit++;data>>>=1;} + return digit;},getPatternPosition:function(typeNumber){return QRUtil.PATTERN_POSITION_TABLE[typeNumber-1];},getMask:function(maskPattern,i,j){switch(maskPattern){case QRMaskPattern.PATTERN000:return(i+j)%2==0;case QRMaskPattern.PATTERN001:return i%2==0;case QRMaskPattern.PATTERN010:return j%3==0;case QRMaskPattern.PATTERN011:return(i+j)%3==0;case QRMaskPattern.PATTERN100:return(Math.floor(i/2)+Math.floor(j/3))%2==0;case QRMaskPattern.PATTERN101:return(i*j)%2+(i*j)%3==0;case QRMaskPattern.PATTERN110:return((i*j)%2+(i*j)%3)%2==0;case QRMaskPattern.PATTERN111:return((i*j)%3+(i+j)%2)%2==0;default:throw new Error("bad maskPattern:"+maskPattern);}},getErrorCorrectPolynomial:function(errorCorrectLength){var a=new QRPolynomial([1],0);for(var i=0;i5){lostPoint+=(3+sameCount-5);}}} + for(var row=0;row=256){n-=255;} + return QRMath.EXP_TABLE[n];},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(var i=0;i<8;i++){QRMath.EXP_TABLE[i]=1<>>(7-index%8))&1)==1;},put:function(num,length){for(var i=0;i>>(length-i-1))&1)==1);}},getLengthInBits:function(){return this.length;},putBit:function(bit){var bufIndex=Math.floor(this.length/8);if(this.buffer.length<=bufIndex){this.buffer.push(0);} + if(bit){this.buffer[bufIndex]|=(0x80>>>(this.length%8));} + this.length++;}};var QRCodeLimitLength=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]]; + + function _isSupportCanvas() { + return typeof CanvasRenderingContext2D != "undefined"; + } + + // android 2.x doesn't support Data-URI spec + function _getAndroid() { + var android = false; + var sAgent = navigator.userAgent; + + if (/android/i.test(sAgent)) { // android + android = true; + aMat = sAgent.toString().match(/android ([0-9]\.[0-9])/i); + + if (aMat && aMat[1]) { + android = parseFloat(aMat[1]); + } + } + + return android; + } + + var svgDrawer = (function() { + + var Drawing = function (el, htOption) { + this._el = el; + this._htOption = htOption; + }; + + Drawing.prototype.draw = function (oQRCode) { + var _htOption = this._htOption; + var _el = this._el; + var nCount = oQRCode.getModuleCount(); + var nWidth = Math.floor(_htOption.width / nCount); + var nHeight = Math.floor(_htOption.height / nCount); + + this.clear(); + + function makeSVG(tag, attrs) { + var el = document.createElementNS('http://www.w3.org/2000/svg', tag); + for (var k in attrs) + if (attrs.hasOwnProperty(k)) el.setAttribute(k, attrs[k]); + return el; + } + + var svg = makeSVG("svg" , {'viewBox': '0 0 ' + String(nCount) + " " + String(nCount), 'width': '100%', 'height': '100%', 'fill': _htOption.colorLight}); + svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); + _el.appendChild(svg); + + svg.appendChild(makeSVG("rect", {"fill": _htOption.colorDark, "width": "1", "height": "1", "id": "template"})); + + for (var row = 0; row < nCount; row++) { + for (var col = 0; col < nCount; col++) { + if (oQRCode.isDark(row, col)) { + var child = makeSVG("use", {"x": String(row), "y": String(col)}); + child.setAttributeNS("http://www.w3.org/1999/xlink", "href", "#template") + svg.appendChild(child); + } + } + } + }; + Drawing.prototype.clear = function () { + while (this._el.hasChildNodes()) + this._el.removeChild(this._el.lastChild); + }; + return Drawing; + })(); + + var useSVG = document.documentElement.tagName.toLowerCase() === "svg"; + + // Drawing in DOM by using Table tag + var Drawing = useSVG ? svgDrawer : !_isSupportCanvas() ? (function () { + var Drawing = function (el, htOption) { + this._el = el; + this._htOption = htOption; + }; + + /** + * Draw the QRCode + * + * @param {QRCode} oQRCode + */ + Drawing.prototype.draw = function (oQRCode) { + var _htOption = this._htOption; + var _el = this._el; + var nCount = oQRCode.getModuleCount(); + var nWidth = Math.floor(_htOption.width / nCount); + var nHeight = Math.floor(_htOption.height / nCount); + var aHTML = ['']; + + for (var row = 0; row < nCount; row++) { + aHTML.push(''); + + for (var col = 0; col < nCount; col++) { + aHTML.push(''); + } + + aHTML.push(''); + } + + aHTML.push('
'); + _el.innerHTML = aHTML.join(''); + + // Fix the margin values as real size. + var elTable = _el.childNodes[0]; + var nLeftMarginTable = (_htOption.width - elTable.offsetWidth) / 2; + var nTopMarginTable = (_htOption.height - elTable.offsetHeight) / 2; + + if (nLeftMarginTable > 0 && nTopMarginTable > 0) { + elTable.style.margin = nTopMarginTable + "px " + nLeftMarginTable + "px"; + } + }; + + /** + * Clear the QRCode + */ + Drawing.prototype.clear = function () { + this._el.innerHTML = ''; + }; + + return Drawing; + })() : (function () { // Drawing in Canvas + function _onMakeImage() { + if(this._callback){ + this._elCanvas.style.display = "none"; + this._callback(this._elCanvas.toDataURL("image/png")); + } + else{ + this._elImage.src = this._elCanvas.toDataURL("image/png"); + this._elImage.style.display = "block"; + this._elCanvas.style.display = "none"; + } + } + + // Android 2.1 bug workaround + // http://code.google.com/p/android/issues/detail?id=5141 + if (this._android && this._android <= 2.1) { + var factor = 1 / window.devicePixelRatio; + var drawImage = CanvasRenderingContext2D.prototype.drawImage; + CanvasRenderingContext2D.prototype.drawImage = function (image, sx, sy, sw, sh, dx, dy, dw, dh) { + if (("nodeName" in image) && /img/i.test(image.nodeName)) { + for (var i = arguments.length - 1; i >= 1; i--) { + arguments[i] = arguments[i] * factor; + } + } else if (typeof dw == "undefined") { + arguments[1] *= factor; + arguments[2] *= factor; + arguments[3] *= factor; + arguments[4] *= factor; + } + + drawImage.apply(this, arguments); + }; + } + + /** + * Check whether the user's browser supports Data URI or not + * + * @private + * @param {Function} fSuccess Occurs if it supports Data URI + * @param {Function} fFail Occurs if it doesn't support Data URI + */ + function _safeSetDataURI(fSuccess, fFail) { + var self = this; + self._fFail = fFail; + self._fSuccess = fSuccess; + + // Check it just once + if (self._bSupportDataURI === null) { + var el = document.createElement("img"); + var fOnError = function() { + self._bSupportDataURI = false; + + if (self._fFail) { + _fFail.call(self); + } + }; + var fOnSuccess = function() { + self._bSupportDataURI = true; + + if (self._fSuccess) { + self._fSuccess.call(self); + } + }; + + el.onabort = fOnError; + el.onerror = fOnError; + el.onload = fOnSuccess; + el.src = "data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; // the Image contains 1px data. + return; + } else if (self._bSupportDataURI === true && self._fSuccess) { + self._fSuccess.call(self); + } else if (self._bSupportDataURI === false && self._fFail) { + self._fFail.call(self); + } + }; + + /** + * Drawing QRCode by using canvas + * + * @constructor + * @param {HTMLElement} el + * @param {Object} htOption QRCode Options + */ + var Drawing = function (el, htOption, callback) { + this._bIsPainted = false; + this._android = _getAndroid(); + + this._htOption = htOption; + this._elCanvas = document.createElement("canvas"); + this._elCanvas.width = htOption.width+10; + this._elCanvas.height = htOption.height+10; + el.appendChild(this._elCanvas); + this._el = el; + this._callback = callback; + this._oContext = this._elCanvas.getContext("2d"); + this._bIsPainted = false; + this._elImage = document.createElement("img"); + this._elImage.alt = "Scan me!"; + this._elImage.style.display = "none"; + this._el.appendChild(this._elImage); + this._bSupportDataURI = null; + }; + + /** + * Draw the QRCode + * + * @param {QRCode} oQRCode + */ + Drawing.prototype.draw = function (oQRCode) { + var _elImage = this._elImage; + var _oContext = this._oContext; + var _htOption = this._htOption; + + var nCount = oQRCode.getModuleCount(); + var nWidth = _htOption.width / nCount; + var nHeight = _htOption.height / nCount; + var nRoundedWidth = Math.round(nWidth); + var nRoundedHeight = Math.round(nHeight); + + _elImage.style.display = "none"; + this.clear(); + + _oContext.fillStyle = _htOption.colorLight; + _oContext.fillRect(0, 0, _htOption.width+10, _htOption.height+10); + for (var row = 0; row < nCount; row++) { + for (var col = 0; col < nCount; col++) { + var bIsDark = oQRCode.isDark(row, col); + var nLeft = col * nWidth + 5; + var nTop = row * nHeight + 5; + _oContext.strokeStyle = bIsDark ? _htOption.colorDark : _htOption.colorLight; + _oContext.lineWidth = 1; + _oContext.fillStyle = bIsDark ? _htOption.colorDark : _htOption.colorLight; + _oContext.fillRect(nLeft, nTop, nWidth, nHeight); + + _oContext.strokeRect( + Math.floor(nLeft) + 0.5, + Math.floor(nTop) + 0.5, + nRoundedWidth, + nRoundedHeight + ); + + _oContext.strokeRect( + Math.ceil(nLeft) - 0.5, + Math.ceil(nTop) - 0.5, + nRoundedWidth, + nRoundedHeight + ); + } + } + + this._bIsPainted = true; + }; + + /** + * Make the image from Canvas if the browser supports Data URI. + */ + Drawing.prototype.makeImage = function () { + if (this._bIsPainted) { + _safeSetDataURI.call(this, _onMakeImage); + } + }; + + /** + * Return whether the QRCode is painted or not + * + * @return {Boolean} + */ + Drawing.prototype.isPainted = function () { + return this._bIsPainted; + }; + + /** + * Clear the QRCode + */ + Drawing.prototype.clear = function () { + this._oContext.clearRect(0, 0, this._elCanvas.width, this._elCanvas.height); + this._bIsPainted = false; + }; + + /** + * @private + * @param {Number} nNumber + */ + Drawing.prototype.round = function (nNumber) { + if (!nNumber) { + return nNumber; + } + + return Math.floor(nNumber * 1000) / 1000; + }; + + return Drawing; + })(); + + /** + * Get the type by string length + * + * @private + * @param {String} sText + * @param {Number} nCorrectLevel + * @return {Number} type + */ + function _getTypeNumber(sText, nCorrectLevel) { + var nType = 1; + var length = _getUTF8Length(sText); + + for (var i = 0, len = QRCodeLimitLength.length; i <= len; i++) { + var nLimit = 0; + + switch (nCorrectLevel) { + case QRErrorCorrectLevel.L : + nLimit = QRCodeLimitLength[i][0]; + break; + case QRErrorCorrectLevel.M : + nLimit = QRCodeLimitLength[i][1]; + break; + case QRErrorCorrectLevel.Q : + nLimit = QRCodeLimitLength[i][2]; + break; + case QRErrorCorrectLevel.H : + nLimit = QRCodeLimitLength[i][3]; + break; + } + + if (length <= nLimit) { + break; + } else { + nType++; + } + } + + if (nType > QRCodeLimitLength.length) { + throw new Error("Too long data"); + } + + return nType; + } + + function _getUTF8Length(sText) { + var replacedText = encodeURI(sText).toString().replace(/\%[0-9a-fA-F]{2}/g, 'a'); + return replacedText.length + (replacedText.length != sText ? 3 : 0); + } + + /** + * @class QRCode + * @constructor + * @example + * new QRCode(document.getElementById("test"), "http://jindo.dev.naver.com/collie"); + * + * @example + * var oQRCode = new QRCode("test", { + * text : "http://naver.com", + * width : 128, + * height : 128 + * }); + * + * oQRCode.clear(); // Clear the QRCode. + * oQRCode.makeCode("http://map.naver.com"); // Re-create the QRCode. + * + * @param {HTMLElement|String} el target element or 'id' attribute of element. + * @param {Object|String} vOption + * @param {String} vOption.text QRCode link data + * @param {Number} [vOption.width=256] + * @param {Number} [vOption.height=256] + * @param {String} [vOption.colorDark="#000000"] + * @param {String} [vOption.colorLight="#ffffff"] + * @param {QRCode.CorrectLevel} [vOption.correctLevel=QRCode.CorrectLevel.H] [L|M|Q|H] + */ + QRCode = function (el, vOption, callback) { + this._htOption = { + width : 256, + height : 256, + typeNumber : 4, + colorDark : "#000000", + colorLight : "#ffffff", + correctLevel : QRErrorCorrectLevel.H + }; + + if (typeof vOption === 'string') { + vOption = { + text : vOption + }; + } + + // Overwrites options + if (vOption) { + for (var i in vOption) { + this._htOption[i] = vOption[i]; + } + } + + if (typeof el == "string") { + el = document.getElementById(el); + } + + this._callback = callback; + this._android = _getAndroid(); + this._el = el; + this._oQRCode = null; + this._oDrawing = new Drawing(this._el, this._htOption, this._callback); + + if (this._htOption.text) { + this.makeCode(this._htOption.text); + } + }; + + /** + * Make the QRCode + * + * @param {String} sText link data + */ + QRCode.prototype.makeCode = function (sText) { + this._oQRCode = new QRCodeModel(_getTypeNumber(sText, this._htOption.correctLevel), this._htOption.correctLevel); + this._oQRCode.addData(sText); + this._oQRCode.make(); + //this._el.title = sText; + this._oDrawing.draw(this._oQRCode); + this.makeImage(); + }; + + /** + * Make the Image from Canvas element + * - It occurs automatically + * - Android below 3 doesn't support Data-URI spec. + * + * @private + */ + QRCode.prototype.makeImage = function () { + if (typeof this._oDrawing.makeImage == "function" && (!this._android || this._android >= 3)) { + this._oDrawing.makeImage(); + } + }; + + /** + * Clear the QRCode + */ + QRCode.prototype.clear = function () { + this._oDrawing.clear(); + }; + + /** + * @name QRCode.CorrectLevel + */ + QRCode.CorrectLevel = QRErrorCorrectLevel; +})(); diff --git a/js/sha.js b/js/sha.js new file mode 100755 index 000000000..af212fba0 --- /dev/null +++ b/js/sha.js @@ -0,0 +1,45 @@ +/* + A JavaScript implementation of the SHA family of hashes, as + defined in FIPS PUB 180-4 and FIPS PUB 202, as well as the corresponding + HMAC implementation as defined in FIPS PUB 198a + + Copyright Brian Turek 2008-2017 + Distributed under the BSD License + See http://caligatio.github.com/jsSHA/ for more information + + Several functions taken from Paul Johnston +*/ +'use strict';(function(Y){function C(c,a,b){var e=0,h=[],n=0,g,l,d,f,m,q,u,r,I=!1,v=[],w=[],t,y=!1,z=!1,x=-1;b=b||{};g=b.encoding||"UTF8";t=b.numRounds||1;if(t!==parseInt(t,10)||1>t)throw Error("numRounds must a integer >= 1");if("SHA-1"===c)m=512,q=K,u=Z,f=160,r=function(a){return a.slice()};else if(0===c.lastIndexOf("SHA-",0))if(q=function(a,b){return L(a,b,c)},u=function(a,b,h,e){var k,f;if("SHA-224"===c||"SHA-256"===c)k=(b+65>>>9<<4)+15,f=16;else if("SHA-384"===c||"SHA-512"===c)k=(b+129>>>10<< +5)+31,f=32;else throw Error("Unexpected error in SHA-2 implementation");for(;a.length<=k;)a.push(0);a[b>>>5]|=128<<24-b%32;b=b+h;a[k]=b&4294967295;a[k-1]=b/4294967296|0;h=a.length;for(b=0;be;e+=1)c[e]=a[e].slice();return c};x=1;if("SHA3-224"=== +c)m=1152,f=224;else if("SHA3-256"===c)m=1088,f=256;else if("SHA3-384"===c)m=832,f=384;else if("SHA3-512"===c)m=576,f=512;else if("SHAKE128"===c)m=1344,f=-1,F=31,z=!0;else if("SHAKE256"===c)m=1088,f=-1,F=31,z=!0;else throw Error("Chosen SHA variant is not supported");u=function(a,c,e,b,h){e=m;var k=F,f,g=[],n=e>>>5,l=0,d=c>>>5;for(f=0;f=e;f+=n)b=D(a.slice(f,f+n),b),c-=e;a=a.slice(f);for(c%=e;a.length>>3;a[f>>2]^=k<=h)break;g.push(a.a);l+=1;0===64*l%e&&D(null,b)}return g}}else throw Error("Chosen SHA variant is not supported");d=M(a,g,x);l=A(c);this.setHMACKey=function(a,b,h){var k;if(!0===I)throw Error("HMAC key already set");if(!0===y)throw Error("Cannot set HMAC key after calling update");if(!0===z)throw Error("SHAKE is not supported for HMAC");g=(h||{}).encoding||"UTF8";b=M(b,g,x)(a);a=b.binLen;b=b.value;k=m>>>3;h=k/4-1;if(ka/8){for(;b.length<=h;)b.push(0);b[h]&=4294967040}for(a=0;a<=h;a+=1)v[a]=b[a]^909522486,w[a]=b[a]^1549556828;l=q(v,l);e=m;I=!0};this.update=function(a){var c,b,k,f=0,g=m>>>5;c=d(a,h,n);a=c.binLen;b=c.value;c=a>>>5;for(k=0;k>>5);n=a%m;y=!0};this.getHash=function(a,b){var k,g,d,m;if(!0===I)throw Error("Cannot call getHash after setting HMAC key");d=N(b);if(!0===z){if(-1===d.shakeLen)throw Error("shakeLen must be specified in options"); +f=d.shakeLen}switch(a){case "HEX":k=function(a){return O(a,f,x,d)};break;case "B64":k=function(a){return P(a,f,x,d)};break;case "BYTES":k=function(a){return Q(a,f,x)};break;case "ARRAYBUFFER":try{g=new ArrayBuffer(0)}catch(p){throw Error("ARRAYBUFFER not supported by this environment");}k=function(a){return R(a,f,x)};break;default:throw Error("format must be HEX, B64, BYTES, or ARRAYBUFFER");}m=u(h.slice(),n,e,r(l),f);for(g=1;g>>24-f%32),m=u(m,f, +0,A(c),f);return k(m)};this.getHMAC=function(a,b){var k,g,d,p;if(!1===I)throw Error("Cannot call getHMAC without first setting HMAC key");d=N(b);switch(a){case "HEX":k=function(a){return O(a,f,x,d)};break;case "B64":k=function(a){return P(a,f,x,d)};break;case "BYTES":k=function(a){return Q(a,f,x)};break;case "ARRAYBUFFER":try{k=new ArrayBuffer(0)}catch(v){throw Error("ARRAYBUFFER not supported by this environment");}k=function(a){return R(a,f,x)};break;default:throw Error("outputFormat must be HEX, B64, BYTES, or ARRAYBUFFER"); +}g=u(h.slice(),n,e,r(l),f);p=q(w,A(c));p=u(g,f,m,p,f);return k(p)}}function b(c,a){this.a=c;this.b=a}function O(c,a,b,e){var h="";a/=8;var n,g,d;d=-1===b?3:0;for(n=0;n>>2]>>>8*(d+n%4*b),h+="0123456789abcdef".charAt(g>>>4&15)+"0123456789abcdef".charAt(g&15);return e.outputUpper?h.toUpperCase():h}function P(c,a,b,e){var h="",n=a/8,g,d,p,f;f=-1===b?3:0;for(g=0;g>>2]:0,p=g+2>>2]:0,p=(c[g>>>2]>>>8*(f+g%4*b)&255)<<16|(d>>>8*(f+(g+1)%4*b)&255)<<8|p>>>8*(f+ +(g+2)%4*b)&255,d=0;4>d;d+=1)8*g+6*d<=a?h+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(p>>>6*(3-d)&63):h+=e.b64Pad;return h}function Q(c,a,b){var e="";a/=8;var h,d,g;g=-1===b?3:0;for(h=0;h>>2]>>>8*(g+h%4*b)&255,e+=String.fromCharCode(d);return e}function R(c,a,b){a/=8;var e,h=new ArrayBuffer(a),d,g;g=new Uint8Array(h);d=-1===b?3:0;for(e=0;e>>2]>>>8*(d+e%4*b)&255;return h}function N(c){var a={outputUpper:!1,b64Pad:"=",shakeLen:-1};c=c||{}; +a.outputUpper=c.outputUpper||!1;!0===c.hasOwnProperty("b64Pad")&&(a.b64Pad=c.b64Pad);if(!0===c.hasOwnProperty("shakeLen")){if(0!==c.shakeLen%8)throw Error("shakeLen must be a multiple of 8");a.shakeLen=c.shakeLen}if("boolean"!==typeof a.outputUpper)throw Error("Invalid outputUpper formatting option");if("string"!==typeof a.b64Pad)throw Error("Invalid b64Pad formatting option");return a}function M(c,a,b){switch(a){case "UTF8":case "UTF16BE":case "UTF16LE":break;default:throw Error("encoding must be UTF8, UTF16BE, or UTF16LE"); +}switch(c){case "HEX":c=function(a,c,d){var g=a.length,l,p,f,m,q,u;if(0!==g%2)throw Error("String of HEX type must be in byte increments");c=c||[0];d=d||0;q=d>>>3;u=-1===b?3:0;for(l=0;l>>1)+q;for(f=m>>>2;c.length<=f;)c.push(0);c[f]|=p<<8*(u+m%4*b)}return{value:c,binLen:4*g+d}};break;case "TEXT":c=function(c,h,d){var g,l,p=0,f,m,q,u,r,t;h=h||[0];d=d||0;q=d>>>3;if("UTF8"===a)for(t=-1=== +b?3:0,f=0;fg?l.push(g):2048>g?(l.push(192|g>>>6),l.push(128|g&63)):55296>g||57344<=g?l.push(224|g>>>12,128|g>>>6&63,128|g&63):(f+=1,g=65536+((g&1023)<<10|c.charCodeAt(f)&1023),l.push(240|g>>>18,128|g>>>12&63,128|g>>>6&63,128|g&63)),m=0;m>>2;h.length<=u;)h.push(0);h[u]|=l[m]<<8*(t+r%4*b);p+=1}else if("UTF16BE"===a||"UTF16LE"===a)for(t=-1===b?2:0,l="UTF16LE"===a&&1!==b||"UTF16LE"!==a&&1===b,f=0;f>>8);r=p+q;for(u=r>>>2;h.length<=u;)h.push(0);h[u]|=g<<8*(t+r%4*b);p+=2}return{value:h,binLen:8*p+d}};break;case "B64":c=function(a,c,d){var g=0,l,p,f,m,q,u,r,t;if(-1===a.search(/^[a-zA-Z0-9=+\/]+$/))throw Error("Invalid character in base-64 string");p=a.indexOf("=");a=a.replace(/\=/g,"");if(-1!==p&&p= 9 + 'function' === typeof document.createEvent ? function CustomEvent(type, params) { + var e = document.createEvent('CustomEvent'); + if (params) { + e.initCustomEvent(type, params.bubbles, params.cancelable, params.detail); + } else { + e.initCustomEvent(type, false, false, void 0); + } + return e; + } : + + // IE <= 8 + function CustomEvent(type, params) { + var e = document.createEventObject(); + e.type = type; + if (params) { + e.bubbles = Boolean(params.bubbles); + e.cancelable = Boolean(params.cancelable); + e.detail = params.detail; + } else { + e.bubbles = false; + e.cancelable = false; + e.detail = void 0; + } + return e; + }; +}); + +var index$1 = interopDefault(index); + +var require$$1$2 = Object.freeze({ + default: index$1 +}); + +var eventmap = createCommonjsModule(function (module) { + 'use strict'; + + var eventmap = []; + var eventname = ''; + var ron = /^on/; + + for (eventname in commonjsGlobal) { + if (ron.test(eventname)) { + eventmap.push(eventname.slice(2)); + } + } + + module.exports = eventmap; +}); + +var eventmap$1 = interopDefault(eventmap); + +var require$$0$2 = Object.freeze({ + default: eventmap$1 +}); + +var crossvent = createCommonjsModule(function (module) { + 'use strict'; + + var customEvent = interopDefault(require$$1$2); + var eventmap = interopDefault(require$$0$2); + var doc = commonjsGlobal.document; + var addEvent = addEventEasy; + var removeEvent = removeEventEasy; + var hardCache = []; + + if (!commonjsGlobal.addEventListener) { + addEvent = addEventHard; + removeEvent = removeEventHard; + } + + module.exports = { + add: addEvent, + remove: removeEvent, + fabricate: fabricateEvent + }; + + function addEventEasy(el, type, fn, capturing) { + return el.addEventListener(type, fn, capturing); + } + + function addEventHard(el, type, fn) { + return el.attachEvent('on' + type, wrap(el, type, fn)); + } + + function removeEventEasy(el, type, fn, capturing) { + return el.removeEventListener(type, fn, capturing); + } + + function removeEventHard(el, type, fn) { + var listener = unwrap(el, type, fn); + if (listener) { + return el.detachEvent('on' + type, listener); + } + } + + function fabricateEvent(el, type, model) { + var e = eventmap.indexOf(type) === -1 ? makeCustomEvent() : makeClassicEvent(); + if (el.dispatchEvent) { + el.dispatchEvent(e); + } else { + el.fireEvent('on' + type, e); + } + function makeClassicEvent() { + var e; + if (doc.createEvent) { + e = doc.createEvent('Event'); + e.initEvent(type, true, true); + } else if (doc.createEventObject) { + e = doc.createEventObject(); + } + return e; + } + function makeCustomEvent() { + return new customEvent(type, { detail: model }); + } + } + + function wrapperFactory(el, type, fn) { + return function wrapper(originalEvent) { + var e = originalEvent || commonjsGlobal.event; + e.target = e.target || e.srcElement; + e.preventDefault = e.preventDefault || function preventDefault() { + e.returnValue = false; + }; + e.stopPropagation = e.stopPropagation || function stopPropagation() { + e.cancelBubble = true; + }; + e.which = e.which || e.keyCode; + fn.call(el, e); + }; + } + + function wrap(el, type, fn) { + var wrapper = unwrap(el, type, fn) || wrapperFactory(el, type, fn); + hardCache.push({ + wrapper: wrapper, + element: el, + type: type, + fn: fn + }); + return wrapper; + } + + function unwrap(el, type, fn) { + var i = find(el, type, fn); + if (i) { + var wrapper = hardCache[i].wrapper; + hardCache.splice(i, 1); // free up a tad of memory + return wrapper; + } + } + + function find(el, type, fn) { + var i, item; + for (i = 0; i < hardCache.length; i++) { + item = hardCache[i]; + if (item.element === el && item.type === type && item.fn === fn) { + return i; + } + } + } +}); + +var crossvent$1 = interopDefault(crossvent); +var add = crossvent.add; +var remove = crossvent.remove; +var fabricate = crossvent.fabricate; + +var require$$1$1 = Object.freeze({ + default: crossvent$1, + add: add, + remove: remove, + fabricate: fabricate +}); + +var classes = createCommonjsModule(function (module) { + 'use strict'; + + var cache = {}; + var start = '(?:^|\\s)'; + var end = '(?:\\s|$)'; + + function lookupClass(className) { + var cached = cache[className]; + if (cached) { + cached.lastIndex = 0; + } else { + cache[className] = cached = new RegExp(start + className + end, 'g'); + } + return cached; + } + + function addClass(el, className) { + var current = el.className; + if (!current.length) { + el.className = className; + } else if (!lookupClass(className).test(current)) { + el.className += ' ' + className; + } + } + + function rmClass(el, className) { + el.className = el.className.replace(lookupClass(className), ' ').trim(); + } + + module.exports = { + add: addClass, + rm: rmClass + }; +}); + +var classes$1 = interopDefault(classes); +var add$1 = classes.add; +var rm = classes.rm; + +var require$$0$3 = Object.freeze({ + default: classes$1, + add: add$1, + rm: rm +}); + +var dragula = createCommonjsModule(function (module) { + 'use strict'; + + var emitter = interopDefault(require$$2); + var crossvent = interopDefault(require$$1$1); + var classes = interopDefault(require$$0$3); + var doc = document; + var documentElement = doc.documentElement; + + function dragula(initialContainers, options) { + var len = arguments.length; + if (len === 1 && Array.isArray(initialContainers) === false) { + options = initialContainers; + initialContainers = []; + } + var _mirror; // mirror image + var _source; // source container + var _item; // item being dragged + var _offsetX; // reference x + var _offsetY; // reference y + var _moveX; // reference move x + var _moveY; // reference move y + var _initialSibling; // reference sibling when grabbed + var _currentSibling; // reference sibling now + var _copy; // item used for copying + var _renderTimer; // timer for setTimeout renderMirrorImage + var _lastDropTarget = null; // last container item was over + var _grabbed; // holds mousedown context until first mousemove + + var o = options || {}; + if (o.moves === void 0) { + o.moves = always; + } + if (o.accepts === void 0) { + o.accepts = always; + } + if (o.invalid === void 0) { + o.invalid = invalidTarget; + } + if (o.containers === void 0) { + o.containers = initialContainers || []; + } + if (o.isContainer === void 0) { + o.isContainer = never; + } + if (o.copy === void 0) { + o.copy = false; + } + if (o.copySortSource === void 0) { + o.copySortSource = false; + } + if (o.revertOnSpill === void 0) { + o.revertOnSpill = false; + } + if (o.removeOnSpill === void 0) { + o.removeOnSpill = false; + } + if (o.direction === void 0) { + o.direction = 'vertical'; + } + if (o.ignoreInputTextSelection === void 0) { + o.ignoreInputTextSelection = true; + } + if (o.mirrorContainer === void 0) { + o.mirrorContainer = doc.body; + } + + var drake = emitter({ + containers: o.containers, + start: manualStart, + end: end, + cancel: cancel, + remove: remove, + destroy: destroy, + canMove: canMove, + dragging: false + }); + + if (o.removeOnSpill === true) { + drake.on('over', spillOver).on('out', spillOut); + } + + events(); + + return drake; + + function isContainer(el) { + return drake.containers.indexOf(el) !== -1 || o.isContainer(el); + } + + function events(remove) { + var op = remove ? 'remove' : 'add'; + touchy(documentElement, op, 'mousedown', grab); + touchy(documentElement, op, 'mouseup', release); + } + + function eventualMovements(remove) { + var op = remove ? 'remove' : 'add'; + touchy(documentElement, op, 'mousemove', startBecauseMouseMoved); + } + + function movements(remove) { + var op = remove ? 'remove' : 'add'; + crossvent[op](documentElement, 'selectstart', preventGrabbed); // IE8 + crossvent[op](documentElement, 'click', preventGrabbed); + } + + function destroy() { + events(true); + release({}); + } + + function preventGrabbed(e) { + if (_grabbed) { + e.preventDefault(); + } + } + + function grab(e) { + _moveX = e.clientX; + _moveY = e.clientY; + + var ignore = whichMouseButton(e) !== 1 || e.metaKey || e.ctrlKey; + if (ignore) { + return; // we only care about honest-to-god left clicks and touch events + } + var item = e.target; + var context = canStart(item); + if (!context) { + return; + } + _grabbed = context; + eventualMovements(); + if (e.type === 'mousedown') { + if (isInput(item)) { + // see also: https://github.com/bevacqua/dragula/issues/208 + item.focus(); // fixes https://github.com/bevacqua/dragula/issues/176 + } else { + e.preventDefault(); // fixes https://github.com/bevacqua/dragula/issues/155 + } + } + } + + function startBecauseMouseMoved(e) { + if (!_grabbed) { + return; + } + if (whichMouseButton(e) === 0) { + release({}); + return; // when text is selected on an input and then dragged, mouseup doesn't fire. this is our only hope + } + // truthy check fixes #239, equality fixes #207 + if (e.clientX !== void 0 && e.clientX === _moveX && e.clientY !== void 0 && e.clientY === _moveY) { + return; + } + if (o.ignoreInputTextSelection) { + var clientX = getCoord('clientX', e); + var clientY = getCoord('clientY', e); + var elementBehindCursor = doc.elementFromPoint(clientX, clientY); + if (isInput(elementBehindCursor)) { + return; + } + } + + var grabbed = _grabbed; // call to end() unsets _grabbed + eventualMovements(true); + movements(); + end(); + start(grabbed); + + var offset = getOffset(_item); + _offsetX = getCoord('pageX', e) - offset.left; + _offsetY = getCoord('pageY', e) - offset.top; + + classes.add(_copy || _item, 'gu-transit'); + renderMirrorImage(); + drag(e); + } + + function canStart(item) { + if (drake.dragging && _mirror) { + return; + } + if (isContainer(item)) { + return; // don't drag container itself + } + var handle = item; + while (getParent(item) && isContainer(getParent(item)) === false) { + if (o.invalid(item, handle)) { + return; + } + item = getParent(item); // drag target should be a top element + if (!item) { + return; + } + } + var source = getParent(item); + if (!source) { + return; + } + if (o.invalid(item, handle)) { + return; + } + + var movable = o.moves(item, source, handle, nextEl(item)); + if (!movable) { + return; + } + + return { + item: item, + source: source + }; + } + + function canMove(item) { + return !!canStart(item); + } + + function manualStart(item) { + var context = canStart(item); + if (context) { + start(context); + } + } + + function start(context) { + if (isCopy(context.item, context.source)) { + _copy = context.item.cloneNode(true); + drake.emit('cloned', _copy, context.item, 'copy'); + } + + _source = context.source; + _item = context.item; + _initialSibling = _currentSibling = nextEl(context.item); + + drake.dragging = true; + drake.emit('drag', _item, _source); + } + + function invalidTarget() { + return false; + } + + function end() { + if (!drake.dragging) { + return; + } + var item = _copy || _item; + drop(item, getParent(item)); + } + + function ungrab() { + _grabbed = false; + eventualMovements(true); + movements(true); + } + + function release(e) { + ungrab(); + + if (!drake.dragging) { + return; + } + var item = _copy || _item; + var clientX = getCoord('clientX', e); + var clientY = getCoord('clientY', e); + var elementBehindCursor = getElementBehindPoint(_mirror, clientX, clientY); + var dropTarget = findDropTarget(elementBehindCursor, clientX, clientY); + if (dropTarget && (_copy && o.copySortSource || !_copy || dropTarget !== _source)) { + drop(item, dropTarget); + } else if (o.removeOnSpill) { + remove(); + } else { + cancel(); + } + } + + function drop(item, target) { + var parent = getParent(item); + if (_copy && o.copySortSource && target === _source) { + parent.removeChild(_item); + } + if (isInitialPlacement(target)) { + drake.emit('cancel', item, _source, _source); + } else { + drake.emit('drop', item, target, _source, _currentSibling); + } + cleanup(); + } + + function remove() { + if (!drake.dragging) { + return; + } + var item = _copy || _item; + var parent = getParent(item); + if (parent) { + parent.removeChild(item); + } + drake.emit(_copy ? 'cancel' : 'remove', item, parent, _source); + cleanup(); + } + + function cancel(revert) { + if (!drake.dragging) { + return; + } + var reverts = arguments.length > 0 ? revert : o.revertOnSpill; + var item = _copy || _item; + var parent = getParent(item); + var initial = isInitialPlacement(parent); + if (initial === false && reverts) { + if (_copy) { + if (parent) { + parent.removeChild(_copy); + } + } else { + _source.insertBefore(item, _initialSibling); + } + } + if (initial || reverts) { + drake.emit('cancel', item, _source, _source); + } else { + drake.emit('drop', item, parent, _source, _currentSibling); + } + cleanup(); + } + + function cleanup() { + var item = _copy || _item; + ungrab(); + removeMirrorImage(); + if (item) { + classes.rm(item, 'gu-transit'); + } + if (_renderTimer) { + clearTimeout(_renderTimer); + } + drake.dragging = false; + if (_lastDropTarget) { + drake.emit('out', item, _lastDropTarget, _source); + } + drake.emit('dragend', item); + _source = _item = _copy = _initialSibling = _currentSibling = _renderTimer = _lastDropTarget = null; + } + + function isInitialPlacement(target, s) { + var sibling; + if (s !== void 0) { + sibling = s; + } else if (_mirror) { + sibling = _currentSibling; + } else { + sibling = nextEl(_copy || _item); + } + return target === _source && sibling === _initialSibling; + } + + function findDropTarget(elementBehindCursor, clientX, clientY) { + var target = elementBehindCursor; + while (target && !accepted()) { + target = getParent(target); + } + return target; + + function accepted() { + var droppable = isContainer(target); + if (droppable === false) { + return false; + } + + var immediate = getImmediateChild(target, elementBehindCursor); + var reference = getReference(target, immediate, clientX, clientY); + var initial = isInitialPlacement(target, reference); + if (initial) { + return true; // should always be able to drop it right back where it was + } + return o.accepts(_item, target, _source, reference); + } + } + + function drag(e) { + if (!_mirror) { + return; + } + e.preventDefault(); + + var clientX = getCoord('clientX', e); + var clientY = getCoord('clientY', e); + var x = clientX - _offsetX; + var y = clientY - _offsetY; + + _mirror.style.left = x + 'px'; + _mirror.style.top = y + 'px'; + + var item = _copy || _item; + var elementBehindCursor = getElementBehindPoint(_mirror, clientX, clientY); + var dropTarget = findDropTarget(elementBehindCursor, clientX, clientY); + var changed = dropTarget !== null && dropTarget !== _lastDropTarget; + if (changed || dropTarget === null) { + out(); + _lastDropTarget = dropTarget; + over(); + } + var parent = getParent(item); + if (dropTarget === _source && _copy && !o.copySortSource) { + if (parent) { + parent.removeChild(item); + } + return; + } + var reference; + var immediate = getImmediateChild(dropTarget, elementBehindCursor); + if (immediate !== null) { + reference = getReference(dropTarget, immediate, clientX, clientY); + } else if (o.revertOnSpill === true && !_copy) { + reference = _initialSibling; + dropTarget = _source; + } else { + if (_copy && parent) { + parent.removeChild(item); + } + return; + } + if (reference === null && changed || reference !== item && reference !== nextEl(item)) { + _currentSibling = reference; + dropTarget.insertBefore(item, reference); + drake.emit('shadow', item, dropTarget, _source); + } + function moved(type) { + drake.emit(type, item, _lastDropTarget, _source); + } + function over() { + if (changed) { + moved('over'); + } + } + function out() { + if (_lastDropTarget) { + moved('out'); + } + } + } + + function spillOver(el) { + classes.rm(el, 'gu-hide'); + } + + function spillOut(el) { + if (drake.dragging) { + classes.add(el, 'gu-hide'); + } + } + + function renderMirrorImage() { + if (_mirror) { + return; + } + var rect = _item.getBoundingClientRect(); + _mirror = _item.cloneNode(true); + _mirror.style.width = getRectWidth(rect) + 'px'; + _mirror.style.height = getRectHeight(rect) + 'px'; + classes.rm(_mirror, 'gu-transit'); + classes.add(_mirror, 'gu-mirror'); + o.mirrorContainer.appendChild(_mirror); + touchy(documentElement, 'add', 'mousemove', drag); + classes.add(o.mirrorContainer, 'gu-unselectable'); + drake.emit('cloned', _mirror, _item, 'mirror'); + } + + function removeMirrorImage() { + if (_mirror) { + classes.rm(o.mirrorContainer, 'gu-unselectable'); + touchy(documentElement, 'remove', 'mousemove', drag); + getParent(_mirror).removeChild(_mirror); + _mirror = null; + } + } + + function getImmediateChild(dropTarget, target) { + var immediate = target; + while (immediate !== dropTarget && getParent(immediate) !== dropTarget) { + immediate = getParent(immediate); + } + if (immediate === documentElement) { + return null; + } + return immediate; + } + + function getReference(dropTarget, target, x, y) { + var horizontal = o.direction === 'horizontal'; + var reference = target !== dropTarget ? inside() : outside(); + return reference; + + function outside() { + // slower, but able to figure out any position + var len = dropTarget.children.length; + var i; + var el; + var rect; + for (i = 0; i < len; i++) { + el = dropTarget.children[i]; + rect = el.getBoundingClientRect(); + if (horizontal && rect.left + rect.width / 2 > x) { + return el; + } + if (!horizontal && rect.top + rect.height / 2 > y) { + return el; + } + } + return null; + } + + function inside() { + // faster, but only available if dropped inside a child element + var rect = target.getBoundingClientRect(); + if (horizontal) { + return resolve(x > rect.left + getRectWidth(rect) / 2); + } + return resolve(y > rect.top + getRectHeight(rect) / 2); + } + + function resolve(after) { + return after ? nextEl(target) : target; + } + } + + function isCopy(item, container) { + return typeof o.copy === 'boolean' ? o.copy : o.copy(item, container); + } + } + + function touchy(el, op, type, fn) { + var touch = { + mouseup: 'touchend', + mousedown: 'touchstart', + mousemove: 'touchmove' + }; + var pointers = { + mouseup: 'pointerup', + mousedown: 'pointerdown', + mousemove: 'pointermove' + }; + var microsoft = { + mouseup: 'MSPointerUp', + mousedown: 'MSPointerDown', + mousemove: 'MSPointerMove' + }; + if (commonjsGlobal.navigator.pointerEnabled) { + crossvent[op](el, pointers[type], fn); + } else if (commonjsGlobal.navigator.msPointerEnabled) { + crossvent[op](el, microsoft[type], fn); + } else { + crossvent[op](el, touch[type], fn); + crossvent[op](el, type, fn); + } + } + + function whichMouseButton(e) { + if (e.touches !== void 0) { + return e.touches.length; + } + if (e.which !== void 0 && e.which !== 0) { + return e.which; + } // see https://github.com/bevacqua/dragula/issues/261 + if (e.buttons !== void 0) { + return e.buttons; + } + var button = e.button; + if (button !== void 0) { + // see https://github.com/jquery/jquery/blob/99e8ff1baa7ae341e94bb89c3e84570c7c3ad9ea/src/event.js#L573-L575 + return button & 1 ? 1 : button & 2 ? 3 : button & 4 ? 2 : 0; + } + } + + function getOffset(el) { + var rect = el.getBoundingClientRect(); + return { + left: rect.left + getScroll('scrollLeft', 'pageXOffset'), + top: rect.top + getScroll('scrollTop', 'pageYOffset') + }; + } + + function getScroll(scrollProp, offsetProp) { + if (typeof commonjsGlobal[offsetProp] !== 'undefined') { + return commonjsGlobal[offsetProp]; + } + if (documentElement.clientHeight) { + return documentElement[scrollProp]; + } + return doc.body[scrollProp]; + } + + function getElementBehindPoint(point, x, y) { + var p = point || {}; + var state = p.className; + var el; + p.className += ' gu-hide'; + el = doc.elementFromPoint(x, y); + p.className = state; + return el; + } + + function never() { + return false; + } + function always() { + return true; + } + function getRectWidth(rect) { + return rect.width || rect.right - rect.left; + } + function getRectHeight(rect) { + return rect.height || rect.bottom - rect.top; + } + function getParent(el) { + return el.parentNode === doc ? null : el.parentNode; + } + function isInput(el) { + return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || isEditable(el); + } + function isEditable(el) { + if (!el) { + return false; + } // no parents were editable + if (el.contentEditable === 'false') { + return false; + } // stop the lookup + if (el.contentEditable === 'true') { + return true; + } // found a contentEditable element in the chain + return isEditable(getParent(el)); // contentEditable is set to 'inherit' + } + + function nextEl(el) { + return el.nextElementSibling || manually(); + function manually() { + var sibling = el; + do { + sibling = sibling.nextSibling; + } while (sibling && sibling.nodeType !== 1); + return sibling; + } + } + + function getEventHost(e) { + // on touchend event, we have to use `e.changedTouches` + // see http://stackoverflow.com/questions/7192563/touchend-event-properties + // see https://github.com/bevacqua/dragula/issues/34 + if (e.targetTouches && e.targetTouches.length) { + return e.targetTouches[0]; + } + if (e.changedTouches && e.changedTouches.length) { + return e.changedTouches[0]; + } + return e; + } + + function getCoord(coord, e) { + var host = getEventHost(e); + var missMap = { + pageX: 'clientX', // IE8 + pageY: 'clientY' // IE8 + }; + if (coord in missMap && !(coord in host) && missMap[coord] in host) { + coord = missMap[coord]; + } + return host[coord]; + } + + module.exports = dragula; +}); + +var dragula$1 = interopDefault(dragula); + +if (!dragula$1) { + throw new Error('[vue-dragula] cannot locate dragula.'); +} + +var raf = window.requestAnimationFrame; +var waitForTransition = raf ? function (fn) { + raf(function () { + raf(fn); + }); +} : function (fn) { + window.setTimeout(fn, 50); +}; + +var DragulaService = function () { + function DragulaService(Vue) { + babelHelpers.classCallCheck(this, DragulaService); + + this.bags = []; // bag store + this.eventBus = new Vue(); + this.events = ['cancel', 'cloned', 'drag', 'dragend', 'drop', 'out', 'over', 'remove', 'shadow', 'dropModel', 'removeModel']; + } + + babelHelpers.createClass(DragulaService, [{ + key: 'add', + value: function add(name, drake) { + var bag = this.find(name); + if (bag) { + throw new Error('Bag named: "' + name + '" already exists.'); + } + bag = { + name: name, + drake: drake + }; + this.bags.push(bag); + if (drake.models) { + this.handleModels(name, drake); + } + if (!bag.initEvents) { + this.setupEvents(bag); + } + return bag; + } + }, { + key: 'find', + value: function find(name) { + var bags = this.bags; + for (var i = 0; i < bags.length; i++) { + if (bags[i].name === name) { + return bags[i]; + } + } + } + }, { + key: 'handleModels', + value: function handleModels(name, drake) { + var _this2 = this; + + if (drake.registered) { + // do not register events twice + return; + } + var dragElm = void 0; + var dragIndex = void 0; + var dropIndex = void 0; + var sourceModel = void 0; + drake.on('remove', function (el, container, source) { + if (!drake.models) { + return; + } + sourceModel = _this2.findModelForContainer(source, drake); + sourceModel.splice(dragIndex, 1); + drake.cancel(true); + _this2.eventBus.$emit('removeModel', [name, el, source, dragIndex]); + }); + drake.on('drag', function (el, source) { + dragElm = el; + dragIndex = _this2.domIndexOf(el, source); + }); + drake.on('drop', function (dropElm, target, source) { + if (!drake.models || !target) { + return; + } + dropIndex = _this2.domIndexOf(dropElm, target); + sourceModel = _this2.findModelForContainer(source, drake); + + if (target === source) { + sourceModel.splice(dropIndex, 0, sourceModel.splice(dragIndex, 1)[0]); + } else { + var notCopy = dragElm === dropElm; + var targetModel = _this2.findModelForContainer(target, drake); + var dropElmModel = notCopy ? sourceModel[dragIndex] : JSON.parse(JSON.stringify(sourceModel[dragIndex])); + + if (notCopy) { + waitForTransition(function () { + sourceModel.splice(dragIndex, 1); + }); + } + targetModel.splice(dropIndex, 0, dropElmModel); + drake.cancel(true); + } + _this2.eventBus.$emit('dropModel', [name, dropElm, target, source, dropIndex]); + }); + drake.registered = true; + } + }, { + key: 'destroy', + value: function destroy(name) { + var bag = this.find(name); + if (!bag) { + return; + } + var bagIndex = this.bags.indexOf(bag); + this.bags.splice(bagIndex, 1); + bag.drake.destroy(); + } + }, { + key: 'setOptions', + value: function setOptions(name, options) { + var bag = this.add(name, dragula$1(options)); + this.handleModels(name, bag.drake); + } + }, { + key: 'setupEvents', + value: function setupEvents(bag) { + bag.initEvents = true; + var _this = this; + var emitter = function emitter(type) { + function replicate() { + var args = Array.prototype.slice.call(arguments); + _this.eventBus.$emit(type, [bag.name].concat(args)); + } + bag.drake.on(type, replicate); + }; + this.events.forEach(emitter); + } + }, { + key: 'domIndexOf', + value: function domIndexOf(child, parent) { + return Array.prototype.indexOf.call(parent.children, child); + } + }, { + key: 'findModelForContainer', + value: function findModelForContainer(container, drake) { + return (this.findModelContainerByContainer(container, drake) || {}).model; + } + }, { + key: 'findModelContainerByContainer', + value: function findModelContainerByContainer(container, drake) { + if (!drake.models) { + return; + } + return drake.models.find(function (model) { + return model.container === container; + }); + } + }]); + return DragulaService; +}(); + +if (!dragula$1) { + throw new Error('[vue-dragula] cannot locate dragula.'); +} + +function VueDragula (Vue) { + var service = new DragulaService(Vue); + + var name = 'globalBag'; + var drake = void 0; + + Vue.vueDragula = { + options: service.setOptions.bind(service), + find: service.find.bind(service), + eventBus: service.eventBus + }; + + Vue.directive('dragula', { + params: ['bag'], + + bind: function bind(container, binding, vnode) { + var bagName = vnode ? vnode.data.attrs.bag // Vue 2 + : this.params.bag; // Vue 1 + if (!vnode) { + container = this.el; // Vue 1 + } + if (bagName !== undefined && bagName.length !== 0) { + name = bagName; + } + var bag = service.find(name); + if (bag) { + drake = bag.drake; + drake.containers.push(container); + return; + } + drake = dragula$1({ + containers: [container] + }); + service.add(name, drake); + + service.handleModels(name, drake); + }, + update: function update(container, binding, vnode, oldVnode) { + var newValue = vnode ? binding.value // Vue 2 + : container; // Vue 1 + if (!newValue) { + return; + } + + var bagName = vnode ? vnode.data.attrs.bag // Vue 2 + : this.params.bag; // Vue 1 + if (bagName !== undefined && bagName.length !== 0) { + name = bagName; + } + var bag = service.find(name); + drake = bag.drake; + if (!drake.models) { + drake.models = []; + } + + if (!vnode) { + container = this.el; // Vue 1 + } + var modelContainer = service.findModelContainerByContainer(container, drake); + + if (modelContainer) { + modelContainer.model = newValue; + } else { + drake.models.push({ + model: newValue, + container: container + }); + } + }, + unbind: function unbind(container, binding, vnode) { + var unbindBagName = 'globalBag'; + var bagName = vnode ? vnode.data.attrs.bag // Vue 2 + : this.params.bag; // Vue 1 + if (!vnode) { + container = this.el; // Vue 1 + } + if (bagName !== undefined && bagName.length !== 0) { + unbindBagName = bagName; + } + var drake = service.find(unbindBagName).drake; + if (!drake) { + return; + } + var containerIndex = drake.containers.indexOf(container); + if (containerIndex > -1) { + drake.containers.splice(containerIndex, 1); + } + if (drake.containers.length === 0) { + service.destroy(unbindBagName); + } + } + }); +} + +function plugin(Vue) { + var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + if (plugin.installed) { + console.warn('[vue-dragula] already installed.'); + } + + VueDragula(Vue); +} + +plugin.version = '1.0.0'; + +if (typeof define === 'function' && define.amd) { + // eslint-disable-line + define([], function () { + plugin; + }); // eslint-disable-line +} else if (window.Vue) { + window.Vue.use(plugin); + } + +return plugin; + +}))); \ No newline at end of file diff --git a/js/vue.min.js b/js/vue.min.js new file mode 100644 index 000000000..fccc40b0f --- /dev/null +++ b/js/vue.min.js @@ -0,0 +1,11 @@ +/*! + * Vue.js v1.0.28-csp + * (c) 2016 Evan You + * Released under the MIT License. + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.Vue=t()}(this,function(){"use strict";function e(t,r,i){if(n(t,r))return void(t[r]=i);if(t._isVue)return void e(t._data,r,i);var a=t.__ob__;if(!a)return void(t[r]=i);if(a.convert(r,i),a.dep.notify(),a.vms)for(var o=a.vms.length;o--;){var s=a.vms[o];s._proxy(r),s._digest()}return i}function t(e,t){if(n(e,t)){delete e[t];var r=e.__ob__;if(!r)return void(e._isVue&&(delete e._data[t],e._digest()));if(r.dep.notify(),r.vms)for(var i=r.vms.length;i--;){var a=r.vms[i];a._unproxy(t),a._digest()}}}function n(e,t){return Mn.call(e,t)}function r(e){return Vn.test(e)}function i(e){var t=(e+"").charCodeAt(0);return 36===t||95===t}function a(e){return null==e?"":e.toString()}function o(e){if("string"!=typeof e)return e;var t=Number(e);return isNaN(t)?e:t}function s(e){return"true"===e||"false"!==e&&e}function l(e){var t=e.charCodeAt(0),n=e.charCodeAt(e.length-1);return t!==n||34!==t&&39!==t?e:e.slice(1,-1)}function u(e){return e.replace(Hn,c)}function c(e,t){return t?t.toUpperCase():""}function p(e){return e.replace(Wn,"$1-$2").replace(Wn,"$1-$2").toLowerCase()}function h(e){return e.replace(zn,c)}function f(e,t){return function(n){var r=arguments.length;return r?r>1?e.apply(t,arguments):e.call(t,n):e.call(t)}}function d(e,t){t=t||0;for(var n=e.length-t,r=new Array(n);n--;)r[n]=e[n+t];return r}function v(e,t){for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}function m(e){return null!==e&&"object"==typeof e}function g(e){return qn.call(e)===Gn}function y(e,t,n,r){Object.defineProperty(e,t,{value:n,enumerable:!!r,writable:!0,configurable:!0})}function b(e,t){var n,r,i,a,o,s=function s(){var l=Date.now()-a;l=0?n=setTimeout(s,t-l):(n=null,o=e.apply(i,r),n||(i=r=null))};return function(){return i=this,r=arguments,a=Date.now(),n||(n=setTimeout(s,t)),o}}function _(e,t){for(var n=e.length;n--;)if(e[n]===t)return n;return-1}function x(e){var t=function t(){if(!t.cancelled)return e.apply(this,arguments)};return t.cancel=function(){t.cancelled=!0},t}function w(e,t){return e==t||!(!m(e)||!m(t))&&JSON.stringify(e)===JSON.stringify(t)}function k(e){return/native code/.test(e.toString())}function S(e){this.size=0,this.limit=e,this.head=this.tail=void 0,this._keymap=Object.create(null)}function C(){return hr.charCodeAt(vr+1)}function E(){return hr.charCodeAt(++vr)}function $(){return vr>=dr}function O(){for(;C()===Or;)E()}function A(e){return e===Sr||e===Cr}function N(e){return Ar[e]}function L(e,t){return Nr[e]===t}function P(){for(var e,t=E();!$();)if(e=E(),e===$r)E();else if(e===t)break}function I(e){for(var t=0,n=e;!$();)if(e=C(),A(e))P();else if(n===e&&t++,L(n,e)&&t--,E(),0===t)break}function j(){for(var e=vr;!$();)if(mr=C(),A(mr))P();else if(N(mr))I(mr);else if(mr===Er){if(E(),mr=C(),mr!==Er){gr!==_r&&gr!==kr||(gr=xr);break}E()}else{if(mr===Or&&(gr===wr||gr===kr)){O();break}gr===xr&&(gr=wr),E()}return hr.slice(e+1,vr)||null}function T(){for(var e=[];!$();)e.push(F());return e}function F(){var e,t={};return gr=xr,t.name=j().trim(),gr=kr,e=D(),e.length&&(t.args=e),t}function D(){for(var e=[];!$()&&gr!==xr;){var t=j();if(!t)break;e.push(R(t))}return e}function R(e){if(br.test(e))return{value:o(e),dynamic:!1};var t=l(e),n=t===e;return{value:n?e:t,dynamic:n}}function B(e){var t=yr.get(e);if(t)return t;hr=e,fr={},dr=hr.length,vr=-1,mr="",gr=_r;var n;return hr.indexOf("|")<0?fr.expression=hr.trim():(fr.expression=j().trim(),n=T(),n.length&&(fr.filters=n)),yr.put(e,fr),fr}function U(e){return e.replace(Pr,"\\$&")}function M(){var e=U(Ur.delimiters[0]),t=U(Ur.delimiters[1]),n=U(Ur.unsafeDelimiters[0]),r=U(Ur.unsafeDelimiters[1]);jr=new RegExp(n+"((?:.|\\n)+?)"+r+"|"+e+"((?:.|\\n)+?)"+t,"g"),Tr=new RegExp("^"+n+"((?:.|\\n)+?)"+r+"$"),Ir=new S(1e3)}function V(e){Ir||M();var t=Ir.get(e);if(t)return t;if(!jr.test(e))return null;for(var n,r,i,a,o,s,l=[],u=jr.lastIndex=0;n=jr.exec(e);)r=n.index,r>u&&l.push({value:e.slice(u,r)}),i=Tr.test(n[0]),a=i?n[1]:n[2],o=a.charCodeAt(0),s=42===o,a=s?a.slice(1):a,l.push({tag:!0,value:a.trim(),html:i,oneTime:s}),u=r+n[0].length;return u1?e.map(function(e){return W(e,t)}).join("+"):W(e[0],t,!0)}function W(e,t,n){return e.tag?e.oneTime&&t?'"'+t.$eval(e.value)+'"':z(e.value,n):'"'+e.value+'"'}function z(e,t){if(Fr.test(e)){var n=B(e);return n.filters?"this._applyFilters("+n.expression+",null,"+JSON.stringify(n.filters)+",false)":"("+e+")"}return t?e:"("+e+")"}function q(e,t,n,r){K(e,1,function(){t.appendChild(e)},n,r)}function G(e,t,n,r){K(e,1,function(){te(e,t)},n,r)}function J(e,t,n){K(e,-1,function(){re(e)},t,n)}function K(e,t,n,r,i){var a=e.__v_trans;if(!a||!a.hooks&&!ir||!r._isCompiled||r.$parent&&!r.$parent._isCompiled)return n(),void(i&&i());var o=t>0?"enter":"leave";a[o](n,i)}function Q(e){if("string"==typeof e){e=document.querySelector(e)}return e}function X(e){if(!e)return!1;var t=e.ownerDocument.documentElement,n=e.parentNode;return t===e||t===n||!(!n||1!==n.nodeType||!t.contains(n))}function Z(e,t){var n=e.getAttribute(t);return null!==n&&e.removeAttribute(t),n}function Y(e,t){var n=Z(e,":"+t);return null===n&&(n=Z(e,"v-bind:"+t)),n}function ee(e,t){return e.hasAttribute(t)||e.hasAttribute(":"+t)||e.hasAttribute("v-bind:"+t)}function te(e,t){t.parentNode.insertBefore(e,t)}function ne(e,t){t.nextSibling?te(e,t.nextSibling):t.parentNode.appendChild(e)}function re(e){e.parentNode.removeChild(e)}function ie(e,t){t.firstChild?te(e,t.firstChild):t.appendChild(e)}function ae(e,t){var n=e.parentNode;n&&n.replaceChild(t,e)}function oe(e,t,n,r){e.addEventListener(t,n,r)}function se(e,t,n){e.removeEventListener(t,n)}function le(e){var t=e.className;return"object"==typeof t&&(t=t.baseVal||""),t}function ue(e,t){er&&!/svg$/.test(e.namespaceURI)?e.className=t:e.setAttribute("class",t)}function ce(e,t){if(e.classList)e.classList.add(t);else{var n=" "+le(e)+" ";n.indexOf(" "+t+" ")<0&&ue(e,(n+t).trim())}}function pe(e,t){if(e.classList)e.classList.remove(t);else{for(var n=" "+le(e)+" ",r=" "+t+" ";n.indexOf(r)>=0;)n=n.replace(r," ");ue(e,n.trim())}e.className||e.removeAttribute("class")}function he(e,t){var n,r;if(ve(e)&&_e(e.content)&&(e=e.content),e.hasChildNodes())for(fe(e),r=t?document.createDocumentFragment():document.createElement("div");n=e.firstChild;)r.appendChild(n);return r}function fe(e){for(var t;t=e.firstChild,de(t);)e.removeChild(t);for(;t=e.lastChild,de(t);)e.removeChild(t)}function de(e){return e&&(3===e.nodeType&&!e.data.trim()||8===e.nodeType)}function ve(e){return e.tagName&&"template"===e.tagName.toLowerCase()}function me(e,t){var n=Ur.debug?document.createComment(e):document.createTextNode(t?" ":"");return n.__v_anchor=!0,n}function ge(e){if(e.hasAttributes())for(var t=e.attributes,n=0,r=t.length;n=l.length){for(var e=0;e=97&&t<=122||t>=65&&t<=90?"ident":t>=49&&t<=57?"number":"else"}function Ue(e){var t=e.trim();return("0"!==e.charAt(0)||!isNaN(e))&&(r(t)?l(t):"*"+t)}function Me(e){function t(){var t=e[c+1];if(p===yi&&"'"===t||p===bi&&'"'===t)return c++,r="\\"+t,f[ui](),!0}var n,r,i,a,o,s,l,u=[],c=-1,p=fi,h=0,f=[];for(f[ci]=function(){void 0!==i&&(u.push(i),i=void 0)},f[ui]=function(){void 0===i?i=r:i+=r},f[pi]=function(){f[ui](),h++},f[hi]=function(){if(h>0)h--,p=gi,f[ui]();else{if(h=0,i=Ue(i),i===!1)return!1;f[ci]()}};null!=p;)if(c++,n=e[c],"\\"!==n||!t()){if(a=Be(n),l=wi[p],o=l[a]||l.else||xi,o===xi)return;if(p=o[0],s=f[o[1]],s&&(r=o[2],r=void 0===r?n:r,s()===!1))return;if(p===_i)return u.raw=e,u}}function Ve(e){var t=li.get(e);return t||(t=Me(e),t&&li.put(e,t)),t}function He(e,t){return Ze(t).get(e)}function We(t,n,r){var i=t;if("string"==typeof n&&(n=Me(n)),!n||!m(t))return!1;for(var a,o,s=0,l=n.length;s-1?n.replace(Pi,Je):n,t+"scope."+n)}function Je(e,t){return Fi[t]}function Ke(e){Oi.test(e),Fi.length=0;var t=e.replace(Li,qe).replace(Ai,"");return t=(" "+t).replace(ji,Ge).replace(Pi,Je),Qe(t)}function Qe(e){try{var t=oi.Function("scope","Math","return "+e);return function(e){return t.call(this,e,Math)}}catch(e){return ze}}function Xe(e){var t=Ve(e);if(t)return function(e,n){We(e,t,n)}}function Ze(e,t){e=e.trim();var n=Si.get(e);if(n)return t&&!n.set&&(n.set=Xe(n.exp)),n;var r={exp:e};return r.get=Ye(e)&&e.indexOf("[")<0?Qe("scope."+e):Ke(e),t&&(r.set=Xe(e)),Si.put(e,r),r}function Ye(e){return Ii.test(e)&&!Ti.test(e)&&"Math."!==e.slice(0,5)}function et(){Ri.length=0,Bi.length=0,Ui={},Mi={},Vi=!1}function tt(){for(var e=!0;e;)e=!1,nt(Ri),nt(Bi),Ri.length?e=!0:(Xn&&Ur.devtools&&Xn.emit("flush"),et())}function nt(e){for(var t=0;t0){var o=a+(r?t:xe(t));i=na.get(o),i||(i=Gt(n,e.$options,!0),na.put(o,i))}else i=Gt(n,e.$options,!0);this.linker=i}function bt(e,t,n){var r=e.node.previousSibling;if(r){for(e=r.__v_frag;!(e&&e.forId===n&&e.inserted||r===t);){if(r=r.previousSibling,!r)return;e=r.__v_frag}return e}}function _t(e){for(var t=-1,n=new Array(Math.floor(e));++t47&&t<58?parseInt(e,10):1===e.length&&(t=e.toUpperCase().charCodeAt(0),t>64&&t<91)?t:ka[e]});return n=[].concat.apply([],n),function(t){if(n.indexOf(t.keyCode)>-1)return e.call(this,t)}}function Et(e){return function(t){return t.stopPropagation(),e.call(this,t)}}function $t(e){return function(t){return t.preventDefault(),e.call(this,t)}}function Ot(e){return function(t){if(t.target===t.currentTarget)return e.call(this,t)}}function At(e){if(Oa[e])return Oa[e];var t=Nt(e);return Oa[e]=Oa[t]=t,t}function Nt(e){e=p(e);var t=u(e),n=t.charAt(0).toUpperCase()+t.slice(1);Aa||(Aa=document.createElement("div"));var r,i=Ca.length;if("filter"!==t&&t in Aa.style)return{kebab:e,camel:t};for(;i--;)if(r=Ea[i]+n,r in Aa.style)return{kebab:Ca[i]+e,camel:r}}function Lt(e){var t=[];if(Jn(e))for(var n=0,r=e.length;n=i?n():e[a].call(t,r)}var i=e.length,a=0;e[0].call(t,r)}function jt(e,t,n){for(var i,a,o,s,l,c,h,f=[],d=n.$options.propsData,v=Object.keys(t),m=v.length;m--;)a=v[m],i=t[a]||za,l=u(a),qa.test(l)&&(h={name:a,path:l,options:i,mode:Wa.ONE_WAY,raw:null},o=p(a),null===(s=Y(e,o))&&(null!==(s=Y(e,o+".sync"))?h.mode=Wa.TWO_WAY:null!==(s=Y(e,o+".once"))&&(h.mode=Wa.ONE_TIME)),null!==s?(h.raw=s,c=B(s),s=c.expression,h.filters=c.filters,r(s)&&!c.filters?h.optimizedLiteral=!0:h.dynamic=!0,h.parentPath=s):null!==(s=Z(e,o))?h.raw=s:d&&null!==(s=d[a]||d[l])&&(h.raw=s),f.push(h));return Tt(f)}function Tt(e){return function(t,r){t._props={};for(var i,a,u,c,h,f=t.$options.propsData,d=e.length;d--;)if(i=e[d],h=i.raw,a=i.path,u=i.options,t._props[a]=i,f&&n(f,a)&&Dt(t,i,f[a]),null===h)Dt(t,i,void 0);else if(i.dynamic)i.mode===Wa.ONE_TIME?(c=(r||t._context||t).$get(i.parentPath),Dt(t,i,c)):t._context?t._bindDir({name:"prop",def:Ja,prop:i},null,null,r):Dt(t,i,t.$get(i.parentPath));else if(i.optimizedLiteral){var v=l(h);c=v===h?s(o(h)):v,Dt(t,i,c)}else c=u.type===Boolean&&(""===h||h===p(i.name))||h,Dt(t,i,c)}}function Ft(e,t,n,r){var i=t.dynamic&&Ye(t.parentPath),a=n;void 0===a&&(a=Bt(e,t)),a=Mt(t,a,e);var o=a!==n;Ut(t,a,e)||(a=void 0),i&&!o?Pe(function(){r(a)}):r(a)}function Dt(e,t,n){Ft(e,t,n,function(n){De(e,t.path,n)})}function Rt(e,t,n){Ft(e,t,n,function(n){e[t.path]=n})}function Bt(e,t){var r=t.options;if(!n(r,"default"))return r.type!==Boolean&&void 0;var i=r.default;return m(i),"function"==typeof i&&r.type!==Function?i.call(e):i}function Ut(e,t,n){if(!e.options.required&&(null===e.raw||null==t))return!0;var r=e.options,i=r.type,a=!i,o=[];if(i){Jn(i)||(i=[i]);for(var s=0;st?-1:e===t?0:1}),t=0,n=s.length;tf.priority)&&(f=h,c=i.name,s=vn(i.name),o=i.value,u=l[1],p=l[2]));return f?fn(e,u,o,n,f,c,p,s):void 0}function hn(){}function fn(e,t,n,r,i,a,o,s){var l=B(n),u={name:t,arg:o,expression:l.expression,filters:l.filters,raw:n,attr:a,modifiers:s,def:i};"for"!==t&&"router-view"!==t||(u.ref=ge(e));var c=function(e,t,n,r,i){u.ref&&De((r||e).$refs,u.ref,null),e._bindDir(u,t,n,r,i)};return c.terminal=!0,c}function dn(e,t){function n(e,t,n){var r=n&&gn(n),i=!r&&B(a);v.push({name:e,attr:o,raw:s,def:t,arg:u,modifiers:c,expression:i&&i.expression,filters:i&&i.filters,interp:n,hasOneTime:r})}for(var r,i,a,o,s,l,u,c,p,h,f,d=e.length,v=[];d--;)if(r=e[d],i=o=r.name,a=s=r.value,h=V(a),u=null,c=vn(i),i=i.replace(uo,""),h)a=H(h),u=i,n("bind",Ma.bind,h);else if(co.test(i))c.literal=!oo.test(i),n("transition",ao.transition);else if(so.test(i))u=i.replace(so,""),n("on",Ma.on);else if(oo.test(i))l=i.replace(oo,""),"style"===l||"class"===l?n(l,ao[l]):(u=l,n("bind",Ma.bind));else if(f=i.match(lo)){if(l=f[1],u=f[2],"else"===l)continue;p=Ne(t,"directives",l,!0),p&&n(l,p)}if(v.length)return mn(v)}function vn(e){var t=Object.create(null),n=e.match(uo);if(n)for(var r=n.length;r--;)t[n[r].slice(1)]=!0;return t}function mn(e){return function(t,n,r,i,a){for(var o=e.length;o--;)t._bindDir(e[o],n,r,i,a)}}function gn(e){for(var t=e.length;t--;)if(e[t].oneTime)return!0}function yn(e){return"SCRIPT"===e.tagName&&(!e.hasAttribute("type")||"text/javascript"===e.getAttribute("type"))}function bn(e,t){return t&&(t._containerAttrs=xn(e)),ve(e)&&(e=ct(e)),t&&(t._asComponent&&!t.template&&(t.template=""),t.template&&(t._content=he(e),e=_n(e,t))),_e(e)&&(ie(me("v-start",!0),e),e.appendChild(me("v-end",!0))),e}function _n(e,t){var n=t.template,r=ct(n,!0);if(r){var i=r.firstChild;if(!i)return r;var a=i.tagName&&i.tagName.toLowerCase();return t.replace?(e===document.body,r.childNodes.length>1||1!==i.nodeType||"component"===a||Ne(t,"components",a)||ee(i,"is")||Ne(t,"elementDirectives",a)||i.hasAttribute("v-for")||i.hasAttribute("v-if")?r:(t._replacerAttrs=xn(i),wn(e,i),i)):(e.appendChild(r),e)}}function xn(e){if(1===e.nodeType&&e.hasAttributes())return d(e.attributes)}function wn(e,t){for(var n,r,i=e.attributes,a=i.length;a--;)n=i[a].name,r=i[a].value,t.hasAttribute(n)||fo.test(n)?"class"===n&&!V(r)&&(r=r.trim())&&r.split(/\s+/).forEach(function(e){ce(t,e)}):t.setAttribute(n,r)}function kn(e,t){if(t){for(var n,r,i=e._slotContents=Object.create(null),a=0,o=t.children.length;a1?d(n):n;var i=t&&n.some(function(e){return e._fromParent});i&&(r=!1);for(var a=d(arguments,1),o=0,s=n.length;ot?a:-a}var n=null,r=void 0;e=xo(e);var i=d(arguments,1),a=i[i.length-1];"number"==typeof a?(a=a<0?-1:1,i=i.length>1?i.slice(0,-1):i):a=1;var o=i[0];return o?("function"==typeof o?n=function(e,t){return o(e,t)*a}:(r=Array.prototype.concat.apply([],i),n=function(e,i,a){return a=a||0,a>=r.length-1?t(e,i,a):t(e,i,a)||n(e,i,a+1)}),e.slice().sort(n)):e}function Bn(e,t){var n;if(g(e)){var r=Object.keys(e);for(n=r.length;n--;)if(Bn(e[r[n]],t))return!0}else if(Jn(e)){for(n=e.length;n--;)if(Bn(e[n],t))return!0}else if(null!=e)return e.toString().toLowerCase().indexOf(t)>-1}function Un(n){n.options={directives:Ma,elementDirectives:_o,filters:ko,transitions:{},components:{},partials:{},replace:!0},n.util=Yr,n.config=Ur,n.set=e,n.delete=t,n.nextTick=ur,n.compiler=vo,n.FragmentFactory=yt,n.internalDirectives=ao,n.parsers={path:ki,text:Dr,template:ea,directive:Lr,expression:Di},n.cid=0;var r=1;n.extend=function(e){e=e||{};var t=this,i=0===t.cid;if(i&&e._Ctor)return e._Ctor;var a=e.name||t.options.name,o=function(e){n.call(this,e)};return o.prototype=Object.create(t.prototype),o.prototype.constructor=o,o.cid=r++,o.options=Ae(t.options,e),o.super=t,o.extend=t.extend,Ur._assetTypes.forEach(function(e){o[e]=t[e]}),a&&(o.options.components[a]=o),i&&(e._Ctor=o),o},n.use=function(e){if(!e.installed){var t=d(arguments,1);return t.unshift(this),"function"==typeof e.install?e.install.apply(e,t):e.apply(null,t),e.installed=!0,this}},n.mixin=function(e){n.options=Ae(n.options,e)},Ur._assetTypes.forEach(function(e){n[e]=function(t,r){return r?("component"===e&&g(r)&&(r.name||(r.name=t),r=n.extend(r)),this.options[e+"s"][t]=r,r):this.options[e+"s"][t]}}),v(n.transition,Vr)}var Mn=Object.prototype.hasOwnProperty,Vn=/^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/,Hn=/-(\w)/g,Wn=/([^-])([A-Z])/g,zn=/(?:^|[-_\/])(\w)/g,qn=Object.prototype.toString,Gn="[object Object]",Jn=Array.isArray,Kn="__proto__"in{},Qn="undefined"!=typeof window&&"[object Object]"!==Object.prototype.toString.call(window),Xn=Qn&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__,Zn=Qn&&window.navigator.userAgent.toLowerCase(),Yn=Zn&&Zn.indexOf("trident")>0,er=Zn&&Zn.indexOf("msie 9.0")>0,tr=Zn&&Zn.indexOf("android")>0,nr=Zn&&/iphone|ipad|ipod|ios/.test(Zn),rr=void 0,ir=void 0,ar=void 0,or=void 0;if(Qn&&!er){var sr=void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend,lr=void 0===window.onanimationend&&void 0!==window.onwebkitanimationend;rr=sr?"WebkitTransition":"transition",ir=sr?"webkitTransitionEnd":"transitionend",ar=lr?"WebkitAnimation":"animation",or=lr?"webkitAnimationEnd":"animationend"}var ur=function(){function e(){n=!1;var e=t.slice(0);t.length=0;for(var r=0;r=this.length&&(this.length=Number(e)+1),this.splice(e,1,t)[0]}),y(Kr,"$remove",function(e){if(this.length){var t=_(this,e);return t>-1?this.splice(t,1):void 0}});var Xr=Object.getOwnPropertyNames(Qr),Zr=!0;Ie.prototype.walk=function(e){for(var t=Object.keys(e),n=0,r=t.length;nthis.maxIterations)throw new Error("Infinite loop detected - reached max iterations")},e.exports}({exports:{}}),ii=function(e){function t(e){function i(e){for(var t=null,n=0;n=0}function i(e){return"0123456789abcdefABCDEF".indexOf(e)>=0}function a(e){return"01234567".indexOf(e)>=0}function o(e){return" "===e||"\t"===e||"\v"===e||"\f"===e||"\xa0"===e||e.charCodeAt(0)>=5760&&"\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\ufeff".indexOf(e)>=0}function s(e){return"\n"===e||"\r"===e||"\u2028"===e||"\u2029"===e}function l(e){return"$"===e||"_"===e||"\\"===e||e>="a"&&e<="z"||e>="A"&&e<="Z"||e.charCodeAt(0)>=128&&pt.NonAsciiIdentifierStart.test(e)}function u(e){return"$"===e||"_"===e||"\\"===e||e>="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||e.charCodeAt(0)>=128&&pt.NonAsciiIdentifierPart.test(e)}function c(e){switch(e){case"class":case"enum":case"export":case"extends":case"import":case"super":return!0}return!1}function p(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0}return!1}function h(e){return"eval"===e||"arguments"===e}function f(e){var t=!1;switch(e.length){case 2:t="if"===e||"in"===e||"do"===e;break;case 3:t="var"===e||"for"===e||"new"===e||"try"===e;break;case 4:t="this"===e||"else"===e||"case"===e||"void"===e||"with"===e;break;case 5:t="while"===e||"break"===e||"catch"===e||"throw"===e;break;case 6:t="return"===e||"typeof"===e||"delete"===e||"switch"===e;break;case 7:t="default"===e||"finally"===e;break;case 8:t="function"===e||"continue"===e||"debugger"===e;break;case 10:t="instanceof"===e}if(t)return!0;switch(e){case"const":return!0;case"yield":case"let":return!0}return!(!ft||!p(e))||c(e)}function d(){var e,t,n;for(t=!1,n=!1;dt=gt&&E({},ct.UnexpectedToken,"ILLEGAL")):(e=ht[dt++],dt>=gt&&E({},ct.UnexpectedToken,"ILLEGAL"),"*"===e&&(e=ht[dt],"/"===e&&(++dt,t=!1)));else if("/"===e)if(e=ht[dt+1],"/"===e)dt+=2,n=!0;else{if("*"!==e)break;dt+=2,t=!0,dt>=gt&&E({},ct.UnexpectedToken,"ILLEGAL")}else if(o(e))++dt;else{if(!s(e))break;++dt,"\r"===e&&"\n"===ht[dt]&&++dt,++vt,mt=dt}}function v(e){var t,n,r,a=0;for(n="u"===e?4:2,t=0;t"===a&&">"===e&&">"===t&&"="===n?(dt+=4,{type:ot.Punctuator,value:">>>=",lineNumber:vt,lineStart:mt,range:[i,dt]}):"="===a&&"="===e&&"="===t?(dt+=3,{type:ot.Punctuator,value:"===",lineNumber:vt,lineStart:mt,range:[i,dt]}):"!"===a&&"="===e&&"="===t?(dt+=3,{type:ot.Punctuator,value:"!==",lineNumber:vt,lineStart:mt,range:[i,dt]}):">"===a&&">"===e&&">"===t?(dt+=3,{type:ot.Punctuator,value:">>>",lineNumber:vt,lineStart:mt,range:[i,dt]}):"<"===a&&"<"===e&&"="===t?(dt+=3,{type:ot.Punctuator,value:"<<=",lineNumber:vt,lineStart:mt,range:[i,dt]}):">"===a&&">"===e&&"="===t?(dt+=3,{type:ot.Punctuator,value:">>=",lineNumber:vt,lineStart:mt,range:[i,dt]}):"="===e&&"<>=!+-*%&|^/".indexOf(a)>=0?(dt+=2,{type:ot.Punctuator,value:a+e,lineNumber:vt,lineStart:mt,range:[i,dt]}):a===e&&"+-<>&|".indexOf(a)>=0&&"+-<>&|".indexOf(e)>=0?(dt+=2,{type:ot.Punctuator,value:a+e,lineNumber:vt,lineStart:mt,range:[i,dt]}):"[]<>+-*%&|^!~?:=/".indexOf(a)>=0?{type:ot.Punctuator,value:ht[dt++],lineNumber:vt,lineStart:mt,range:[i,dt]}:void 0):{type:ot.Punctuator,value:ht[dt++],lineNumber:vt,lineStart:mt,range:[i,dt]})}function y(){var e,n,o;if(o=ht[dt],t(r(o)||"."===o,"Numeric literal must start with a decimal digit or a decimal point"),n=dt,e="","."!==o){if(e=ht[dt++],o=ht[dt],"0"===e){if("x"===o||"X"===o){for(e+=ht[dt++];dt=gt&&(o=""),E({},ct.UnexpectedToken,"ILLEGAL");return dt=0&&dt=gt?{type:ot.EOF,lineNumber:vt,lineStart:mt,range:[dt,dt]}:(t=g(),"undefined"!=typeof t?t:(e=ht[dt],"'"===e||'"'===e?b():"."===e||r(e)?y():(t=m(),"undefined"!=typeof t?t:void E({},ct.UnexpectedToken,"ILLEGAL"))))}function k(){var e;return yt?(dt=yt.range[1],vt=yt.lineNumber,mt=yt.lineStart,e=yt,yt=null,e):(yt=null,w())}function S(){var e,t,n;return null!==yt?yt:(e=dt,t=vt,n=mt,yt=w(),dt=e,vt=t,mt=n,yt)}function C(){var e,t,n,r;return e=dt,t=vt,n=mt,d(),r=vt!==t,dt=e,vt=t,mt=n,r}function E(e,t){var n,r=Array.prototype.slice.call(arguments,2),i=t.replace(/%(\d)/g,function(e,t){return r[t]||""});throw"number"==typeof e.lineNumber?(n=new Error("Line "+e.lineNumber+": "+i),n.index=e.range[0],n.lineNumber=e.lineNumber,n.column=e.range[0]-mt+1):(n=new Error("Line "+vt+": "+i),n.index=dt,n.lineNumber=vt,n.column=dt-mt+1),n}function $(){try{E.apply(null,arguments)}catch(e){if(!_t.errors)throw e;_t.errors.push(e)}}function O(e){if(e.type===ot.EOF&&E(e,ct.UnexpectedEOS),e.type===ot.NumericLiteral&&E(e,ct.UnexpectedNumber),e.type===ot.StringLiteral&&E(e,ct.UnexpectedString),e.type===ot.Identifier&&E(e,ct.UnexpectedIdentifier),e.type===ot.Keyword){if(c(e.value))E(e,ct.UnexpectedReserved);else if(ft&&p(e.value))return void $(e,ct.StrictReservedWord);E(e,ct.UnexpectedToken,e.value)}E(e,ct.UnexpectedToken,e.value)}function A(e){var t=k();t.type===ot.Punctuator&&t.value===e||O(t)}function N(e){var t=k();t.type===ot.Keyword&&t.value===e||O(t)}function L(e){var t=S();return t.type===ot.Punctuator&&t.value===e}function P(e){var t=S();return t.type===ot.Keyword&&t.value===e}function I(){var e=S(),t=e.value;return e.type===ot.Punctuator&&("="===t||"*="===t||"/="===t||"%="===t||"+="===t||"-="===t||"<<="===t||">>="===t||">>>="===t||"&="===t||"^="===t||"|="===t)}function j(){var e,t;if(";"===ht[dt])return void k();if(t=vt,d(),vt===t){if(L(";"))return void k();e=S(),e.type===ot.EOF||L("}")||O(e)}}function T(e){return e.type===lt.Identifier||e.type===lt.MemberExpression}function F(){var e=[];for(A("[");!L("]");)L(",")?(k(),e.push(null)):(e.push(ue()),L("]")||A(","));return A("]"),{type:lt.ArrayExpression,elements:e}}function D(e,t){var n,r;return n=ft,r=Fe(),t&&ft&&h(e[0].name)&&$(t,ct.StrictParamName),ft=n,{type:lt.FunctionExpression,id:null,params:e,defaults:[],body:r,rest:null,generator:!1,expression:!1}}function R(){var e=k();return e.type===ot.StringLiteral||e.type===ot.NumericLiteral?(ft&&e.octal&&$(e,ct.StrictOctalLiteral),Je(e)):{type:lt.Identifier,name:e.value}}function B(){var e,t,n,r;return e=S(),e.type===ot.Identifier?(n=R(),"get"!==e.value||L(":")?"set"!==e.value||L(":")?(A(":"),{type:lt.Property,key:n,value:ue(),kind:"init"}):(t=R(),A("("),e=S(),e.type!==ot.Identifier?(A(")"),$(e,ct.UnexpectedToken,e.value),{type:lt.Property,key:t,value:D([]),kind:"set"}):(r=[fe()],A(")"),{type:lt.Property,key:t,value:D(r,e),kind:"set"})):(t=R(),A("("),A(")"),{type:lt.Property,key:t,value:D([]),kind:"get"})):e.type!==ot.EOF&&e.type!==ot.Punctuator?(t=R(),A(":"),{type:lt.Property,key:t,value:ue(),kind:"init"}):void O(e)}function U(){var e,t,n,r=[],i={},a=String;for(A("{");!L("}");)e=B(),t=e.key.type===lt.Identifier?e.key.name:a(e.key.value),n="init"===e.kind?ut.Data:"get"===e.kind?ut.Get:ut.Set,Object.prototype.hasOwnProperty.call(i,t)?(i[t]===ut.Data?ft&&n===ut.Data?$({},ct.StrictDuplicateProperty):n!==ut.Data&&$({},ct.AccessorDataProperty):n===ut.Data?$({},ct.AccessorDataProperty):i[t]&n&&$({},ct.AccessorGetSet),i[t]|=n):i[t]=n,r.push(e),L("}")||A(",");return A("}"),{type:lt.ObjectExpression,properties:r}}function M(){var e;return A("("),e=ce(),A(")"),e}function V(){var e=S(),t=e.type;if(t===ot.Identifier)return{type:lt.Identifier,name:k().value};if(t===ot.StringLiteral||t===ot.NumericLiteral)return ft&&e.octal&&$(e,ct.StrictOctalLiteral),Je(k());if(t===ot.Keyword){if(P("this"))return k(),{type:lt.ThisExpression};if(P("function"))return Re()}return t===ot.BooleanLiteral?(k(),e.value="true"===e.value,Je(e)):t===ot.NullLiteral?(k(),e.value=null,Je(e)):L("[")?F():L("{")?U():L("(")?M():L("/")||L("/=")?Je(_()):O(k())}function H(){var e=[];if(A("("),!L(")"))for(;dt>")||L(">>>");)e={type:lt.BinaryExpression, +operator:k().value,left:e,right:Y()};return e}function te(){var e,t;for(t=bt.allowIn,bt.allowIn=!0,e=ee();L("<")||L(">")||L("<=")||L(">=")||t&&P("in")||P("instanceof");)e={type:lt.BinaryExpression,operator:k().value,left:e,right:ee()};return bt.allowIn=t,e}function ne(){for(var e=te();L("==")||L("!=")||L("===")||L("!==");)e={type:lt.BinaryExpression,operator:k().value,left:e,right:te()};return e}function re(){for(var e=ne();L("&");)k(),e={type:lt.BinaryExpression,operator:"&",left:e,right:ne()};return e}function ie(){for(var e=re();L("^");)k(),e={type:lt.BinaryExpression,operator:"^",left:e,right:re()};return e}function ae(){for(var e=ie();L("|");)k(),e={type:lt.BinaryExpression,operator:"|",left:e,right:ie()};return e}function oe(){for(var e=ae();L("&&");)k(),e={type:lt.LogicalExpression,operator:"&&",left:e,right:ae()};return e}function se(){for(var e=oe();L("||");)k(),e={type:lt.LogicalExpression,operator:"||",left:e,right:oe()};return e}function le(){var e,t,n;return e=se(),L("?")&&(k(),t=bt.allowIn,bt.allowIn=!0,n=ue(),bt.allowIn=t,A(":"),e={type:lt.ConditionalExpression,test:e,consequent:n,alternate:ue()}),e}function ue(){var e,t;return e=S(),t=le(),I()&&(T(t)||$({},ct.InvalidLHSInAssignment),ft&&t.type===lt.Identifier&&h(t.name)&&$(e,ct.StrictLHSAssignment),t={type:lt.AssignmentExpression,operator:k().value,left:t,right:ue()}),t}function ce(){var e=ue();if(L(","))for(e={type:lt.SequenceExpression,expressions:[e]};dt0&&_t.comments[_t.comments.length-1].range[1]>r||_t.comments.push({type:e,value:n,range:[r,i],loc:a})}function He(){var e,t,n,r,i,a;for(e="",i=!1,a=!1;dt=gt?(a=!1,e+=t,n.end={line:vt,column:gt-mt},Ve("Line",e,r,gt,n)):e+=t;else if(i)s(t)?("\r"===t&&"\n"===ht[dt+1]?(++dt,e+="\r\n"):e+=t,++vt,++dt,mt=dt,dt>=gt&&E({},ct.UnexpectedToken,"ILLEGAL")):(t=ht[dt++],dt>=gt&&E({},ct.UnexpectedToken,"ILLEGAL"),e+=t,"*"===t&&(t=ht[dt],"/"===t&&(e=e.substr(0,e.length-1),i=!1,++dt,n.end={line:vt,column:dt-mt},Ve("Block",e,r,dt,n),e="")));else if("/"===t)if(t=ht[dt+1],"/"===t)n={start:{line:vt,column:dt-mt}},r=dt,dt+=2,a=!0,dt>=gt&&(n.end={line:vt,column:dt-mt},a=!1,Ve("Line",e,r,dt,n));else{if("*"!==t)break;r=dt,dt+=2,i=!0,n={start:{line:vt,column:dt-mt-2}},dt>=gt&&E({},ct.UnexpectedToken,"ILLEGAL")}else if(o(t))++dt;else{if(!s(t))break;++dt,"\r"===t&&"\n"===ht[dt]&&++dt,++vt,mt=dt}}function We(){var e,t,n,r=[];for(e=0;e<_t.comments.length;++e)t=_t.comments[e],n={type:t.type,value:t.value},_t.range&&(n.range=t.range),_t.loc&&(n.loc=t.loc),r.push(n);_t.comments=r}function ze(){var e,t,r,i,a;return d(),e=dt,t={start:{line:vt,column:dt-mt}},r=_t.advance(),t.end={line:vt,column:dt-mt},r.type!==ot.EOF&&(i=[r.range[0],r.range[1]],a=n(r.range[0],r.range[1]),_t.tokens.push({type:st[r.type],value:a,range:i,loc:t})),r}function qe(){var e,t,n,r;return d(),e=dt,t={start:{line:vt,column:dt-mt}},n=_t.scanRegExp(),t.end={line:vt,column:dt-mt},_t.tokens.length>0&&(r=_t.tokens[_t.tokens.length-1],r.range[0]===e&&"Punctuator"===r.type&&("/"!==r.value&&"/="!==r.value||_t.tokens.pop())),_t.tokens.push({type:"RegularExpression",value:n.literal,range:[e,dt],loc:t}),n}function Ge(){var e,t,n,r=[];for(e=0;e<_t.tokens.length;++e)t=_t.tokens[e],n={type:t.type,value:t.value},_t.range&&(n.range=t.range),_t.loc&&(n.loc=t.loc),r.push(n);_t.tokens=r}function Je(e){return{type:lt.Literal,value:e.value}}function Ke(e){return{type:lt.Literal,value:e.value,raw:n(e.range[0],e.range[1])}}function Qe(){var e={};return e.range=[dt,dt],e.loc={start:{line:vt,column:dt-mt},end:{line:vt,column:dt-mt}},e.end=function(){this.range[1]=dt,this.loc.end.line=vt,this.loc.end.column=dt-mt},e.applyGroup=function(e){_t.range&&(e.groupRange=[this.range[0],this.range[1]]),_t.loc&&(e.groupLoc={start:{line:this.loc.start.line,column:this.loc.start.column},end:{line:this.loc.end.line,column:this.loc.end.column}})},e.apply=function(e){_t.range&&(e.range=[this.range[0],this.range[1]]),_t.loc&&(e.loc={start:{line:this.loc.start.line,column:this.loc.start.column},end:{line:this.loc.end.line,column:this.loc.end.column}})},e}function Xe(){var e,t;return d(),e=Qe(),A("("),t=ce(),A(")"),e.end(),e.applyGroup(t),t}function Ze(){var e,t;for(d(),e=Qe(),t=P("new")?G():V();L(".")||L("[");)L("[")?(t={type:lt.MemberExpression,computed:!0,object:t,property:q()},e.end(),e.apply(t)):(t={type:lt.MemberExpression,computed:!1,object:t,property:z()},e.end(),e.apply(t));return t}function Ye(){var e,t;for(d(),e=Qe(),t=P("new")?G():V();L(".")||L("[")||L("(");)L("(")?(t={type:lt.CallExpression,callee:t,arguments:H()},e.end(),e.apply(t)):L("[")?(t={type:lt.MemberExpression,computed:!0,object:t,property:q()},e.end(),e.apply(t)):(t={type:lt.MemberExpression,computed:!1,object:t,property:z()},e.end(),e.apply(t));return t}function et(e){var t,n,r;t="[object Array]"===Object.prototype.toString.apply(e)?[]:{};for(n in e)e.hasOwnProperty(n)&&"groupRange"!==n&&"groupLoc"!==n&&(r=e[n],null===r||"object"!=typeof r||r instanceof RegExp?t[n]=r:t[n]=et(r));return t}function tt(e,t){return function(n){function r(e){return e.type===lt.LogicalExpression||e.type===lt.BinaryExpression}function i(n){var a,o;r(n.left)&&i(n.left),r(n.right)&&i(n.right),e&&(n.left.groupRange||n.right.groupRange?(a=n.left.groupRange?n.left.groupRange[0]:n.left.range[0],o=n.right.groupRange?n.right.groupRange[1]:n.right.range[1],n.range=[a,o]):"undefined"==typeof n.range&&(a=n.left.range[0],o=n.right.range[1],n.range=[a,o])),t&&(n.left.groupLoc||n.right.groupLoc?(a=n.left.groupLoc?n.left.groupLoc.start:n.left.loc.start,o=n.right.groupLoc?n.right.groupLoc.end:n.right.loc.end,n.loc={start:a,end:o}):"undefined"==typeof n.loc&&(n.loc={start:n.left.loc.start,end:n.right.loc.end}))}return function(){var a,o;return d(),a=Qe(),o=n.apply(null,arguments),a.end(),e&&"undefined"==typeof o.range&&a.apply(o),t&&"undefined"==typeof o.loc&&a.apply(o),r(o)&&i(o),o}}}function nt(){var e;_t.comments&&(_t.skipComment=d,d=He),_t.raw&&(_t.createLiteral=Je,Je=Ke),(_t.range||_t.loc)&&(_t.parseGroupExpression=M,_t.parseLeftHandSideExpression=K,_t.parseLeftHandSideExpressionAllowCall=J,M=Xe,K=Ze,J=Ye,e=tt(_t.range,_t.loc),_t.parseAdditiveExpression=Y,_t.parseAssignmentExpression=ue,_t.parseBitwiseANDExpression=re,_t.parseBitwiseORExpression=ae,_t.parseBitwiseXORExpression=ie,_t.parseBlock=he,_t.parseFunctionSourceElements=Fe,_t.parseCatchClause=Pe,_t.parseComputedMember=q,_t.parseConditionalExpression=le,_t.parseConstLetDeclaration=ge,_t.parseEqualityExpression=ne,_t.parseExpression=ce,_t.parseForVariableDeclaration=ke,_t.parseFunctionDeclaration=De,_t.parseFunctionExpression=Re,_t.parseLogicalANDExpression=oe,_t.parseLogicalORExpression=se,_t.parseMultiplicativeExpression=Z,_t.parseNewExpression=G,_t.parseNonComputedProperty=W,_t.parseObjectProperty=B,_t.parseObjectPropertyKey=R,_t.parsePostfixExpression=Q,_t.parsePrimaryExpression=V,_t.parseProgram=Me,_t.parsePropertyFunction=D,_t.parseRelationalExpression=te,_t.parseStatement=Te,_t.parseShiftExpression=ee,_t.parseSwitchCase=Ae,_t.parseUnaryExpression=X,_t.parseVariableDeclaration=de,_t.parseVariableIdentifier=fe,Y=e(_t.parseAdditiveExpression),ue=e(_t.parseAssignmentExpression),re=e(_t.parseBitwiseANDExpression),ae=e(_t.parseBitwiseORExpression),ie=e(_t.parseBitwiseXORExpression),he=e(_t.parseBlock),Fe=e(_t.parseFunctionSourceElements),Pe=e(_t.parseCatchClause),q=e(_t.parseComputedMember),le=e(_t.parseConditionalExpression),ge=e(_t.parseConstLetDeclaration),ne=e(_t.parseEqualityExpression),ce=e(_t.parseExpression),ke=e(_t.parseForVariableDeclaration),De=e(_t.parseFunctionDeclaration),Re=e(_t.parseFunctionExpression),K=e(K),oe=e(_t.parseLogicalANDExpression),se=e(_t.parseLogicalORExpression),Z=e(_t.parseMultiplicativeExpression),G=e(_t.parseNewExpression),W=e(_t.parseNonComputedProperty),B=e(_t.parseObjectProperty),R=e(_t.parseObjectPropertyKey),Q=e(_t.parsePostfixExpression),V=e(_t.parsePrimaryExpression),Me=e(_t.parseProgram),D=e(_t.parsePropertyFunction),te=e(_t.parseRelationalExpression),Te=e(_t.parseStatement),ee=e(_t.parseShiftExpression),Ae=e(_t.parseSwitchCase),X=e(_t.parseUnaryExpression),de=e(_t.parseVariableDeclaration),fe=e(_t.parseVariableIdentifier)),"undefined"!=typeof _t.tokens&&(_t.advance=w,_t.scanRegExp=_,w=ze,_=qe)}function rt(){"function"==typeof _t.skipComment&&(d=_t.skipComment),_t.raw&&(Je=_t.createLiteral),(_t.range||_t.loc)&&(Y=_t.parseAdditiveExpression,ue=_t.parseAssignmentExpression,re=_t.parseBitwiseANDExpression,ae=_t.parseBitwiseORExpression,ie=_t.parseBitwiseXORExpression,he=_t.parseBlock,Fe=_t.parseFunctionSourceElements,Pe=_t.parseCatchClause,q=_t.parseComputedMember,le=_t.parseConditionalExpression,ge=_t.parseConstLetDeclaration,ne=_t.parseEqualityExpression,ce=_t.parseExpression,ke=_t.parseForVariableDeclaration,De=_t.parseFunctionDeclaration,Re=_t.parseFunctionExpression,M=_t.parseGroupExpression,K=_t.parseLeftHandSideExpression,J=_t.parseLeftHandSideExpressionAllowCall,oe=_t.parseLogicalANDExpression,se=_t.parseLogicalORExpression,Z=_t.parseMultiplicativeExpression,G=_t.parseNewExpression,W=_t.parseNonComputedProperty,B=_t.parseObjectProperty,R=_t.parseObjectPropertyKey,V=_t.parsePrimaryExpression,Q=_t.parsePostfixExpression,Me=_t.parseProgram,D=_t.parsePropertyFunction,te=_t.parseRelationalExpression,Te=_t.parseStatement,ee=_t.parseShiftExpression,Ae=_t.parseSwitchCase,X=_t.parseUnaryExpression,de=_t.parseVariableDeclaration,fe=_t.parseVariableIdentifier),"function"==typeof _t.scanRegExp&&(w=_t.advance,_=_t.scanRegExp)}function it(e){var t,n=e.length,r=[];for(t=0;t0?1:0,mt=0,gt=ht.length,yt=null,bt={allowIn:!0,labelSet:{},inFunctionBody:!1,inIteration:!1,inSwitch:!1},_t={},"undefined"!=typeof t&&(_t.range="boolean"==typeof t.range&&t.range,_t.loc="boolean"==typeof t.loc&&t.loc,_t.raw="boolean"==typeof t.raw&&t.raw,"boolean"==typeof t.tokens&&t.tokens&&(_t.tokens=[]),"boolean"==typeof t.comment&&t.comment&&(_t.comments=[]),"boolean"==typeof t.tolerant&&t.tolerant&&(_t.errors=[])),gt>0&&"undefined"==typeof ht[0]&&(e instanceof String&&(ht=e.valueOf()),"undefined"==typeof ht[0]&&(ht=it(e))),nt();try{n=Me(),"undefined"!=typeof _t.comments&&(We(),n.comments=_t.comments),"undefined"!=typeof _t.tokens&&(Ge(),n.tokens=_t.tokens),"undefined"!=typeof _t.errors&&(n.errors=_t.errors),(_t.range||_t.loc)&&(n.body=et(n.body))}catch(e){throw e}finally{rt(),_t={}}return n}var ot,st,lt,ut,ct,pt,ht,ft,dt,vt,mt,gt,yt,bt,_t;ot={BooleanLiteral:1,EOF:2,Identifier:3,Keyword:4,NullLiteral:5,NumericLiteral:6,Punctuator:7,StringLiteral:8},st={},st[ot.BooleanLiteral]="Boolean",st[ot.EOF]="",st[ot.Identifier]="Identifier",st[ot.Keyword]="Keyword",st[ot.NullLiteral]="Null",st[ot.NumericLiteral]="Numeric",st[ot.Punctuator]="Punctuator",st[ot.StringLiteral]="String",lt={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement"},ut={Data:1,Get:2,Set:4},ct={UnexpectedToken:"Unexpected token %0",UnexpectedNumber:"Unexpected number",UnexpectedString:"Unexpected string",UnexpectedIdentifier:"Unexpected identifier",UnexpectedReserved:"Unexpected reserved word",UnexpectedEOS:"Unexpected end of input",NewlineAfterThrow:"Illegal newline after throw",InvalidRegExp:"Invalid regular expression",UnterminatedRegExp:"Invalid regular expression: missing /",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInForIn:"Invalid left-hand side in for-in",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NoCatchOrFinally:"Missing catch or finally after try",UnknownLabel:"Undefined label '%0'",Redeclaration:"%0 '%1' has already been declared",IllegalContinue:"Illegal continue statement",IllegalBreak:"Illegal break statement",IllegalReturn:"Illegal return statement",StrictModeWith:"Strict mode code may not include a with statement",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictParamDupe:"Strict mode function may not have duplicate parameter names",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictDuplicateProperty:"Duplicate data property in object literal not allowed in strict mode",AccessorDataProperty:"Object literal may not have data and accessor property with the same name",AccessorGetSet:"Object literal may not have multiple get/set accessors with the same name",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictReservedWord:"Use of future reserved word in strict mode"},pt={NonAsciiIdentifierStart:new RegExp("[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]"),NonAsciiIdentifierPart:new RegExp("[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]")},"undefined"==typeof"esprima"[0]&&(n=function(e,t){return ht.slice(e,t).join("")}),e.version="1.0.4",e.parse=at,e.Syntax=function(){var e,t={};"function"==typeof Object.create&&(t=Object.create(null));for(e in lt)lt.hasOwnProperty(e)&&(t[e]=lt[e]); +return"function"==typeof Object.freeze&&Object.freeze(t),t}()}),e.exports}({exports:{}}),oi=function(e,t){function n(e,t){var n=i(e),r=Object.create(t||{});return f(a(n,r))}function r(e){var t=Object.create(e||{});return function(){var e=Array.prototype.slice.call(arguments),n=e.slice(-1)[0];e=e.slice(0,-1),"string"==typeof n&&(n=m("function a(){"+n+"}").body[0].body);var r=i(n);return h(r,e,t)}}function i(e){var t="string"==typeof e?m(e):e;return g(t)}function a(e,t){function n(e){for(var t=void 0,n=0;n":return j>S;case">=":return j>=S;case"|":return j|S;case"&":return j&S;case"^":return j^S;case"instanceof":return j instanceof S;default:return o(e)}case"LogicalExpression":switch(e.operator){case"&&":return i(e.left)&&i(e.right);case"||":return i(e.left)||i(e.right);default:return o(e)}case"ThisExpression":return w.this;case"Identifier":if("undefined"===e.name)return;if(l(w,e.name,x))return f(w[e.name]);throw new ReferenceError(e.name+" is not defined");case"CallExpression":var I=e.arguments.map(function(e){return i(e)}),T=null,$=i(e.callee);return"MemberExpression"===e.callee.type&&(T=i(e.callee.object)),$.apply(T,I);case"MemberExpression":var L=i(e.object);if(e.computed)var P=i(e.property);else var P=e.property.name;return L=x.getPropertyObject(L,P),a(L[P]);case"ConditionalExpression":var N=i(e.test);return i(N?e.consequent:e.alternate);case"EmptyStatement":return;default:return o(e)}}function a(e){return e===si&&(e=g),f(e)}function u(){w=Object.create(w)}function c(){w=Object.getPrototypeOf(w)}function m(e,t,n,r){var a=null;if("Identifier"===t.type?(a=t.name,e=s(e,a,x)):"MemberExpression"===t.type&&(a=t.computed?i(t.property):t.property.name,e=i(t.object)),p(e,a,x))switch(r){case void 0:return e[a]=i(n);case"=":return e[a]=i(n);case"+=":return e[a]+=i(n);case"-=":return e[a]-=i(n);case"++":return e[a]++;case"--":return e[a]--}}var g=r(t),x=b(t),w=t;return i(e)}function o(e){console.error(e);var t=new Error("Unsupported expression: "+e.type);throw t.node=e,t}function s(e,t,n){var r=n.getPrototypeOf(e);return!r||u(e,t)?e:s(r,t,n)}function l(e,t,n){var r=n.getPrototypeOf(e),i=u(e,t);return void 0!==e[t]||(!r||i?i:l(r,t,n))}function u(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function c(e,t){return Object.prototype.propertyIsEnumerable.call(e,t)}function p(e,t,n){return"__proto__"!==t&&!n.isPrimitive(e)&&(null==e||(u(e,t)?!!c(e,t):p(n.getPrototypeOf(e),t,n)))}function h(e,n,r){return function(){var i=Object.create(r);this==t?i.this=null:i.this=this;var o=Array.prototype.slice.call(arguments);i.arguments=arguments,o.forEach(function(e,t){var r=n[t];r&&(i[r]=e)});var s=a(e,i);if(s instanceof v)return s.value}}function f(e){return e instanceof v?e.value:e}function d(e){return e.name}function v(e,t){this.type=e,this.value=t}var m=(e.exports,ai.parse),g=ii,y=ri,b=ni;e.exports=n,e.exports.FunctionFactory=r,e.exports.Function=r();var _=1e6;return e.exports}({exports:{}},ti),si=oi.Function,li=new S(1e3),ui=0,ci=1,pi=2,hi=3,fi=0,di=1,vi=2,mi=3,gi=4,yi=5,bi=6,_i=7,xi=8,wi=[];wi[fi]={ws:[fi],ident:[mi,ui],"[":[gi],eof:[_i]},wi[di]={ws:[di],".":[vi],"[":[gi],eof:[_i]},wi[vi]={ws:[vi],ident:[mi,ui]},wi[mi]={ident:[mi,ui],0:[mi,ui],number:[mi,ui],ws:[di,ci],".":[vi,ci],"[":[gi,ci],eof:[_i,ci]},wi[gi]={"'":[yi,ui],'"':[bi,ui],"[":[gi,pi],"]":[di,hi],eof:xi,else:[gi,ui]},wi[yi]={"'":[gi,ui],eof:xi,else:[yi,ui]},wi[bi]={'"':[gi,ui],eof:xi,else:[bi,ui]};var ki=Object.freeze({parsePath:Ve,getPath:He,setPath:We}),Si=new S(1e3),Ci="Math,Date,this,true,false,null,undefined,Infinity,NaN,isNaN,isFinite,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,parseInt,parseFloat",Ei=new RegExp("^("+Ci.replace(/,/g,"\\b|")+"\\b)"),$i="break,case,class,catch,const,continue,debugger,default,delete,do,else,export,extends,finally,for,function,if,import,in,instanceof,let,return,super,switch,throw,try,var,while,with,yield,enum,await,implements,package,protected,static,interface,private,public",Oi=new RegExp("^("+$i.replace(/,/g,"\\b|")+"\\b)"),Ai=/\s/g,Ni=/\n/g,Li=/[\{,]\s*[\w\$_]+\s*:|('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\"']|\\.)*`|`(?:[^`\\]|\\.)*`)|new |typeof |void /g,Pi=/"(\d+)"/g,Ii=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*$/,ji=/[^\w$\.](?:[A-Za-z_$][\w$]*)/g,Ti=/^(?:true|false|null|undefined|Infinity|NaN)$/,Fi=[],Di=Object.freeze({parseExpression:Ze,isSimplePath:Ye}),Ri=[],Bi=[],Ui={},Mi={},Vi=!1,Hi=0;it.prototype.get=function(){this.beforeGet();var e,t=this.scope||this.vm;try{e=this.getter.call(t,t)}catch(e){}return this.deep&&at(e),this.preProcess&&(e=this.preProcess(e)),this.filters&&(e=t._applyFilters(e,null,this.filters,!1)),this.postProcess&&(e=this.postProcess(e)),this.afterGet(),e},it.prototype.set=function(e){var t=this.scope||this.vm;this.filters&&(e=t._applyFilters(e,this.value,this.filters,!0));try{this.setter.call(t,t,e)}catch(e){}var n=t.$forContext;if(n&&n.alias===this.expression){if(n.filters)return;n._withLock(function(){t.$key?n.rawValue[t.$key]=e:n.rawValue.$set(t.$index,e)})}},it.prototype.beforeGet=function(){Le.target=this},it.prototype.addDep=function(e){var t=e.id;this.newDepIds.has(t)||(this.newDepIds.add(t),this.newDeps.push(e),this.depIds.has(t)||e.addSub(this))},it.prototype.afterGet=function(){Le.target=null;for(var e=this.deps.length;e--;){var t=this.deps[e];this.newDepIds.has(t.id)||t.removeSub(this)}var n=this.depIds;this.depIds=this.newDepIds,this.newDepIds=n,this.newDepIds.clear(),n=this.deps,this.deps=this.newDeps,this.newDeps=n,this.newDeps.length=0},it.prototype.update=function(e){this.lazy?this.dirty=!0:this.sync||!Ur.async?this.run():(this.shallow=this.queued?!!e&&this.shallow:!!e,this.queued=!0,rt(this))},it.prototype.run=function(){if(this.active){var e=this.get();if(e!==this.value||(m(e)||this.deep)&&!this.shallow){var t=this.value;this.value=e;this.prevError;this.cb.call(this.vm,e,t)}this.queued=this.shallow=!1}},it.prototype.evaluate=function(){var e=Le.target;this.value=this.get(),this.dirty=!1,Le.target=e},it.prototype.depend=function(){for(var e=this.deps.length;e--;)this.deps[e].depend()},it.prototype.teardown=function(){if(this.active){this.vm._isBeingDestroyed||this.vm._vForRemoving||this.vm._watchers.$remove(this);for(var e=this.deps.length;e--;)this.deps[e].removeSub(this);this.active=!1,this.vm=this.cb=this.value=null}};var Wi=new cr,zi={bind:function(){this.attr=3===this.el.nodeType?"data":"textContent"},update:function(e){this.el[this.attr]=a(e)}},qi=new S(1e3),Gi=new S(1e3),Ji={efault:[0,"",""],legend:[1,"
","
"],tr:[2,"","
"],col:[2,"","
"]};Ji.td=Ji.th=[3,"","
"],Ji.option=Ji.optgroup=[1,'"],Ji.thead=Ji.tbody=Ji.colgroup=Ji.caption=Ji.tfoot=[1,"","
"],Ji.g=Ji.defs=Ji.symbol=Ji.use=Ji.image=Ji.text=Ji.circle=Ji.ellipse=Ji.line=Ji.path=Ji.polygon=Ji.polyline=Ji.rect=[1,'',""];var Ki=/<([\w:-]+)/,Qi=/&#?\w+?;/,Xi=/ +
+
+
+
+
{{ entry.issuer.split('::')[0] }}
+
+ +
+
+ +
+ +
+
+
+
+ +
+ + + + + + +
+
+
+ +
+

Authenticator for Google™ Authenticator,
© 2018
Authenticator Extension. Released under the MIT License.

+

Google™ is Google's trademark, Google Authenticator is Google’s trade name, those rights of ownership belong with Google Inc.

+

jsqrcode Copyright jsqrcode authors. Licensed under the Apache License.

+

ZXing Copyright ZXing authors. Licensed under the Apache License.

+

totp.js Copyright its author. Licensed under the MIT License.

+

jsSHA Copyright jsSHA authors. Licensed under the BSD License.

+

qrcode.js Copyright qrcode.js author. Licensed under the MIT License.

+

crypto-js Copyright crypto-js author. Licensed under the BSD License.

+

Droid Sans Mono Copyright Steve Matteson. Licensed under the Apache License.

+

Font Awesome Copyright Dave Gandy. Licensed under the SIL OFL License 1.1.

+

Thanks to Mike Robinson <3

+
+ +
+
+
{{ i18n.add_qr }}
+
{{ i18n.add_secret }}
+
+
+ + + + + +
{{ i18n.ok }}
+
+
+ +
+
{{ i18n.security_warning }}
+ + + + +
{{ i18n.ok }}
+
+ +
+
{{ i18n.passphrase_info }}
+ + +
{{ i18n.ok }}
+
+ +
+
{{ i18n.export_info }}
+ {{ i18n.download_backup }} + {{ i18n.import_backup }} +
+ +
+
+
{{ i18n.dropbox_risk }}
+ + + + +
{{ i18n.ok }}
+
+
+ +
+ + +
{{ i18n.ok }}
+
+
+
+ + +
+
{{ message.length ? message[0] : '' }}
+
{{ i18n.ok }}
+
+ + +
+
{{ confirmMessage }}
+
+
{{ i18n.yes }}
+
{{ i18n.no }}
+
+
+ + +
{{ notification }}
+ + +
+ + +
+ + + + + + + + + + + + + + + + + diff --git a/qr.html b/qr.html new file mode 100644 index 000000000..4111933e1 --- /dev/null +++ b/qr.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/background.ts b/src/background.ts new file mode 100644 index 000000000..2aba094bc --- /dev/null +++ b/src/background.ts @@ -0,0 +1,145 @@ +/* tslint:disable:no-reference */ +/// +/// +/// +/// + +let cachedPassphrase = ''; + +chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + if (message.action === 'position') { + if (!sender.tab) { + return; + } + getQr( + sender.tab, message.info.left, message.info.top, message.info.width, + message.info.height, message.info.windowWidth, message.info.passphrase); + } else if (message.action === 'cachePassphrase') { + cachedPassphrase = message.value; + } else if (message.action === 'passphrase') { + sendResponse(cachedPassphrase); + } +}); + +let contentTab: chrome.tabs.Tab; + +function getQr( + tab: chrome.tabs.Tab, left: number, top: number, width: number, + height: number, windowWidth: number, passphrase: string) { + chrome.tabs.captureVisibleTab(tab.windowId, {format: 'png'}, (dataUrl) => { + contentTab = tab; + const qr = new Image(); + qr.src = dataUrl; + qr.onload = () => { + const captureCanvas = document.createElement('canvas'); + captureCanvas.width = width; + captureCanvas.height = height; + const ctx = captureCanvas.getContext('2d'); + if (!ctx) { + return; + } + ctx.drawImage(qr, left, top, width, height, 0, 0, width, height); + const url = captureCanvas.toDataURL(); + qrcode.callback = (text) => { + getTotp(text, passphrase); + }; + qrcode.decode(url); + }; + }); +} + +async function getTotp(text: string, passphrase: string) { + const id = contentTab.id; + if (!id) { + return; + } + + if (text.indexOf('otpauth://') !== 0) { + if (text === 'error decoding QR Code') { + chrome.tabs.sendMessage(id, {action: 'errorqr'}); + } else { + chrome.tabs.sendMessage(id, {action: 'text', text}); + } + } else { + let uri = text.split('otpauth://')[1]; + let type = uri.substr(0, 4).toLowerCase(); + uri = uri.substr(5); + let label = uri.split('?')[0]; + const parameterPart = uri.split('?')[1]; + if (!label || !parameterPart) { + chrome.tabs.sendMessage(id, {action: 'errorqr'}); + } else { + let account = ''; + let secret = ''; + let issuer = ''; + + label = decodeURIComponent(label); + if (label.indexOf(':') !== -1) { + issuer = label.split(':')[0]; + account = label.split(':')[1]; + } else { + account = label; + } + const parameters = parameterPart.split('&'); + parameters.forEach((item) => { + const parameter = item.split('='); + if (parameter[0].toLowerCase() === 'secret') { + secret = parameter[1]; + } else if (parameter[0].toLowerCase() === 'issuer') { + issuer = parameter[1]; + } else if (parameter[0].toLowerCase() === 'counter') { + let counter = Number(parameter[1]); + counter = (isNaN(counter) || counter < 0) ? 0 : counter; + } + }); + + if (!secret) { + chrome.tabs.sendMessage(id, {action: 'errorqr'}); + } else if ( + !/^[0-9a-f]+$/i.test(secret) && !/^[2-7a-z]+=*$/i.test(secret)) { + chrome.tabs.sendMessage(id, {action: 'secretqr', secret}); + } else { + const encryption = new Encryption(passphrase); + const hash = CryptoJS.MD5(secret).toString(); + if (!/^[2-7a-z]+=*$/i.test(secret) && /^[0-9a-f]+$/i.test(secret)) { + type = 'hex'; + } + const entryData: {[hash: string]: OTPStorage} = {}; + entryData[hash] = { + account, + hash, + issuer, + secret, + type, + encrypted: false, + index: 0, + counter: 0 + }; + await EntryStorage.import(encryption, entryData); + chrome.tabs.sendMessage(id, {action: 'added', account}); + } + } + } + return; +} + +// Show issue page after first install +chrome.runtime.onInstalled.addListener((details) => { + if (details.reason !== 'install') { + return; + } + + let url: string|null = null; + + if (navigator.userAgent.indexOf('Chrome') !== -1) { + url = + 'https://github.com/Authenticator-Extension/Authenticator/wiki/Chrome-Issues'; + } else if (navigator.userAgent.indexOf('Firefox') !== -1) { + url = + 'https://github.com/Authenticator-Extension/Authenticator/wiki/Firefox-Issues'; + } + + if (url) { + window.open(url, '_blank'); + } +}); diff --git a/src/content.ts b/src/content.ts new file mode 100644 index 000000000..c6dc7b1ad --- /dev/null +++ b/src/content.ts @@ -0,0 +1,164 @@ +chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + switch (message.action) { + case 'capture': + sendResponse('beginCapture'); + showGrayLayout(message.passphrase); + break; + case 'errorsecret': + alert(chrome.i18n.getMessage('errorsecret') + message.secret); + break; + case 'errorqr': + alert(chrome.i18n.getMessage('errorqr')); + break; + case 'added': + alert(message.account + chrome.i18n.getMessage('added')); + break; + case 'text': + showQrCode(message.text); + break; + default: + // invalid command, ignore it + break; + } +}); + +sessionStorage.captureBoxPositionLeft = 0; +sessionStorage.captureBoxPositionTop = 0; + +function showGrayLayout(passphrase: string) { + let grayLayout = document.getElementById('__ga_grayLayout__'); + if (!grayLayout) { + grayLayout = document.createElement('div'); + grayLayout.id = '__ga_grayLayout__'; + document.body.appendChild(grayLayout); + const scan = document.createElement('div'); + scan.className = 'scan'; + scan.style.background = 'url(' + + chrome.extension.getURL('images/scan.gif') + ') no-repeat center'; + grayLayout.appendChild(scan); + const captureBox = document.createElement('div'); + captureBox.id = '__ga_captureBox__'; + grayLayout.appendChild(captureBox); + grayLayout.onmousedown = grayLayoutDown; + grayLayout.onmousemove = grayLayoutMove; + grayLayout.onmouseup = (event) => { + grayLayoutUp(event, passphrase); + }; + grayLayout.oncontextmenu = (event) => { + event.preventDefault(); + return; + }; + } + grayLayout.style.display = 'block'; +} + +function grayLayoutDown(event: MouseEvent) { + if (event.button === 1 || event.button === 2) { + event.preventDefault(); + return; + } + const captureBox = document.getElementById('__ga_captureBox__'); + if (!captureBox) { + return; + } + + sessionStorage.captureBoxPositionLeft = event.clientX; + sessionStorage.captureBoxPositionTop = event.clientY; + captureBox.style.left = event.clientX + 'px'; + captureBox.style.top = event.clientY + 'px'; + captureBox.style.width = '1px'; + captureBox.style.height = '1px'; + captureBox.style.display = 'block'; + return; +} + +function grayLayoutMove(event: MouseEvent) { + if (event.button === 1 || event.button === 2) { + event.preventDefault(); + return; + } + const captureBox = document.getElementById('__ga_captureBox__'); + if (!captureBox) { + return; + } + + const captureBoxLeft = + Math.min(sessionStorage.captureBoxPositionLeft, event.clientX); + const captureBoxTop = + Math.min(sessionStorage.captureBoxPositionTop, event.clientY); + const captureBoxWidth = + Math.abs(sessionStorage.captureBoxPositionLeft - event.clientX) - 1; + const captureBoxHeight = + Math.abs(sessionStorage.captureBoxPositionTop - event.clientY) - 1; + captureBox.style.left = captureBoxLeft + 'px'; + captureBox.style.top = captureBoxTop + 'px'; + captureBox.style.width = captureBoxWidth + 'px'; + captureBox.style.height = captureBoxHeight + 'px'; + return; +} + +function grayLayoutUp(event: MouseEvent, passphrase: string) { + const grayLayout = document.getElementById('__ga_grayLayout__'); + const captureBox = document.getElementById('__ga_captureBox__'); + if (!captureBox || !grayLayout) { + return; + } + + setTimeout(() => { + captureBox.style.display = 'none'; + grayLayout.style.display = 'none'; + }, 100); + + if (event.button === 1 || event.button === 2) { + event.preventDefault(); + return; + } + + let captureBoxLeft = + Math.min(sessionStorage.captureBoxPositionLeft, event.clientX) + 1; + let captureBoxTop = + Math.min(sessionStorage.captureBoxPositionTop, event.clientY) + 1; + let captureBoxWidth = + Math.abs(sessionStorage.captureBoxPositionLeft - event.clientX) - 1; + let captureBoxHeight = + Math.abs(sessionStorage.captureBoxPositionTop - event.clientY) - 1; + captureBoxLeft *= window.devicePixelRatio; + captureBoxTop *= window.devicePixelRatio; + captureBoxWidth *= window.devicePixelRatio; + captureBoxHeight *= window.devicePixelRatio; + + // make sure captureBox and grayLayout is hidden + setTimeout(() => { + sendPosition( + captureBoxLeft, captureBoxTop, captureBoxWidth, captureBoxHeight, + passphrase); + }, 200); + return false; +} + +function sendPosition( + left: number, top: number, width: number, height: number, + passphrase: string) { + chrome.runtime.sendMessage({ + action: 'position', + info: { + left, + top, + width, + height, + windowWidth: window.innerWidth, + passphrase + } + }); +} + +function showQrCode(msg: string) { + const left = (screen.width / 2) - 200; + const top = (screen.height / 2) - 100; + const url = + chrome.extension.getURL('qr.html') + '?' + encodeURIComponent(msg); + window.open( + url, '_blank', + 'toolbar=no, location=no, status=no, menubar=no, scrollbars=yes, copyhistory=no, width=400, height=200, left=' + + left + ',top=' + top); +} diff --git a/src/models/dropbox.ts b/src/models/dropbox.ts new file mode 100644 index 000000000..2003b3c9c --- /dev/null +++ b/src/models/dropbox.ts @@ -0,0 +1,97 @@ +/* tslint:disable:no-reference */ +/// +/// +/// + +class Dropbox { + async getToken(code?: string) { + if (localStorage.dropboxToken) { + return localStorage.dropboxToken; + } + + if (!code) { + return ''; + } + + const url = 'https://api.dropboxapi.com/oauth2/token'; + return new Promise( + (resolve: (value: string) => void, reject: (reason: Error) => void) => { + try { + const xhr = new XMLHttpRequest(); + xhr.open('POST', url); + xhr.setRequestHeader( + 'Content-type', 'application/x-www-form-urlencoded'); + xhr.onreadystatechange = () => { + if (xhr.readyState === 4) { + const res: {[key: string]: string} = + JSON.parse(xhr.responseText); + localStorage.dropboxToken = res.access_token; + return resolve(res.access_token); + } + return; + }; + xhr.send( + `client_id=013qun2m82h9jim&client_secret=pk5tt1jrxuwq240&grant_type=authorization_code&code=${ + code}`); + } catch (error) { + return reject(error); + } + }); + } + + async upload(encryption: Encryption) { + const exportData = await EntryStorage.getExport(encryption); + for (const hash of Object.keys(exportData)) { + if (exportData[hash].encrypted) { + throw new Error('Error passphrase.'); + } + } + const backup = JSON.stringify(exportData, null, 2); + + const url = 'https://content.dropboxapi.com/2/files/upload'; + const token = await this.getToken(); + return new Promise( + (resolve: (value: boolean) => void, + reject: (reason: Error) => void) => { + if (!token) { + resolve(false); + } + try { + const xhr = new XMLHttpRequest(); + const now = + (new Date()).toISOString().slice(0, 10).replace(/-/g, ''); + const apiArg = { + path: `/${now}.json`, + mode: 'add', + autorename: true + }; + xhr.open('POST', url); + xhr.setRequestHeader('Authorization', 'Bearer ' + token); + xhr.setRequestHeader('Content-type', 'application/octet-stream'); + xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify(apiArg)); + xhr.onreadystatechange = () => { + if (xhr.readyState === 4) { + if (xhr.status === 401) { + localStorage.removeItem('dropboxToken'); + resolve(false); + } + try { + const res = JSON.parse(xhr.responseText); + if (res.name) { + resolve(true); + } else { + resolve(false); + } + } catch (error) { + reject(error); + } + } + return; + }; + xhr.send(backup); + } catch (error) { + return reject(error); + } + }); + } +} diff --git a/src/models/encryption.ts b/src/models/encryption.ts new file mode 100644 index 000000000..73a6f0d95 --- /dev/null +++ b/src/models/encryption.ts @@ -0,0 +1,39 @@ +/* tslint:disable:no-reference */ +/// + +class Encryption { + private password: string; + + constructor(password: string) { + this.password = password; + } + + getEncryptedSecret(secret: string): string { + if (!this.password) { + return secret; + } + return CryptoJS.AES.encrypt(secret, this.password).toString(); + } + + getDecryptedSecret(secret: string): string { + if (!this.password) { + return secret; + } + + try { + const decryptedSecret = CryptoJS.AES.decrypt(secret, this.password) + .toString(CryptoJS.enc.Utf8); + return decryptedSecret || 'Encrypted'; + } catch (error) { + return 'Encrypted'; + } + } + + getEncryptionStatus(): boolean { + return this.password ? true : false; + } + + updateEncryptionPassword(password: string) { + this.password = password; + } +} diff --git a/src/models/interface.ts b/src/models/interface.ts new file mode 100644 index 000000000..f108cbae9 --- /dev/null +++ b/src/models/interface.ts @@ -0,0 +1,56 @@ +/* tslint:disable:no-reference */ +/// + +enum OTPType { + totp = 1, + hotp, + battle, + steam, + hex +} + +interface OTP { + type: OTPType; + index: number; + issuer: string; + secret: string; + account: string; + hash: string; + counter: number; + code: string; + create(encryption: Encryption): Promise; + update(encryption: Encryption): Promise; + next(encryption: Encryption): Promise; + delete(): Promise; + generate(): void; +} + +interface OTPStorage { + account: string; + encrypted: boolean; + hash: string; + index: number; + issuer: string; + secret: string; + type: string; + counter: number; +} + +/* tslint:disable-next-line:interface-name */ +interface I18nMessage { + [key: string]: {message: string, description: string}; +} + +interface UIConfig { + el?: string; + data?: { + /* tslint:disable-next-line:no-any */ + [name: string]: any + }; + methods?: { + /* tslint:disable-next-line:no-any */ + [name: string]: (...arg: any[]) => any + }; + /* tslint:disable-next-line:no-any */ + ready?: (...arg: any[]) => any; +} diff --git a/src/models/key-utilities.ts b/src/models/key-utilities.ts new file mode 100644 index 000000000..9d66a3443 --- /dev/null +++ b/src/models/key-utilities.ts @@ -0,0 +1,135 @@ +// Originally based on the JavaScript implementation as provided by Russell +// Sayers on his Tin Isles blog: +// http://blog.tinisles.com/2011/10/google-authenticator-one-time-password-algorithm-in-javascript/ + +// Rewrite with TypeScript by Sneezry https://github.com/Sneezry + +/* tslint:disable:no-reference */ +/// +/// + +class KeyUtilities { + private static dec2hex(s: number): string { + return (s < 15.5 ? '0' : '') + Math.round(s).toString(16); + } + + private static hex2dec(s: string): number { + return Number(`0x${s}`); + } + + private static hex2str(hex: string) { + let str = ''; + for (let i = 0; i < hex.length; i += 2) { + str += String.fromCharCode(this.hex2dec(hex.substr(i, 2))); + } + return str; + } + + private static leftpad(str: string, len: number, pad: string): string { + if (len + 1 >= str.length) { + str = new Array(len + 1 - str.length).join(pad) + str; + } + return str; + } + + private static base32tohex(base32: string): string { + const base32chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + let bits = ''; + let hex = ''; + + for (let i = 0; i < base32.length; i++) { + const val = base32chars.indexOf(base32.charAt(i).toUpperCase()); + bits += this.leftpad(val.toString(2), 5, '0'); + } + + for (let i = 0; i + 4 <= bits.length; i += 4) { + const chunk = bits.substr(i, 4); + hex = hex + Number(`0b${chunk}`).toString(16); + } + + if (hex.length % 2 && hex[hex.length - 1] === '0') { + hex = hex.substr(0, hex.length - 1); + } + + return hex; + } + + private static base26(num: number) { + const chars = '23456789BCDFGHJKMNPQRTVWXY'; + let output = ''; + const len = 5; + for (let i = 0; i < len; i++) { + output += chars[num % chars.length]; + num = Math.floor(num / chars.length); + } + if (output.length < len) { + output = new Array(len - output.length + 1).join(chars[0]) + output; + } + return output; + } + + static generate(type: OTPType, secret: string, counter: number) { + secret = secret.replace(/\s/g, ''); + let len = 6; + let b26 = false; + let key: string; + switch (type) { + case OTPType.totp: + case OTPType.hotp: + key = this.base32tohex(secret); + break; + case OTPType.hex: + key = secret; + break; + case OTPType.battle: + key = this.base32tohex(secret); + len = 8; + break; + case OTPType.steam: + key = this.base32tohex(secret); + len = 10; + b26 = true; + break; + default: + key = this.base32tohex(secret); + } + + if (!key) { + throw new Error('Invalid secret key'); + } + + if (type !== OTPType.hotp) { + let epoch = Math.round(new Date().getTime() / 1000.0); + if (localStorage.offset) { + epoch = epoch + Number(localStorage.offset); + } + counter = Math.floor(epoch / 30); + } + + const time = this.leftpad(this.dec2hex(counter), 16, '0'); + + // external library for SHA functionality + const hmacObj = new jsSHA('SHA-1', 'HEX'); + hmacObj.setHMACKey(key, 'HEX'); + hmacObj.update(time); + const hmac = hmacObj.getHMAC('HEX'); + + let offset = 0; + if (hmac !== 'KEY MUST BE IN BYTE INCREMENTS') { + offset = this.hex2dec(hmac.substring(hmac.length - 1)); + } + + let otp = + (this.hex2dec(hmac.substr(offset * 2, 8)) & this.hex2dec('7fffffff')) + + ''; + + if (b26) { + return this.base26(Number(otp)); + } + + if (otp.length < len) { + otp = new Array(len - otp.length + 1).join('0') + otp; + } + return (otp).substr(otp.length - len, len).toString(); + } +} diff --git a/src/models/otp.ts b/src/models/otp.ts new file mode 100644 index 000000000..bb3ed3507 --- /dev/null +++ b/src/models/otp.ts @@ -0,0 +1,68 @@ +/* tslint:disable:no-reference */ +/// +/// +/// +/// + +class OTPEntry implements OTP { + type: OTPType; + index: number; + issuer: string; + secret: string; + account: string; + hash: string; + counter: number; + code = '••••••'; + + constructor( + type: OTPType, issuer: string, secret: string, account: string, + index: number, counter: number) { + this.type = type; + this.index = index; + this.issuer = issuer; + this.secret = secret; + this.account = account; + this.hash = CryptoJS.MD5(secret).toString(); + this.counter = counter; + if (this.type !== OTPType.hotp) { + this.generate(); + } + } + + async create(encryption: Encryption) { + await EntryStorage.add(encryption, this); + return; + } + + async update(encryption: Encryption) { + await EntryStorage.update(encryption, this); + return; + } + + async delete() { + await EntryStorage.delete(this); + return; + } + + async next(encryption: Encryption) { + if (this.type !== OTPType.hotp) { + return; + } + this.generate(); + this.counter++; + await this.update(encryption); + return; + } + + generate() { + if (this.secret === 'Encrypted') { + this.code = 'Encrypted'; + } else { + try { + this.code = KeyUtilities.generate(this.type, this.secret, this.counter); + } catch (error) { + this.code = 'Invalid'; + } + } + } +} diff --git a/src/models/storage.ts b/src/models/storage.ts new file mode 100644 index 000000000..3cb7d9c4a --- /dev/null +++ b/src/models/storage.ts @@ -0,0 +1,367 @@ +/* tslint:disable:no-reference */ +/// +/// +/// + +class EntryStorage { + private static getOTPStorageFromEntry( + encryption: Encryption, entry: OTPEntry): OTPStorage { + const storageItem: OTPStorage = { + account: entry.account, + hash: entry.hash, + index: entry.index, + issuer: entry.issuer, + type: OTPType[entry.type], + counter: entry.counter, + secret: encryption.getEncryptedSecret(entry.secret), + encrypted: encryption.getEncryptionStatus() + }; + return storageItem; + } + + private static ensureUniqueIndex(_data: {[hash: string]: OTPStorage}) { + const tempEntryArray: OTPStorage[] = []; + + for (const hash of Object.keys(_data)) { + if (!this.isValidEntry(_data, hash)) { + continue; + } + tempEntryArray.push(_data[hash]); + } + + tempEntryArray.sort((a, b) => { + return a.index - b.index; + }); + + const newData: {[hash: string]: OTPStorage} = {}; + for (let i = 0; i < tempEntryArray.length; i++) { + tempEntryArray[i].index = i; + newData[tempEntryArray[i].hash] = tempEntryArray[i]; + } + + return newData; + } + + private static isOTPStorage(entry: object) { + const properties = [ + 'account', 'hash', 'index', 'issuer', 'type', 'counter', 'secret', + 'encrypted' + ]; + for (let i = 0; i < properties.length; i++) { + if (!entry.hasOwnProperty(properties[i])) { + return false; + } + } + return true; + } + + private static isValidEntry( + _data: {[hash: string]: OTPStorage}, hash: string) { + if (typeof _data[hash] !== 'object') { + console.log('Key "' + hash + '" is not an object'); + return false; + } else { + if (!this.isOTPStorage(_data[hash])) { + console.log('Key "' + hash + '" is not OTPStorage'); + return false; + } + return true; + } + } + + static async hasEncryptedEntry() { + return new Promise( + (resolve: (value: boolean) => void, + reject: (reason: Error) => void) => { + chrome.storage.sync.get((_data: {[hash: string]: OTPStorage}) => { + for (const hash of Object.keys(_data)) { + if (!this.isValidEntry(_data, hash)) { + continue; + } + if (_data[hash].encrypted) { + return resolve(true); + } + } + return resolve(false); + }); + return; + }); + } + + static async getExport(encryption: Encryption) { + return new Promise( + (resolve: (value: {[hash: string]: OTPStorage}) => void, + reject: (reason: Error) => void) => { + try { + chrome.storage.sync.get((_data: {[hash: string]: OTPStorage}) => { + for (const hash of Object.keys(_data)) { + if (!this.isValidEntry(_data, hash)) { + delete _data[hash]; + continue; + } + // decrypt the data to export + if (_data[hash].encrypted) { + const decryptedSecret = + encryption.getDecryptedSecret(_data[hash].secret); + if (decryptedSecret !== _data[hash].secret && + decryptedSecret !== 'Encrypted') { + _data[hash].secret = decryptedSecret; + _data[hash].encrypted = false; + } + } + // we need correct hash + if (hash !== _data[hash].hash) { + _data[_data[hash].hash] = _data[hash]; + delete _data[hash]; + } + } + return resolve(_data); + }); + return; + } catch (error) { + return reject(error); + } + }); + } + + static async import( + encryption: Encryption, data: {[hash: string]: OTPStorage}) { + return new Promise( + (resolve: () => void, reject: (reason: Error) => void) => { + try { + chrome.storage.sync.get((_data: {[hash: string]: OTPStorage}) => { + for (const hash of Object.keys(data)) { + // never trust data import from user + // we do not support encrypted data import any longer + if (!data[hash].secret || data[hash].encrypted) { + // we need give a failed warning + continue; + } + + data[hash].hash = data[hash].hash || hash; + data[hash].account = data[hash].account || ''; + data[hash].encrypted = encryption.getEncryptionStatus(); + data[hash].index = data[hash].index || 0; + data[hash].issuer = data[hash].issuer || ''; + data[hash].type = data[hash].type || OTPType[OTPType.totp]; + data[hash].counter = data[hash].counter || 0; + + if (/^(blz\-|bliz\-)/.test(data[hash].secret)) { + const secretMatches = + data[hash].secret.match(/^(blz\-|bliz\-)(.*)/); + if (secretMatches && secretMatches.length >= 3) { + data[hash].secret = secretMatches[2]; + data[hash].type = OTPType[OTPType.battle]; + } + } + + if (/^stm\-/.test(data[hash].secret)) { + const secretMatches = data[hash].secret.match(/^stm\-(.*)/); + if (secretMatches && secretMatches.length >= 2) { + data[hash].secret = secretMatches[1]; + data[hash].type = OTPType[OTPType.steam]; + } + } + + const _hash = CryptoJS.MD5(data[hash].secret).toString(); + if (_hash !== hash) { + data[_hash] = data[hash]; + data[_hash].hash = _hash; + delete data[hash]; + } + + data[_hash].secret = + encryption.getEncryptedSecret(data[_hash].secret); + + _data[_hash] = data[_hash]; + } + _data = this.ensureUniqueIndex(_data); + chrome.storage.sync.set(_data, resolve); + }); + return; + } catch (error) { + return reject(error); + } + }); + } + + static async add(encryption: Encryption, entry: OTPEntry) { + return new Promise( + (resolve: () => void, reject: (reason: Error) => void) => { + try { + chrome.storage.sync.get((_data: {[hash: string]: OTPStorage}) => { + if (_data.hasOwnProperty(entry.hash)) { + throw new Error('The specific entry has already existed.'); + } + const storageItem = + this.getOTPStorageFromEntry(encryption, entry); + _data[entry.hash] = storageItem; + _data = this.ensureUniqueIndex(_data); + chrome.storage.sync.set(_data, resolve); + }); + return; + } catch (error) { + return reject(error); + } + }); + } + + static async update(encryption: Encryption, entry: OTPEntry) { + return new Promise( + (resolve: () => void, reject: (reason: Error) => void) => { + try { + chrome.storage.sync.get((_data: {[hash: string]: OTPStorage}) => { + if (!_data.hasOwnProperty(entry.hash)) { + throw new Error('The specific entry is not existing.'); + } + const storageItem = + this.getOTPStorageFromEntry(encryption, entry); + _data[entry.hash] = storageItem; + _data = this.ensureUniqueIndex(_data); + chrome.storage.sync.set(_data, resolve); + }); + return; + } catch (error) { + return reject(error); + } + }); + } + + static async set(encryption: Encryption, entries: OTPEntry[]) { + return new Promise( + (resolve: () => void, reject: (reason: Error) => void) => { + try { + chrome.storage.sync.get((_data: {[hash: string]: OTPStorage}) => { + entries.forEach(entry => { + const storageItem = + this.getOTPStorageFromEntry(encryption, entry); + _data[entry.hash] = storageItem; + }); + _data = this.ensureUniqueIndex(_data); + chrome.storage.sync.set(_data, resolve); + }); + return; + } catch (error) { + reject(error); + } + }); + } + + static async get(encryption: Encryption) { + return new Promise( + (resolve: (value: OTPEntry[]) => void, + reject: (reason: Error) => void) => { + try { + chrome.storage.sync.get((_data: {[hash: string]: OTPStorage}) => { + const data: OTPEntry[] = []; + for (let hash of Object.keys(_data)) { + if (!this.isValidEntry(_data, hash)) { + continue; + } + const entryData = _data[hash]; + let needMigrate = false; + + if (!entryData.type) { + entryData.type = OTPType[OTPType.totp]; + needMigrate = true; + } + + let type: OTPType; + switch (entryData.type) { + case 'totp': + case 'hotp': + case 'battle': + case 'steam': + type = OTPType[entryData.type]; + break; + default: + // we need correct the type here + // and save it + type = OTPType.totp; + entryData.type = OTPType[OTPType.totp]; + needMigrate = true; + } + entryData.secret = entryData.encrypted ? + encryption.getDecryptedSecret(entryData.secret) : + entryData.secret; + + const entry = new OTPEntry( + type, entryData.issuer, entryData.secret, entryData.account, + entryData.index, entryData.counter); + data.push(entry); + + // we need migrate secret in old format here + if (/^(blz\-|bliz\-)/.test(entryData.secret)) { + const secretMatches = + entryData.secret.match(/^(blz\-|bliz\-)(.*)/); + if (secretMatches && secretMatches.length >= 3) { + entryData.secret = entryData.encrypted ? + secretMatches[2] : + encryption.getEncryptedSecret(entry.secret); + entryData.type = OTPType[OTPType.battle]; + needMigrate = true; + } + } + + if (/^stm\-/.test(entryData.secret)) { + const secretMatches = entryData.secret.match(/^stm\-(.*)/); + if (secretMatches && secretMatches.length >= 2) { + entryData.secret = entryData.encrypted ? + secretMatches[2] : + encryption.getEncryptedSecret(entry.secret); + entryData.type = OTPType[OTPType.steam]; + needMigrate = true; + } + } + + // we need correct the hash + if (entry.secret !== 'Encrypted') { + const _hash = CryptoJS.MD5(entry.secret).toString(); + if (hash !== _hash) { + chrome.storage.sync.remove(hash); + hash = _hash; + entryData.hash = hash; + needMigrate = true; + } + } + + if (needMigrate) { + const _entry: {[hash: string]: OTPStorage} = {}; + _entry[hash] = entryData; + this.import(encryption, _entry); + } + } + + data.sort((a, b) => { + return a.index - b.index; + }); + return resolve(data); + }); + return; + } catch (error) { + return reject(error); + } + }); + } + + static async delete(entry: OTPEntry) { + return new Promise( + (resolve: () => void, reject: (reason: Error) => void) => { + try { + chrome.storage.sync.get((_data: {[hash: string]: OTPStorage}) => { + if (_data.hasOwnProperty(entry.hash)) { + delete _data[entry.hash]; + } + _data = this.ensureUniqueIndex(_data); + chrome.storage.sync.remove(entry.hash, () => { + chrome.storage.sync.set(_data, resolve); + }); + return; + }); + return; + } catch (error) { + return reject(error); + } + }); + } +} diff --git a/src/popup.ts b/src/popup.ts new file mode 100644 index 000000000..b17c2b04b --- /dev/null +++ b/src/popup.ts @@ -0,0 +1,98 @@ +/* tslint:disable:no-reference */ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +async function init() { + const ui = new UI({el: '#authenticator'}); + + await className(ui); + await i18n(ui); + await menu(ui); + await info(ui); + await passphrase(ui); + await entry(ui); + await qr(ui); + await message(ui); + await addAccount(ui); + + const authenticator = ui.generate(); + + if (authenticator.shouldShowPassphrase) { + authenticator.showInfo('passphrase'); + } + + // localStorage passphrase warning + if (localStorage.encodedPhrase) { + authenticator.alert(authenticator.i18n.local_passphrase_warning); + } + + // Remind backup + const backupReminder = setInterval(() => { + if (authenticator.entries.length === 0) { + return; + } + + for (let i = 0; i < authenticator.entries.length; i++) { + if (authenticator.entries[i].secret === 'Encrypted') { + return; + } + } + + clearInterval(backupReminder); + + const clientTime = Math.floor(new Date().getTime() / 1000 / 3600 / 24); + if (!localStorage.lastRemindingBackupTime) { + localStorage.lastRemindingBackupTime = clientTime; + } else if ( + clientTime - localStorage.lastRemindingBackupTime >= 30 || + clientTime - localStorage.lastRemindingBackupTime < 0) { + // backup to Dropbox + if (authenticator.dropboxToken) { + chrome.permissions.contains( + {origins: ['https://*.dropboxapi.com/*']}, + async (hasPermission) => { + if (hasPermission) { + try { + const dropbox = new Dropbox(); + const res = await dropbox.upload(authenticator.encryption); + if (res) { + // we have uploaded backup to Dropbox + // no need to remind + localStorage.lastRemindingBackupTime = clientTime; + return; + } + } catch (error) { + // ignore + } + } + authenticator.alert(authenticator.i18n.remind_backup); + localStorage.lastRemindingBackupTime = clientTime; + }); + } else { + authenticator.alert(authenticator.i18n.remind_backup); + localStorage.lastRemindingBackupTime = clientTime; + } + } + return; + }, 1000); + + return; +} + +chrome.permissions.contains( + {origins: ['https://www.google.com/']}, (hasPermission) => { + if (hasPermission) { + syncTimeWithGoogle(); + } + }); + +init(); diff --git a/src/ui/add-account.ts b/src/ui/add-account.ts new file mode 100644 index 000000000..9442406ae --- /dev/null +++ b/src/ui/add-account.ts @@ -0,0 +1,105 @@ +/* tslint:disable:no-reference */ +/// +/// + +async function insertContentScript() { + return new Promise((resolve: () => void, reject: (reason: Error) => void) => { + try { + return chrome.tabs.executeScript({file: '/build/content.js'}, () => { + chrome.tabs.insertCSS({file: '/css/content.css'}, resolve); + }); + } catch (error) { + return reject(error); + } + }); +} + +async function addAccount(_ui: UI) { + const ui: UIConfig = { + data: { + newAccount: {show: false, account: '', secret: '', type: OTPType.totp}, + newPassphrase: {phrase: '', confirm: ''} + }, + methods: { + addNewAccount: async () => { + let type: OTPType; + if (!/^[a-z2-7]+=*$/i.test(_ui.instance.newAccount.secret) && + /^[0-9a-f]+$/i.test(_ui.instance.newAccount.secret)) { + type = OTPType.hex; + } else { + type = _ui.instance.newAccount.type; + } + + const entry = new OTPEntry( + type, '', _ui.instance.newAccount.secret, + _ui.instance.newAccount.account, 0, 0); + await entry.create(_ui.instance.encryption); + await _ui.instance.updateEntries(); + _ui.instance.newAccount.type = OTPType.totp; + _ui.instance.account = ''; + _ui.instance.secret = ''; + _ui.instance.newAccount.show = false; + _ui.instance.closeInfo(); + _ui.instance.class.edit = false; + + const codes = document.getElementById('codes'); + if (codes) { + // wait vue apply changes to dom + setTimeout(() => { + codes.scrollTop = 0; + }, 0); + } + return; + }, + beginCapture: async () => { + await insertContentScript(); + + const entries = _ui.instance.entries as OTPEntry[]; + for (let i = 0; i < entries.length; i++) { + // we have encrypted entry + // the current passphrase is incorrect + // shouldn't add new account with + // the current passphrase + if (entries[i].code === 'Encrypted') { + _ui.instance.alert(_ui.instance.i18n.phrase_incorrect); + return; + } + } + + chrome.tabs.query({active: true, lastFocusedWindow: true}, (tabs) => { + const tab = tabs[0]; + if (!tab || !tab.id) { + return; + } + chrome.tabs.sendMessage( + tab.id, {action: 'capture', passphrase: _ui.instance.passphrase}, + (result) => { + if (result !== 'beginCapture') { + _ui.instance.alert(_ui.instance.i18n.capture_failed); + } else { + window.close(); + } + }); + }); + return; + }, + addAccountManually: () => { + const entries = _ui.instance.entries as OTPEntry[]; + for (let i = 0; i < entries.length; i++) { + // we have encrypted entry + // the current passphrase is incorrect + // shouldn't add new account with + // the current passphrase + if (entries[i].code === 'Encrypted') { + _ui.instance.alert(_ui.instance.i18n.phrase_incorrect); + return; + } + } + + _ui.instance.newAccount.show = true; + } + } + }; + + _ui.update(ui); +} diff --git a/src/ui/class.ts b/src/ui/class.ts new file mode 100644 index 000000000..41a38dd3a --- /dev/null +++ b/src/ui/class.ts @@ -0,0 +1,25 @@ +/* tslint:disable:no-reference */ +/// +/// + +async function className(_ui: UI) { + const ui: UIConfig = { + data: { + class: { + timeout: false, + edit: false, + slidein: false, + slideout: false, + fadein: false, + fadeout: false, + qrfadein: false, + qrfadeout: false, + notificationFadein: false, + notificationFadeout: false, + hotpDiabled: false + } + } + }; + + _ui.update(ui); +} diff --git a/src/ui/entry.ts b/src/ui/entry.ts new file mode 100644 index 000000000..bd2a695a0 --- /dev/null +++ b/src/ui/entry.ts @@ -0,0 +1,412 @@ +/* tslint:disable:no-reference */ +/// +/// +/// +/// +/// + +async function getEntries(encryption: Encryption) { + const optEntries: OTPEntry[] = await EntryStorage.get(encryption); + return optEntries; +} + +/* tslint:disable-next-line:no-any */ +async function updateCode(app: any) { + let second = new Date().getSeconds(); + if (localStorage.offset) { + second += Number(localStorage.offset) + 30; + } + second = second % 30; + app.sector = getSector(second); + if (second > 25) { + app.class.timeout = true; + } else { + app.class.timeout = false; + } + if (second < 1) { + const entries = app.entries as OTP[]; + for (let i = 0; i < entries.length; i++) { + if (entries[i].type !== OTPType.hotp) { + entries[i].generate(); + } + } + } +} + +function getSector(second: number) { + const canvas = document.createElement('canvas'); + canvas.width = 40; + canvas.height = 40; + const ctx = canvas.getContext('2d'); + if (!ctx) { + return; + } + ctx.fillStyle = '#888'; + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.arc( + 20, 20, 16, second / 30 * Math.PI * 2 - Math.PI / 2, Math.PI * 3 / 2, + false); + ctx.fill(); + const url = canvas.toDataURL(); + return `url(${url}) center / 20px 20px`; +} + +function getBackupFile(entryData: {[hash: string]: OTPStorage}) { + let json = JSON.stringify(entryData, null, 2); + // for windows notepad + json = json.replace(/\n/g, '\r\n'); + const base64Data = btoa(json); + return `data:application/octet-stream;base64,${base64Data}`; +} + +async function getSiteName() { + return new Promise( + (resolve: (value: Array) => void, + reject: (reason: Error) => void) => { + chrome.tabs.query({active: true, lastFocusedWindow: true}, (tabs) => { + const tab = tabs[0]; + if (!tab) { + return resolve([null, null]); + } + + const title = tab.title ? + tab.title.replace(/[^a-z0-9]/ig, '').toLowerCase() : + null; + + if (!tab.url) { + return resolve([title, null]); + } + + const urlParser = document.createElement('a'); + urlParser.href = tab.url; + const hostname = urlParser.hostname.toLowerCase(); + + // try to parse name from hostname + // i.e. hostname is www.example.com + // name should be example + let nameFromDomain = ''; + + // ip address + if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname)) { + nameFromDomain = hostname; + } + + // local network + if (hostname.indexOf('.') === -1) { + nameFromDomain = hostname; + } + + const hostLevelUnits = hostname.split('.'); + + if (hostLevelUnits.length === 2) { + nameFromDomain = hostLevelUnits[0]; + } + + // www.example.com + // example.com.cn + if (hostLevelUnits.length > 2) { + // example.com.cn + if (['com', 'net', 'org', 'edu', 'gov', 'co'].indexOf( + hostLevelUnits[hostLevelUnits.length - 2]) !== -1) { + nameFromDomain = hostLevelUnits[hostLevelUnits.length - 3]; + } else { // www.example.com + nameFromDomain = hostLevelUnits[hostLevelUnits.length - 2]; + } + } + + nameFromDomain = nameFromDomain.replace(/-/g, '').toLowerCase(); + + return resolve([title, nameFromDomain, hostname]); + }); + }); +} + +function hasMatchedEntry(siteName: Array, entries: OTPEntry[]) { + if (siteName.length < 2) { + return false; + } + + for (let i = 0; i < entries.length; i++) { + if (isMatchedEntry(siteName, entries[i])) { + return true; + } + } + return false; +} + +function isMatchedEntry(siteName: Array, entry: OTPEntry) { + const issuerHostMatches = entry.issuer.split('::'); + const issuer = issuerHostMatches[0].replace(/[^0-9a-z]/ig, '').toLowerCase(); + + if (!issuer) { + return false; + } + + const siteTitle = siteName[0] || ''; + const siteNameFromHost = siteName[1] || ''; + const siteHost = siteName[2] || ''; + + if (issuerHostMatches.length > 1) { + if (siteHost && siteHost.indexOf(issuerHostMatches[1]) !== -1) { + return true; + } + } + // site title should be more detailed + // so we use siteTitle.indexOf(issuer) + if (siteTitle && siteTitle.indexOf(issuer) !== -1) { + return true; + } + + if (siteNameFromHost && issuer.indexOf(siteNameFromHost) !== -1) { + return true; + } + + return false; +} + +async function getCachedPassphrase() { + return new Promise( + (resolve: (value: string) => void, reject: (reason: Error) => void) => { + const cookie = document.cookie; + const cookieMatch = + cookie ? document.cookie.match(/passphrase=([^;]*)/) : null; + const cachedPassphrase = + cookieMatch && cookieMatch.length > 1 ? cookieMatch[1] : null; + const cachedPassphraseLocalStorage = localStorage.encodedPhrase ? + CryptoJS.AES.decrypt(localStorage.encodedPhrase, '') + .toString(CryptoJS.enc.Utf8) : + ''; + if (cachedPassphrase || cachedPassphraseLocalStorage) { + return resolve(cachedPassphrase || cachedPassphraseLocalStorage); + } + + chrome.runtime.sendMessage( + {action: 'passphrase'}, (passphrase: string) => { + return resolve(passphrase); + }); + }); +} + +async function entry(_ui: UI) { + const cachedPassphrase = await getCachedPassphrase(); + const encryption: Encryption = new Encryption(cachedPassphrase); + let shouldShowPassphrase = + cachedPassphrase ? false : await EntryStorage.hasEncryptedEntry(); + const exportData = + shouldShowPassphrase ? {} : await EntryStorage.getExport(encryption); + const entries = shouldShowPassphrase ? [] : await getEntries(encryption); + + for (let i = 0; i < entries.length; i++) { + if (entries[i].code === 'Encrypted') { + shouldShowPassphrase = true; + break; + } + } + + const exportFile = getBackupFile(exportData); + const siteName = await getSiteName(); + const shouldFilter = hasMatchedEntry(siteName, entries); + + const ui: UIConfig = { + data: { + entries, + encryption, + OTPType, + shouldShowPassphrase, + exportData: JSON.stringify(exportData, null, 2), + exportFile, + sector: '', + notification: '', + notificationTimeout: 0, + filter: true, + shouldFilter, + importType: 'import_file', + importCode: '', + importEncrypted: false, + importPassphrase: '' + }, + methods: { + isMatchedEntry: (entry: OTPEntry) => { + return isMatchedEntry(siteName, entry); + }, + updateCode: async () => { + return await updateCode(_ui.instance); + }, + importBackupCode: async () => { + try { + const exportData: {[hash: string]: OTPStorage} = + JSON.parse(_ui.instance.importCode); + const passphrase = + _ui.instance.importEncrypted && _ui.instance.importPassphrase ? + _ui.instance.importPassphrase : + null; + const decryptedBackup: {[hash: string]: OTPStorage} = {}; + for (const hash of Object.keys(exportData)) { + if (typeof exportData[hash] !== 'object') { + continue; + } + if (!exportData[hash].secret) { + continue; + } + if (exportData[hash].encrypted && !passphrase) { + continue; + } + if (exportData[hash].encrypted) { + try { + exportData[hash].secret = + CryptoJS.AES.decrypt(exportData[hash].secret, passphrase) + .toString(CryptoJS.enc.Utf8); + exportData[hash].encrypted = false; + } catch (error) { + continue; + } + } + // exportData[hash].secret may be empty after decrypt with wrong + // passphrase + if (!exportData[hash].secret) { + continue; + } + decryptedBackup[hash] = exportData[hash]; + } + if (Object.keys(decryptedBackup).length) { + await EntryStorage.import(_ui.instance.encryption, decryptedBackup); + await _ui.instance.updateEntries(); + alert(_ui.instance.i18n.updateSuccess); + window.close(); + } else { + alert(_ui.instance.i18n.updateFailure); + } + return; + } catch (error) { + throw error; + } + }, + noCopy: (code: string) => { + return code === 'Encrypted' || code === 'Invalid' || + code.startsWith('•'); + }, + updateStorage: async () => { + await EntryStorage.set(_ui.instance.encryption, _ui.instance.entries); + return; + }, + showBulls: (code: string) => { + if (code.startsWith('•')) { + return code; + } + return new Array(code.length).fill('•').join(''); + }, + importEntries: async () => { + await EntryStorage.import( + _ui.instance.encryption, JSON.parse(_ui.instance.exportData)); + await _ui.instance.updateEntries(); + _ui.instance.alert(_ui.instance.i18n.updateSuccess); + return; + }, + updateEntries: async () => { + const exportData = + await EntryStorage.getExport(_ui.instance.encryption); + _ui.instance.exportData = JSON.stringify(exportData, null, 2); + _ui.instance.entries = await getEntries(_ui.instance.encryption); + _ui.instance.exportFile = getBackupFile(exportData); + await _ui.instance.updateCode(); + return; + }, + importFile: (event: Event, closeWindow: boolean) => { + const target = event.target as HTMLInputElement; + if (!target || !target.files) { + return; + } + if (target.files[0]) { + const reader = new FileReader(); + reader.onload = async () => { + const importData = JSON.parse(reader.result); + await EntryStorage.import(_ui.instance.encryption, importData); + await _ui.instance.updateEntries(); + _ui.instance.alert(_ui.instance.i18n.updateSuccess); + if (closeWindow) { + window.close(); + } + }; + reader.readAsText(target.files[0]); + } else { + _ui.instance.alert(_ui.instance.i18n.updateFailure); + if (closeWindow) { + window.alert(_ui.instance.i18n.updateFailure); + window.close(); + } + } + return; + }, + removeEntry: async (entry: OTPEntry) => { + if (await _ui.instance.confirm(_ui.instance.i18n.confirm_delete)) { + await entry.delete(); + await _ui.instance.updateEntries(); + } + return; + }, + editEntry: () => { + _ui.instance.class.edit = !_ui.instance.class.edit; + const codes = document.getElementById('codes'); + if (codes) { + // wait vue apply changes to dom + setTimeout(() => { + codes.scrollTop = _ui.instance.class.edit ? codes.scrollHeight : 0; + }, 0); + } + return; + }, + nextCode: async (entry: OTPEntry) => { + if (_ui.instance.class.hotpDiabled) { + return; + } + _ui.instance.class.hotpDiabled = true; + await entry.next(_ui.instance.encryption); + setTimeout(() => { + _ui.instance.class.hotpDiabled = false; + }, 3000); + return; + }, + copyCode: (entry: OTPEntry) => { + if (_ui.instance.class.edit || entry.code === 'Invalid' || + entry.code.startsWith('•')) { + return; + } + + if (entry.code === 'Encrypted') { + _ui.instance.showInfo('passphrase'); + return; + } + + chrome.permissions.request( + {permissions: ['clipboardWrite']}, (granted) => { + if (granted) { + const codeClipboard = document.getElementById( + 'codeClipboard') as HTMLInputElement; + if (!codeClipboard) { + return; + } + codeClipboard.value = entry.code; + codeClipboard.focus(); + codeClipboard.select(); + document.execCommand('Copy'); + _ui.instance.notification = _ui.instance.i18n.copied; + clearTimeout(_ui.instance.notificationTimeout); + _ui.instance.class.notificationFadein = true; + _ui.instance.class.notificationFadeout = false; + _ui.instance.notificationTimeout = setTimeout(() => { + _ui.instance.class.notificationFadein = false; + _ui.instance.class.notificationFadeout = true; + setTimeout(() => { + _ui.instance.class.notificationFadeout = false; + }, 200); + }, 1000); + } + }); + return; + }, + } + }; + + _ui.update(ui); +} diff --git a/src/ui/i18n.ts b/src/ui/i18n.ts new file mode 100644 index 000000000..86628c0ea --- /dev/null +++ b/src/ui/i18n.ts @@ -0,0 +1,38 @@ +/* tslint:disable:no-reference */ +/// +/// + +async function loadI18nMessages() { + return new Promise( + (resolve: (value: {[key: string]: string}) => void, + reject: (reason: Error) => void) => { + try { + const xhr = new XMLHttpRequest(); + xhr.overrideMimeType('application/json'); + xhr.onreadystatechange = () => { + if (xhr.readyState === 4) { + const i18nMessage: I18nMessage = JSON.parse(xhr.responseText); + const i18nData: {[key: string]: string} = {}; + for (const key of Object.keys(i18nMessage)) { + i18nData[key] = chrome.i18n.getMessage(key); + } + return resolve(i18nData); + } + return; + }; + xhr.open( + 'GET', chrome.extension.getURL('/_locales/en/messages.json')); + xhr.send(); + } catch (error) { + return reject(error); + } + }); +} + +async function i18n(_ui: UI) { + const i18n = await loadI18nMessages(); + + const ui: UIConfig = {data: {i18n}}; + + _ui.update(ui); +} diff --git a/src/ui/info.ts b/src/ui/info.ts new file mode 100644 index 000000000..9eab6d32b --- /dev/null +++ b/src/ui/info.ts @@ -0,0 +1,65 @@ +/* tslint:disable:no-reference */ +/// +/// + +async function info(_ui: UI) { + const ui: UIConfig = { + data: { + info: '', + dropboxCode: '', + dropboxToken: localStorage.dropboxToken || '' + }, + methods: { + saveDropboxCode: async () => { + const dropbox = new Dropbox(); + _ui.instance.dropboxToken = + await dropbox.getToken(_ui.instance.dropboxCode); + _ui.instance.closeInfo(); + return; + }, + showInfo: (tab: string) => { + if (tab === 'export' || tab === 'security') { + const entries = _ui.instance.entries as OTPEntry[]; + for (let i = 0; i < entries.length; i++) { + // we have encrypted entry + // the current passphrase is incorrect + // cannot export account data + // or change passphrase + if (entries[i].code === 'Encrypted') { + _ui.instance.alert(_ui.instance.i18n.phrase_incorrect); + return; + } + } + } else if (tab === 'dropbox') { + chrome.permissions.request( + {origins: ['https://*.dropboxapi.com/*']}, async (granted) => { + if (granted) { + _ui.instance.class.fadein = true; + _ui.instance.class.fadeout = false; + _ui.instance.info = tab; + } + return; + }); + return; + } + + _ui.instance.class.fadein = true; + _ui.instance.class.fadeout = false; + _ui.instance.info = tab; + return; + }, + closeInfo: () => { + _ui.instance.class.fadein = false; + _ui.instance.class.fadeout = true; + setTimeout(() => { + _ui.instance.class.fadeout = false; + _ui.instance.info = ''; + _ui.instance.newAccount.show = false; + }, 200); + return; + } + } + }; + + _ui.update(ui); +} diff --git a/src/ui/menu.ts b/src/ui/menu.ts new file mode 100644 index 000000000..8f444b95f --- /dev/null +++ b/src/ui/menu.ts @@ -0,0 +1,125 @@ +/* tslint:disable:no-reference */ +/// +/// + +function getVersion() { + return chrome.runtime.getManifest().version; +} + +async function syncTimeWithGoogle() { + return new Promise( + (resolve: (value: string) => void, reject: (reason: Error) => void) => { + try { + const xhr = new XMLHttpRequest(); + xhr.open('HEAD', 'https://www.google.com/generate_204'); + const xhrAbort = setTimeout(() => { + xhr.abort(); + return resolve('updateFailure'); + }, 5000); + xhr.onreadystatechange = () => { + if (xhr.readyState === 4) { + clearTimeout(xhrAbort); + const date = xhr.getResponseHeader('date'); + if (!date) { + return resolve('updateFailure'); + } + const serverTime = new Date(date).getTime(); + const clientTime = new Date().getTime(); + const offset = Math.round((serverTime - clientTime) / 1000); + + if (Math.abs(offset) <= 300) { // within 5 minutes + localStorage.offset = + Math.round((serverTime - clientTime) / 1000); + return resolve('updateSuccess'); + } else { + return resolve('clock_too_far_off'); + } + } + }; + xhr.send(); + } catch (error) { + return reject(error); + } + }); +} + +function resize(zoom: number) { + if (zoom !== 100) { + document.body.style.marginBottom = 480 * (zoom / 100 - 1) + 'px'; + document.body.style.marginRight = 320 * (zoom / 100 - 1) + 'px'; + document.body.style.transform = 'scale(' + (zoom / 100) + ')'; + } +} + +function openHelp() { + let url = + 'https://github.com/Authenticator-Extension/Authenticator/wiki/Chrome-Issues'; + + if (navigator.userAgent.indexOf('Chrome') !== -1) { + url = + 'https://github.com/Authenticator-Extension/Authenticator/wiki/Chrome-Issues'; + } else if (navigator.userAgent.indexOf('Firefox') !== -1) { + url = + 'https://github.com/Authenticator-Extension/Authenticator/wiki/Firefox-Issues'; + } + + window.open(url, '_blank'); +} + +async function menu(_ui: UI) { + const version = getVersion(); + const zoom = Number(localStorage.zoom) || 100; + resize(zoom); + + const ui: UIConfig = { + data: {version, zoom}, + methods: { + openLink: (url: string) => { + window.open(url, '_blank'); + return; + }, + showMenu: () => { + _ui.instance.class.slidein = true; + _ui.instance.class.slideout = false; + return; + }, + closeMenu: () => { + _ui.instance.class.slidein = false; + _ui.instance.class.slideout = true; + setTimeout(() => { + _ui.instance.class.slideout = false; + }, 200); + return; + }, + openHelp: () => { + openHelp(); + return; + }, + isChrome: () => { + if (navigator.userAgent.indexOf('Chrome') !== -1) { + return true; + } else { + return false; + } + }, + saveZoom: () => { + localStorage.zoom = _ui.instance.zoom; + resize(_ui.instance.zoom); + return; + }, + syncClock: async () => { + chrome.permissions.request( + {origins: ['https://www.google.com/']}, async (granted) => { + if (granted) { + const message = await syncTimeWithGoogle(); + _ui.instance.alert(_ui.instance.i18n[message]); + } + return; + }); + return; + } + } + }; + + _ui.update(ui); +} diff --git a/src/ui/message.ts b/src/ui/message.ts new file mode 100644 index 000000000..330870b3e --- /dev/null +++ b/src/ui/message.ts @@ -0,0 +1,52 @@ +/* tslint:disable:no-reference */ +/// +/// + +function isCustomEvent(event: Event): event is CustomEvent { + return 'detail' in event; +} + +async function message(_ui: UI) { + const ui: UIConfig = { + data: {message: [], messageIdle: true, confirmMessage: ''}, + methods: { + alert: (message: string) => { + _ui.instance.message.unshift(message); + }, + closeAlert: () => { + _ui.instance.messageIdle = false; + _ui.instance.message.shift(); + setTimeout(() => { + _ui.instance.messageIdle = true; + }, 200); + }, + confirm: async (message: string) => { + return new Promise( + (resolve: (value: boolean) => void, + reject: (reason: Error) => void) => { + _ui.instance.confirmMessage = message; + window.addEventListener('confirm', (event) => { + _ui.instance.confirmMessage = ''; + if (!isCustomEvent(event)) { + return resolve(false); + } + return resolve(event.detail); + }); + return; + }); + }, + confirmOK: () => { + const confirmEvent = new CustomEvent('confirm', {detail: true}); + window.dispatchEvent(confirmEvent); + return; + }, + confirmCancel: () => { + const confirmEvent = new CustomEvent('confirm', {detail: false}); + window.dispatchEvent(confirmEvent); + return; + } + } + }; + + _ui.update(ui); +} diff --git a/src/ui/passphrase.ts b/src/ui/passphrase.ts new file mode 100644 index 000000000..1d2cf1dfc --- /dev/null +++ b/src/ui/passphrase.ts @@ -0,0 +1,40 @@ +/* tslint:disable:no-reference */ +/// +/// + +function cachePassword(password: string) { + document.cookie = 'passphrase=' + password; + chrome.runtime.sendMessage({action: 'cachePassphrase', value: password}); +} + +async function passphrase(_ui: UI) { + const ui: UIConfig = { + data: {passphrase: ''}, + methods: { + applyPassphrase: async () => { + _ui.instance.encryption.updateEncryptionPassword( + _ui.instance.passphrase); + await _ui.instance.updateEntries(); + _ui.instance.closeInfo(); + cachePassword(_ui.instance.passphrase); + return; + }, + changePassphrase: async () => { + if (_ui.instance.newPassphrase.phrase !== + _ui.instance.newPassphrase.confirm) { + _ui.instance.alert(_ui.instance.i18n.phrase_not_match); + return; + } + _ui.instance.encryption.updateEncryptionPassword( + _ui.instance.newPassphrase.phrase); + cachePassword(_ui.instance.newPassphrase.phrase); + await _ui.instance.importEntries(); + // remove cached passphrase in old version + localStorage.removeItem('encodedPhrase'); + return; + } + } + }; + + _ui.update(ui); +} diff --git a/src/ui/qr.ts b/src/ui/qr.ts new file mode 100644 index 000000000..ff7542320 --- /dev/null +++ b/src/ui/qr.ts @@ -0,0 +1,62 @@ +/* tslint:disable:no-reference */ +/// +/// + +/* tslint:disable-next-line:no-any */ +declare var QRCode: any; + +async function getQrUrl(entry: OTPEntry) { + return new Promise( + (resolve: (value: string) => void, reject: (reason: Error) => void) => { + const label = + entry.issuer ? (entry.issuer + ':' + entry.account) : entry.account; + const type = entry.type === OTPType.hex ? OTPType[OTPType.totp] : + OTPType[entry.type]; + const otpauth = 'otpauth://' + type + '/' + label + + '?secret=' + entry.secret + + (entry.issuer ? ('&issuer=' + entry.issuer.split('::')[0]) : '') + + ((entry.type === OTPType.hotp) ? ('&counter=' + entry.counter) : + ''); + /* tslint:disable-next-line:no-unused-expression */ + new QRCode( + 'qr', { + text: otpauth, + width: 128, + height: 128, + colorDark: '#000000', + colorLight: '#ffffff', + correctLevel: QRCode.CorrectLevel.L + }, + resolve); + return; + }); +} + +async function qr(_ui: UI) { + const ui: UIConfig = { + data: {qr: ''}, + methods: { + shouldShowQrIcon: (entry: OTPEntry) => { + return entry.secret !== 'Encrypted' && entry.type !== OTPType.battle && + entry.type !== OTPType.steam; + }, + showQr: async (entry: OTPEntry) => { + const qrUrl = await getQrUrl(entry); + _ui.instance.qr = `url(${qrUrl})`; + _ui.instance.class.qrfadein = true; + _ui.instance.class.qrfadeout = false; + return; + }, + hideQr: () => { + _ui.instance.class.qrfadein = false; + _ui.instance.class.qrfadeout = true; + setTimeout(() => { + _ui.instance.class.qrfadeout = false; + }, 200); + return; + } + } + }; + + _ui.update(ui); +} diff --git a/src/ui/ui.ts b/src/ui/ui.ts new file mode 100644 index 000000000..9d45a5e0d --- /dev/null +++ b/src/ui/ui.ts @@ -0,0 +1,68 @@ +/* tslint:disable:no-reference */ +/// + +// need to find a better way to handle Vue types without modules +// we use vue 1.0 here to solve csp issues +/* tslint:disable-next-line:no-any */ +declare var Vue: any; + +/* tslint:disable-next-line:no-any */ +declare var vueDragula: any; + +class UI { + private ui: UIConfig; + // Vue instance + /* tslint:disable-next-line:no-any */ + instance: any; + + constructor(ui: UIConfig) { + this.ui = ui; + } + + update(ui: UIConfig) { + if (ui.data) { + this.ui.data = this.ui.data || {}; + for (const key of Object.keys(ui.data)) { + this.ui.data[key] = ui.data[key]; + } + } + + if (ui.methods) { + this.ui.methods = this.ui.methods || {}; + for (const key of Object.keys(ui.methods)) { + this.ui.methods[key] = ui.methods[key]; + } + } + } + + generate() { + Vue.use(vueDragula); + this.ui.ready = () => { + Vue.vueDragula.eventBus.$on('drop', async () => { + // wait for this.instance.entries sync from dom + setTimeout(async () => { + let needUpdate = false; + for (let i = 0; i < this.instance.entries.length; i++) { + const entry: OTPEntry = this.instance.entries[i]; + if (entry.index !== i) { + needUpdate = true; + entry.index = i; + } + } + + if (needUpdate) { + await this.instance.updateStorage(); + } + return; + }, 0); + return; + }); + }; + this.instance = new Vue(this.ui); + this.instance.updateCode(); + setInterval(async () => { + await this.instance.updateCode(); + }, 1000); + return this.instance; + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 000000000..dd0840a2f --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "./node_modules/gts/tsconfig-google.json", + "compilerOptions": { + "lib": ["es6", "dom"], + "target": "es6", + "strict": true, + "rootDir": "src", + "outDir": "build" + }, + "include": [ + "src/*.ts", + "src/**/*.ts", + "test/*.ts", + "test/**/*.ts" + ], + "exclude": [ + "node_modules" + ] +}