<commit_before>//
//  FolioReaderWebView.swift
//  FolioReaderKit
//
//  Created by <NAME> on 21.09.16.
//  Copyright (c) 2016 Folio Reader. All rights reserved.
//

import UIKit

open class FolioReaderWebView: UIWebView {

	var isColors = false
	var isShare = false
    var isOneWord = false

	// MARK: - UIMenuController

	open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
		guard readerConfig != nil && readerConfig.useReaderMenuController == true else {
			return super.canPerformAction(action, withSender: sender)
		}
        
		if isShare {
			return false
		} else if isColors {
			return false
		} else {
			if action == #selector(highlight(_:))
				|| (action == #selector(define(_:)) && isOneWord)
                || (action == #selector(play(_:)) && (book.hasAudio() || readerConfig.enableTTS))
				|| (action == #selector(share(_:)) && readerConfig.allowSharing)
				|| (action == #selector(copy(_:)) && readerConfig.allowSharing) {
				return true
			}
			return false
		}
	}

	// MARK: - UIMenuController - Actions

	func share(_ sender: UIMenuController) {
		let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

		let shareImage = UIAlertAction(title: readerConfig.localizedShareImageQuote, style: .default, handler: { (action) -> Void in
			if self.isShare {
				if let textToShare = self.js("getHighlightContent()") {
					FolioReader.shared.readerCenter?.presentQuoteShare(textToShare)
				}
			} else {
				if let textToShare = self.js("getSelectedText()") {
					FolioReader.shared.readerCenter?.presentQuoteShare(textToShare)
					self.isUserInteractionEnabled = false
					self.isUserInteractionEnabled = true
				}
			}
			self.setMenuVisible(false)
		})

		let shareText = UIAlertAction(title: readerConfig.localizedShareTextQuote, style: .default) { (action) -> Void in
			if self.isShare {
				if let textToShare = self.js("getHighlightContent()") {
					FolioReader.shared.readerCenter?.shareHighlight(textToShare, rect: sender.menuFrame)
				}
			} else {
				if let textToShare = self.js("getSelectedText()") {
					FolioReader.shared.readerCenter?.shareHighlight(textToShare, rect: sender.menuFrame)
				}
			}
			self.setMenuVisible(false)
		}

		let cancel = UIAlertAction(title: readerConfig.localizedCancel, style: .cancel, handler: nil)

		alertController.addAction(shareImage)
		alertController.addAction(shareText)
		alertController.addAction(cancel)

        if let alert = alertController.popoverPresentationController {
            alert.sourceView = FolioReader.shared.readerCenter?.currentPage
            alert.sourceRect = sender.menuFrame
        }
        
		FolioReader.shared.readerCenter?.present(alertController, animated: true, completion: nil)
	}

	func colors(_ sender: UIMenuController?) {
		isColors = true
		createMenu(options: false)
		setMenuVisible(true)
	}

	func remove(_ sender: UIMenuController?) {
		if let removedId = js("removeThisHighlight()") {
			Highlight.removeById(removedId)
		}
		setMenuVisible(false)
	}

	func highlight(_ sender: UIMenuController?) {
		let highlightAndReturn = js("highlightString('\(HighlightStyle.classForStyle(FolioReader.currentHighlightStyle))')")
		let jsonData = highlightAndReturn?.data(using: String.Encoding.utf8)

		do {
			let json = try JSONSerialization.jsonObject(with: jsonData!, options: []) as! NSArray
			let dic = json.firstObject as! [String: String]
			let rect = CGRectFromString(dic["rect"]!)
			let startOffset = dic["startOffset"]!
			let endOffset = dic["endOffset"]!

			// Force remove text selection
			isUserInteractionEnabled = false
			isUserInteractionEnabled = true

			createMenu(options: true)
			setMenuVisible(true, andRect: rect)

			// Persist
			let html = js("getHTML()")
			if let highlight = Highlight.matchHighlight(html, andId: dic["id"]!, startOffset: startOffset, endOffset: endOffset) {
				highlight.persist()
			}
		} catch {
			print("Could not receive JSON")
		}
	}

	func define(_ sender: UIMenuController?) {
		let selectedText = js("getSelectedText()")

		setMenuVisible(false)
		isUserInteractionEnabled = false
		isUserInteractionEnabled = true

		let vc = UIReferenceLibraryViewController(term: selectedText! )
		vc.view.tintColor = readerConfig.tintColor
		FolioReader.shared.readerContainer.show(vc, sender: nil)
	}

	func play(_ sender: UIMenuController?) {
		FolioReader.shared.readerAudioPlayer?.play()
<commit_msg>Fix incorrect menu on second highlight attempt (#177)<commit_after>//
//  FolioReaderWebView.swift
//  FolioReaderKit
//
//  Created by <NAME> on 21.09.16.
//  Copyright (c) 2016 Folio Reader. All rights reserved.
//

import UIKit

open class FolioReaderWebView: UIWebView {

	var isColors = false
	var isShare = false
    var isOneWord = false

	// MARK: - UIMenuController

	open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
		guard readerConfig != nil && readerConfig.useReaderMenuController == true else {
			return super.canPerformAction(action, withSender: sender)
		}
        
		if isShare {
			return false
		} else if isColors {
			return false
		} else {
			if action == #selector(highlight(_:))
				|| (action == #selector(define(_:)) && isOneWord)
                || (action == #selector(play(_:)) && (book.hasAudio() || readerConfig.enableTTS))
				|| (action == #selector(share(_:)) && readerConfig.allowSharing)
				|| (action == #selector(copy(_:)) && readerConfig.allowSharing) {
				return true
			}
			return false
		}
	}

	// MARK: - UIMenuController - Actions

	func share(_ sender: UIMenuController) {
		let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

		let shareImage = UIAlertAction(title: readerConfig.localizedShareImageQuote, style: .default, handler: { (action) -> Void in
			if self.isShare {
				if let textToShare = self.js("getHighlightContent()") {
					FolioReader.shared.readerCenter?.presentQuoteShare(textToShare)
				}
			} else {
				if let textToShare = self.js("getSelectedText()") {
					FolioReader.shared.readerCenter?.presentQuoteShare(textToShare)
					self.isUserInteractionEnabled = false
					self.isUserInteractionEnabled = true
				}
			}
			self.setMenuVisible(false)
		})

		let shareText = UIAlertAction(title: readerConfig.localizedShareTextQuote, style: .default) { (action) -> Void in
			if self.isShare {
				if let textToShare = self.js("getHighlightContent()") {
					FolioReader.shared.readerCenter?.shareHighlight(textToShare, rect: sender.menuFrame)
				}
			} else {
				if let textToShare = self.js("getSelectedText()") {
					FolioReader.shared.readerCenter?.shareHighlight(textToShare, rect: sender.menuFrame)
				}
			}
			self.setMenuVisible(false)
		}

		let cancel = UIAlertAction(title: readerConfig.localizedCancel, style: .cancel, handler: nil)

		alertController.addAction(shareImage)
		alertController.addAction(shareText)
		alertController.addAction(cancel)

        if let alert = alertController.popoverPresentationController {
            alert.sourceView = FolioReader.shared.readerCenter?.currentPage
            alert.sourceRect = sender.menuFrame
        }
        
		FolioReader.shared.readerCenter?.present(alertController, animated: true, completion: nil)
	}

	func colors(_ sender: UIMenuController?) {
		isColors = true
		createMenu(options: false)
		setMenuVisible(true)
	}

	func remove(_ sender: UIMenuController?) {
		if let removedId = js("removeThisHighlight()") {
			Highlight.removeById(removedId)
		}
		setMenuVisible(false)
	}

	func highlight(_ sender: UIMenuController?) {
		let highlightAndReturn = js("highlightString('\(HighlightStyle.classForStyle(FolioReader.currentHighlightStyle))')")
		let jsonData = highlightAndReturn?.data(using: String.Encoding.utf8)

		do {
			let json = try JSONSerialization.jsonObject(with: jsonData!, options: []) as! NSArray
			let dic = json.firstObject as! [String: String]
			let rect = CGRectFromString(dic["rect"]!)
			let startOffset = dic["startOffset"]!
			let endOffset = dic["endOffset"]!

			// Force remove text selection
			isUserInteractionEnabled = false
			isUserInteractionEnabled = true

			createMenu(options: false)
			setMenuVisible(true, andRect: rect)

			// Persist
			let html = js("getHTML()")
			if let highlight = Highlight.matchHighlight(html, andId: dic["id"]!, startOffset: startOffset, endOffset: endOffset) {
				highlight.persist()
			}
		} catch {
			print("Could not receive JSON")
		}
	}

	func define(_ sender: UIMenuController?) {
		let selectedText = js("getSelectedText()")

		setMenuVisible(false)
		isUserInteractionEnabled = false
		isUserInteractionEnabled = true

		let vc = UIReferenceLibraryViewController(term: selectedText! )
		vc.view.tintColor = readerConfig.tintColor
		FolioReader.shared.readerContainer.show(vc, sender: nil)
	}

	func play(_ sender: UIMenuController?) {
		FolioReader.shared.readerAudioPlayer?.play()

{'fraction_non_alphanumeric': 0.11510550407502512, 'fraction_numerical': 0.002791113095902646, 'mean_word_length': 4.061016949152543, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2466200', 'n_tokens_mistral': 3121, 'n_tokens_neox': 2696, 'n_words': 587}