@@ -3,6 +3,7 @@ package com.habr.codeconverter
33import java.awt.Toolkit
44import java.awt.datatransfer.DataFlavor
55import java.awt.datatransfer.StringSelection
6+ import java.awt.datatransfer.UnsupportedFlavorException
67import java.io.InputStream
78
89val HTML_FLAVOR = DataFlavor (" text/html" , " Rich Formatted Text" )
@@ -13,22 +14,56 @@ val color = Regex("[\";]color:#(.*?)[\";]")
1314val styleItalic = Regex (" (font-style:italic)" )
1415val styleBold = Regex (" (font-weight:bold)" )
1516
16- fun main () {
17- val cb = Toolkit .getDefaultToolkit().systemClipboard
18- val source = (cb.getData(HTML_FLAVOR ) as InputStream ).reader().readText()
19- println (source)
20- StringSelection (
21- " <code>" +
22- source.substring(pre)!!
23- .replace(span) {
24- it.groups[2 ]!! .value.styledWith(it.groups[1 ]!! .value)
25- }
26- .replace(" <br>" , " \n " )
27- .replace("  " , " " )
28- + " </code>"
29- ).let { cb.setContents(it, it) }
17+ val clipboard = Toolkit .getDefaultToolkit().systemClipboard!!
18+ val clipboardHtml
19+ get() =
20+ try {
21+ clipboard.getData(HTML_FLAVOR )
22+ } catch (e: UnsupportedFlavorException ) {
23+ null
24+ }
25+ ?.let { it as ? InputStream }
26+ ?.reader()
27+ ?.readText()
28+
29+ fun main (vararg args : String ) =
30+ if (args.isNotEmpty()) {
31+ println (" Running as daemon" )
32+ clipboard.addFlavorListener {
33+ convertClipboard()
34+ }.also {
35+ Thread .currentThread().suspend ()
36+ }
37+ } else
38+ convertClipboard()
39+
40+ private fun convertClipboard () {
41+ clipboardHtml
42+ ?.also {
43+ // debug only
44+ println (" Source clipboard data as html:\n $it " )
45+ }
46+ ?.convertCode()
47+ ?.putIntoClipboard()
3048}
3149
50+ private fun String.convertCode () =
51+ substring(pre)
52+ ?.replace(span) { span -> span.groups[2 ]!! .value.styledWith(span.groups[1 ]!! .value) }
53+ ?.replaceTags()
54+ ?.wrapWithCode()
55+
56+ private fun String.putIntoClipboard () =
57+ StringSelection (this )
58+ .let { clipboard.setContents(it, it) }
59+
60+ private fun String.wrapWithCode () =
61+ " <code>$this </code>"
62+
63+ private fun String.replaceTags () =
64+ replace(" <br>" , " \n " )
65+ .replace("  " , " " )
66+
3267private fun String.styledWith (style : String ) =
3368 styledWith(
3469 style.substring(color),
0 commit comments