aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--bbcode/LICENSE27
-rw-r--r--bbcode/Setup.hs2
-rw-r--r--bbcode/bbcode.cabal33
-rw-r--r--bbcode/bbcode.nix18
-rw-r--r--bbcode/src/BBCode.hs96
-rw-r--r--bbcode/src/BBCode/Syntax.hs108
-rw-r--r--bbcode/src/BBCode/Tokenizer.hs44
-rw-r--r--default.nix8
-rw-r--r--default.result.do20
-rw-r--r--servant/api/Thermoprint/Api.hs28
-rw-r--r--servant/servant.cabal31
-rw-r--r--servant/servant.nix5
-rw-r--r--servant/src/Main.hs71
-rw-r--r--thermoprint/src/Thermoprint.hs121
-rw-r--r--thermoprint/thermoprint.cabal54
-rw-r--r--thermoprint/thermoprint.nix5
-rw-r--r--tprint/LICENSE27
-rw-r--r--tprint/Setup.hs2
-rw-r--r--tprint/src/Main.hs77
-rw-r--r--tprint/tprint.cabal31
-rw-r--r--tprint/tprint.nix20
21 files changed, 767 insertions, 61 deletions
diff --git a/bbcode/LICENSE b/bbcode/LICENSE
new file mode 100644
index 0000000..4ad71e2
--- /dev/null
+++ b/bbcode/LICENSE
@@ -0,0 +1,27 @@
1Statement of Purpose
2
3The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
4
5Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
6
7For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
8
91. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
10
11the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
12moral rights retained by the original author(s) and/or performer(s);
13publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
14rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
15rights protecting the extraction, dissemination, use and reuse of data in a Work;
16database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
17other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
182. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
19
203. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
21
224. Limitations and Disclaimers.
23
24No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
25Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
26Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
27Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. \ No newline at end of file
diff --git a/bbcode/Setup.hs b/bbcode/Setup.hs
new file mode 100644
index 0000000..9a994af
--- /dev/null
+++ b/bbcode/Setup.hs
@@ -0,0 +1,2 @@
1import Distribution.Simple
2main = defaultMain
diff --git a/bbcode/bbcode.cabal b/bbcode/bbcode.cabal
new file mode 100644
index 0000000..b17ff34
--- /dev/null
+++ b/bbcode/bbcode.cabal
@@ -0,0 +1,33 @@
1-- Initial bbcode.cabal generated by cabal init. For further
2-- documentation, see http://haskell.org/cabal/users-guide/
3
4name: bbcode
5version: 0.0.0
6synopsis: A tiny parser for bbcode->thermoprint-syntax-tree conversion
7-- description:
8homepage: git://git.yggdrasil.li/thermoprint
9license: PublicDomain
10license-file: LICENSE
11author: Gregor Kleen
12maintainer: aethoago@141.li
13-- copyright:
14-- category:
15build-type: Simple
16-- extra-source-files:
17cabal-version: >=1.10
18
19library
20 exposed-modules: BBCode
21 other-modules: BBCode.Tokenizer
22 , BBCode.Syntax
23 -- other-extensions:
24 hs-source-dirs: src
25 default-language: Haskell2010
26 build-depends: base >=4.8 && <4.9
27 , thermoprint
28 , attoparsec >=0.13.0 && <1
29 , text >=1.2.1 && <2
30 , parsec >=3.1.9 && <4
31 , mtl >=2.2.1 && <3
32 , case-insensitive >=1.2.0 && <2
33 , containers >=0.5.6 && <1 \ No newline at end of file
diff --git a/bbcode/bbcode.nix b/bbcode/bbcode.nix
new file mode 100644
index 0000000..d363a17
--- /dev/null
+++ b/bbcode/bbcode.nix
@@ -0,0 +1,18 @@
1{ mkDerivation
2, stdenv
3, base
4, thermoprint
5, attoparsec, parsec, mtl, case-insensitive, containers
6}:
7mkDerivation {
8 pname = "bbcode";
9 version = "0.0.0";
10 src = ./.;
11 libraryHaskellDepends = [ base
12 thermoprint
13 attoparsec parsec mtl case-insensitive containers
14 ];
15 homepage = "git://git.yggdrasil.li/thermoprint";
16 description = "A tiny parser for bbcode->thermoprint-syntax-tree conversion";
17 license = stdenv.lib.licenses.publicDomain;
18}
diff --git a/bbcode/src/BBCode.hs b/bbcode/src/BBCode.hs
new file mode 100644
index 0000000..750fb0f
--- /dev/null
+++ b/bbcode/src/BBCode.hs
@@ -0,0 +1,96 @@
1{-# LANGUAGE OverloadedStrings, OverloadedLists, RankNTypes, ImpredicativeTypes #-}
2
3module BBCode
4 ( parse
5 ) where
6
7import Thermoprint
8
9import BBCode.Tokenizer
10import BBCode.Syntax
11
12import Data.Maybe
13import Data.Monoid
14import Data.Either
15import Data.Bifunctor
16import Data.List
17import Data.Ord
18import Data.Foldable
19
20import Data.Function (on)
21
22import Data.CaseInsensitive ( CI )
23import qualified Data.CaseInsensitive as CI
24
25import Data.Map ( Map )
26import qualified Data.Map as Map
27
28import Prelude hiding (takeWhile)
29
30import Debug.Trace
31
32knownTags :: Map (CI String) (Either (Block String -> Block String) (Inline String -> Inline String))
33knownTags = [ ("center", Left Center)
34 , ("u", Right Underline)
35 ]
36
37isBlock, isInline :: String -> Bool
38isBlock = testTag isLeft
39isInline = testTag isRight
40testTag f k = fromMaybe False (f <$> Map.lookup (CI.mk k) knownTags)
41
42data Decorated c = Decorated c [String]
43 deriving (Show, Eq)
44
45parse :: String -> Either String (Block String)
46parse input = (remerge . blockify <$> (tokenize input >>= treeify)) >>= semantics
47
48blockify :: ContentForest -> [Decorated String]
49blockify = map sortDeco . concat . map (blockify' [])
50 where
51 blockify' _ Empty = []
52 blockify' initial (Content str) = [str `Decorated` initial]
53 blockify' initial (Tagged cs tag) = concat $ map (blockify' $ tag : initial) cs
54 sortDeco :: Decorated c -> Decorated c
55 sortDeco (Decorated c tags) = Decorated c $ (nubBy ((==) `on` CI.mk) . sortBy blockiness) tags
56 blockiness :: String -> String -> Ordering
57 blockiness a b = comparing isBlock a b <> comparing CI.mk a b -- sort also alphabetically for the benefit of remerge
58
59remerge :: [Decorated String] -> ContentForest
60remerge [] = []
61remerge [(Decorated c deco)] = [appEndo applyDeco $ Content c]
62 where
63 applyDeco = foldMap (\t -> Endo (\c -> Tagged [c] t)) $ reverse deco
64remerge xs = concat $ map toTree $ groupLasts xs
65 where
66 groupLasts = groupBy ((==) `on` (listToMaybe . reverse . (\(Decorated _ ds) -> ds)))
67 -- toTree :: [Decorated String] -> [ContentTree]
68 toTree [] = []
69 toTree (x@(Decorated _ []):xs) = map (Content . (\(Decorated c []) -> c)) (x:xs)
70 toTree (x@(Decorated _ ds):xs) = [Tagged content tag]
71 where
72 tag = last ds
73 content = toTree $ map stripLast (x:xs)
74 stripLast (Decorated c ds) = Decorated c (init ds)
75
76unknownTag :: forall a. String -> Either String a
77unknownTag tag = Left $ "Unknown tag: " ++ tag
78
79semantics :: ContentForest -> Either String (Block String)
80semantics forest = Over <$> mapM semantics' forest
81
82semantics' :: ContentTree -> Either String (Block String)
83semantics' Empty = Right $ Over []
84semantics' (Content str) = Right $ Paragraph (Cooked str)
85semantics' (Tagged cs tag) = case Map.lookup (CI.mk tag) knownTags of
86 Nothing -> unknownTag tag
87 Just (Left f) -> Over . map f <$> mapM semantics' cs
88 Just (Right f) -> Paragraph . Beside . map f<$> mapM iSemantics cs
89
90iSemantics :: ContentTree -> Either String (Inline String)
91iSemantics Empty = Right $ Beside []
92iSemantics (Content str) = Right $ Cooked str
93iSemantics (Tagged cs tag) = case Map.lookup (CI.mk tag) knownTags of
94 Nothing -> unknownTag tag
95 Just (Left f) -> error "Known inline tag sorted within block"
96 Just (Right f) -> Beside . map f <$> mapM iSemantics cs
diff --git a/bbcode/src/BBCode/Syntax.hs b/bbcode/src/BBCode/Syntax.hs
new file mode 100644
index 0000000..a196e05
--- /dev/null
+++ b/bbcode/src/BBCode/Syntax.hs
@@ -0,0 +1,108 @@
1{-# LANGUAGE RecordWildCards #-}
2
3module BBCode.Syntax
4 ( treeify
5 , ContentForest
6 , ContentTree(..)
7 ) where
8
9import BBCode.Tokenizer (Token(..))
10
11import Data.Foldable
12import Data.Bifunctor
13import Data.Monoid
14
15import Control.Monad.State
16import Control.Monad.Trans
17import Control.Monad
18
19import Data.CaseInsensitive ( CI )
20import qualified Data.CaseInsensitive as CI
21
22import Data.Function (on)
23
24type ContentForest = [ContentTree]
25data ContentTree = Content String
26 | Tagged [ContentTree] String
27 | Empty
28 deriving (Show, Eq)
29
30data Step = Down [ContentTree] [ContentTree] String
31 deriving (Show)
32
33data Zipper = Zipper
34 { hole :: String
35 , prevs :: [ContentTree]
36 , steps :: [Step]
37 }
38 deriving (Show)
39
40type Parser = StateT Zipper (Either String)
41abort :: String -> Parser a
42abort = lift . Left
43
44
45treeify :: [Token] -> Either String ContentForest
46treeify tokenStream = second (postProcess . unZip) $ execStateT (mapM_ incorporate tokenStream) (Zipper "" [] [])
47
48postProcess :: ContentForest -> ContentForest
49postProcess forest = do
50 tree <- forest
51 let
52 tree' = postProcess' tree
53 guard $ tree' /= Empty
54 return tree'
55 where
56 postProcess' :: ContentTree -> ContentTree
57 postProcess' (Content "") = Empty
58 postProcess' (Tagged [] _) = Empty
59 postProcess' (Tagged cs t) = Tagged [c' | c <- cs, let c' = postProcess' c, c' /= Empty ] t
60 postProcess' x = x
61
62unZip :: Zipper -> ContentForest
63unZip Zipper{..} = reverse (apply hole steps : prevs)
64
65apply :: String -> [Step] -> ContentTree
66apply hole steps = hole `apply'` (reverse steps)
67apply' "" [] = Empty
68apply' hole [] = Content hole
69apply' hole (Down pres posts tag:steps) = Tagged (reverse pres ++ [hole `apply` steps] ++ posts) tag
70
71incorporate :: Token -> Parser ()
72incorporate (Text str) = append str
73incorporate (Whitespace str)
74 | delimitsPar str = do
75 currSteps <- gets steps
76 if null currSteps then
77 modify (\Zipper{..} -> Zipper { hole = "", steps = [], prevs = (hole `apply` steps : prevs) })
78 else
79 append str
80 | otherwise = append str
81 where
82 delimitsPar str = (sum . map (const (1 :: Integer)) . filter (== '\n') $ str) >= 1
83incorporate (TagOpen tagName) = modify $ (\z@(Zipper{..}) -> z { steps = (Down [] [] tagName : steps) })
84incorporate (TagClose tagName) = do
85 currSteps <- gets steps
86 case currSteps of
87 [] -> abort $ "Closing unopenend tag: " ++ tagName
88 (Down pres posts tagName':s) -> if ((==) `on` CI.mk) tagName tagName' then
89 goUp
90 else
91 abort $ "Mismatched tags: [" ++ tagName' ++ "]...[/" ++ tagName ++ "]"
92
93append :: String -> Parser ()
94append str = modify (\z@(Zipper{..}) -> z { hole = hole ++ str })
95
96goUp :: Parser ()
97goUp = do
98 (Down pres posts tagName:s) <- gets steps
99 hole <- gets hole
100 let
101 steppedHole = Tagged (reverse pres ++ [Content hole] ++ posts) tagName
102 case s of
103 [] -> modify $ (\z@(Zipper{..}) -> Zipper { hole = "", prevs = steppedHole : prevs, steps = [] })
104 (t:ts) -> do
105 let
106 (Down pres posts tagName) = t
107 t' = Down (steppedHole : pres) posts tagName
108 modify $ (\z -> z { hole = "", steps = (t':ts) })
diff --git a/bbcode/src/BBCode/Tokenizer.hs b/bbcode/src/BBCode/Tokenizer.hs
new file mode 100644
index 0000000..c860c7c
--- /dev/null
+++ b/bbcode/src/BBCode/Tokenizer.hs
@@ -0,0 +1,44 @@
1{-# LANGUAGE OverloadedStrings #-}
2
3module BBCode.Tokenizer
4 ( Token(..)
5 , tokenize
6 ) where
7
8import qualified Data.Text.Lazy as TL
9import qualified Data.Text as T
10
11import Control.Applicative
12import Data.Attoparsec.Text.Lazy
13
14import Data.Char (isSpace)
15import Data.Monoid (mconcat)
16
17data Token = Text String
18 | Whitespace String
19 | TagOpen String
20 | TagClose String
21 deriving (Show, Read, Eq)
22
23tokenize :: String -> Either String [Token]
24tokenize = eitherResult . parse (tokenize' <* endOfInput) . TL.pack
25
26tokenize' :: Parser [Token]
27tokenize' = many $ choice [ whitespace
28 , Text . T.unpack <$> ("\\" *> "[")
29 , tagClose
30 , tagOpen
31 , text
32 ]
33
34whitespace :: Parser Token
35whitespace = Whitespace <$> many1 space
36
37tagOpen :: Parser Token
38tagOpen = TagOpen . T.unpack <$> ("[" *> takeWhile1 (/= ']') <* "]")
39
40tagClose :: Parser Token
41tagClose = TagClose . T.unpack <$> ("[/" *> takeWhile1 (/= ']') <* "]")
42
43text :: Parser Token
44text = Text . T.unpack <$> takeWhile1 (\c -> not (isSpace c) && notInClass "[" c)
diff --git a/default.nix b/default.nix
index 6b9e8ab..8c1478b 100644
--- a/default.nix
+++ b/default.nix
@@ -2,7 +2,13 @@
2}: 2}:
3 3
4rec { 4rec {
5 servant = pkgs.haskellPackages.callPackage ./servant/servant.nix { 5 tprint = pkgs.haskellPackages.callPackage ./tprint/tprint.nix {
6 inherit thermoprint-servant thermoprint bbcode;
7 };
8 bbcode = pkgs.haskellPackages.callPackage ./bbcode/bbcode.nix {
9 inherit thermoprint;
10 };
11 thermoprint-servant = pkgs.haskellPackages.callPackage ./servant/servant.nix {
6 inherit thermoprint; 12 inherit thermoprint;
7 }; 13 };
8 thermoprint = pkgs.haskellPackages.callPackage ./thermoprint/thermoprint.nix {}; 14 thermoprint = pkgs.haskellPackages.callPackage ./thermoprint/thermoprint.nix {};
diff --git a/default.result.do b/default.result.do
index f7cf7ef..56be121 100644
--- a/default.result.do
+++ b/default.result.do
@@ -1,12 +1,18 @@
1find $2 -name '*.hs' -print0 | xargs --null redo-ifchange
2
3# Recording cross-component dependencies
4case $2 in 1case $2 in
5 servant) 2 servant)
6 redo-ifchange thermoprint.result 3 dir=servant
7 ;; 4 name=thermoprint-servant
5 ;;
6 *)
7 dir=$2
8 name=$2
9 ;;
8esac 10esac
9 11
10nix-build -A $2 -o $2.result-link 1>&2 12find $dir \( -name '*.hs' -or -name '*.cabal' -or -name '*.nix' \) -print0 | xargs --verbose --null redo-ifchange
13
14redo-ifchange default.nix
15
16nix-build -A $name -o $dir.result-link 1>&2
11 17
12exec readlink $2.result-link \ No newline at end of file 18exec readlink $dir.result-link \ No newline at end of file
diff --git a/servant/api/Thermoprint/Api.hs b/servant/api/Thermoprint/Api.hs
new file mode 100644
index 0000000..bd5744b
--- /dev/null
+++ b/servant/api/Thermoprint/Api.hs
@@ -0,0 +1,28 @@
1{-# LANGUAGE DataKinds, TypeOperators, DeriveGeneric #-}
2
3module Thermoprint.Api
4 ( ThermoprintApi
5 ) where
6
7import Thermoprint
8import Data.Aeson
9import Servant.API
10import qualified Data.Text.Lazy as Text
11import qualified Data.ByteString.Lazy.Char8 as ByteString
12import Data.ByteString.Lazy.Char8 (ByteString)
13import GHC.Generics
14
15import Control.Monad
16
17instance ToJSON ByteString where
18 toJSON = toJSON . Text.pack . ByteString.unpack
19instance FromJSON ByteString where
20 parseJSON value = (ByteString.pack . Text.unpack) `liftM` parseJSON value
21
22instance ToJSON c => ToJSON (Inline c)
23instance FromJSON c => FromJSON (Inline c)
24
25instance ToJSON c => ToJSON (Block c)
26instance FromJSON c => FromJSON (Block c)
27
28type ThermoprintApi = "print" :> Capture "printerId" Integer :> ReqBody '[JSON] (Block String) :> Post '[JSON] ()
diff --git a/servant/servant.cabal b/servant/servant.cabal
index b509dbc..b877196 100644
--- a/servant/servant.cabal
+++ b/servant/servant.cabal
@@ -16,11 +16,36 @@ build-type: Simple
16-- extra-source-files: 16-- extra-source-files:
17cabal-version: >=1.10 17cabal-version: >=1.10
18 18
19library
20 exposed-modules: Thermoprint.Api
21 hs-source-dirs: api
22 default-language: Haskell2010
23 other-extensions: DataKinds
24 , TypeOperators
25 , DeriveGeneric
26 build-depends: base >=4.8 && <4.9
27 , thermoprint
28 , aeson >=0.9.0 && <0.10
29 , servant >=0.4.4 && <0.5
30 , text >=1.2.1 && <4.5
31 , bytestring >=0.10.6 && <0.11
32
19executable thermoprint 33executable thermoprint
20 main-is: Main.hs 34 main-is: Main.hs
35 hs-source-dirs: src
36 default-language: Haskell2010
21 -- other-modules: 37 -- other-modules:
22 -- other-extensions: 38 other-extensions: RecordWildCards
39 , OverloadedStrings
23 build-depends: base >=4.8 && <4.9 40 build-depends: base >=4.8 && <4.9
24 , thermoprint 41 , thermoprint
25 hs-source-dirs: src 42 , thermoprint-servant
26 default-language: Haskell2010 \ No newline at end of file 43 , aeson >=0.9.0 && <0.10
44 , wai >=3.0.3 && <3.1
45 , servant-server >=0.4.4 && <0.5
46 , warp >=3.1.3 && <3.2
47 , text >=1.2.1 && <1.3
48 , bytestring >=0.10.6 && <0.11
49 , either >=4.4.1 && <4.5
50 , optparse-applicative >=0.11.0 && <0.12
51 , transformers >=0.4.2 && <0.5 \ No newline at end of file
diff --git a/servant/servant.nix b/servant/servant.nix
index 6c90a4f..a84fc77 100644
--- a/servant/servant.nix
+++ b/servant/servant.nix
@@ -2,16 +2,17 @@
2, stdenv 2, stdenv
3, base 3, base
4, thermoprint 4, thermoprint
5, aeson, wai, servant-server, warp, optparse-applicative
5}: 6}:
6 7
7mkDerivation { 8mkDerivation {
8 pname = "thermoprint-servant"; 9 pname = "thermoprint-servant";
9 version = "0.0.0"; 10 version = "0.0.0";
10 src = ./.; 11 src = ./.;
11 isLibrary = false; 12 isLibrary = true;
12 isExecutable = true; 13 isExecutable = true;
13 executableHaskellDepends = [ 14 executableHaskellDepends = [
14 base thermoprint 15 base thermoprint aeson wai servant-server warp optparse-applicative
15 ]; 16 ];
16 homepage = "git://git.yggdrasil.li/thermoprint"; 17 homepage = "git://git.yggdrasil.li/thermoprint";
17 description = "Server for interfacing to cheap thermoprinters"; 18 description = "Server for interfacing to cheap thermoprinters";
diff --git a/servant/src/Main.hs b/servant/src/Main.hs
index e9e1deb..9d88559 100644
--- a/servant/src/Main.hs
+++ b/servant/src/Main.hs
@@ -1,2 +1,71 @@
1{-# LANGUAGE RecordWildCards, OverloadedStrings #-}
2
3import Thermoprint
4import Thermoprint.Api
5
6import Data.Aeson
7import Network.Wai
8import Network.Wai.Handler.Warp
9import Servant
10import qualified Data.Text.Lazy as Text
11import qualified Data.ByteString.Lazy.Char8 as ByteString
12import Data.ByteString.Lazy.Char8 (ByteString)
13import GHC.Generics
14
15import Control.Monad
16import Control.Monad.IO.Class
17import Control.Monad.Trans.Either
18
19import Options.Applicative
20
21import System.IO
22
23server :: Options -> Integer -> Block String -> EitherT ServantErr IO ()
24server Options{..} printerNo printOut = do
25 printerPath <- case genericIndex printers printerNo of
26 Just path -> return path
27 Nothing -> left $ err404 { errBody = "printerId out of bounds" }
28 liftIO $ withFile printerPath WriteMode doPrint
29 where
30 doPrint handle = do
31 hSetBuffering handle NoBuffering
32 ByteString.hPut handle $ render' printOut
33 genericIndex :: Integral i => [a] -> i -> Maybe a
34 genericIndex (x:_) 0 = Just x
35 genericIndex (_:xs) n
36 | n > 0 = genericIndex xs (n - 1)
37 | otherwise = Nothing
38 genericIndex _ _ = Nothing
39
40data Options = Options
41 { port :: Int
42 , printers :: [FilePath]
43 }
44
45options :: Parser Options
46options = Options
47 <$> option auto (
48 long "port"
49 <> short 'p'
50 <> metavar "PORT"
51 <> help "The port we'll run the server on"
52 <> value 8080
53 <> showDefault
54 )
55 <*> some (strArgument (
56 metavar "PATH [...]"
57 <> help "Path to one of the printers to use"
58 ))
59
60thermoprintApi :: Proxy ThermoprintApi
61thermoprintApi = Proxy
62
1main :: IO () 63main :: IO ()
2main = undefined 64main = do
65 execParser opts >>= main'
66 where
67 opts = info (helper <*> options) (
68 fullDesc
69 <> header "thermoprint-servant - A REST server for interacting with a cheap thermoprinter"
70 )
71 main' args@(Options{..}) = run port $ serve thermoprintApi (server args)
diff --git a/thermoprint/src/Thermoprint.hs b/thermoprint/src/Thermoprint.hs
index c8c4c47..3541f81 100644
--- a/thermoprint/src/Thermoprint.hs
+++ b/thermoprint/src/Thermoprint.hs
@@ -1,3 +1,122 @@
1{-# LANGUAGE DeriveFunctor, DeriveGeneric, RecordWildCards, FlexibleInstances #-}
1module Thermoprint 2module Thermoprint
2 ( 3 ( Block(..)
4 , Inline(..)
5 , PrinterConf(..)
6 , render
7 , render'
8 , module Data.Monoid
3 ) where 9 ) where
10
11import Data.Default
12import qualified Data.ByteString.Lazy as Lazy (ByteString)
13import Data.ByteString.Lazy.Char8 (pack)
14import Data.Monoid
15import GHC.Generics
16
17import Data.Binary.Put
18import Data.Encoding
19import Data.Encoding.CP437
20import Data.Word
21
22import Data.List
23
24-- data PrintOut c = Paragraph c
25-- | Center (PrintOut c)
26-- | Underline (PrintOut c)
27-- | Concat (PrintOut c) (PrintOut c)
28-- | Raw Lazy.ByteString
29-- deriving (Show, Read, Eq, Functor, Generic)
30
31data Block c = Over [Block c]
32 | Center (Block c)
33 | Paragraph (Inline c)
34 deriving (Show, Read, Eq, Functor, Generic)
35data Inline c = Beside [Inline c]
36 | Underline (Inline c)
37 | Cooked c
38 | Raw Lazy.ByteString
39 deriving (Show, Read, Eq, Functor, Generic)
40
41instance Monoid (Block c) where
42 mempty = Over []
43 mappend (Over xs) (Over ys) = Over (xs ++ ys)
44 mappend x (Over xs) = Over (x:xs)
45 mappend (Over xs) x = Over (xs ++ [x])
46 mappend x y = Over [x,y]
47
48instance Monoid c => Monoid (Inline c) where
49 mempty = Beside []
50 mappend (Cooked a) (Cooked b) = Cooked (a <> b)
51 mappend (Beside xs) (Beside ys) = Beside (xs ++ ys)
52 mappend x (Beside xs) = Beside (x:xs)
53 mappend (Beside xs) x = Beside (xs ++ [x])
54 mappend x y = Beside [x,y]
55
56data PrinterConf c = PrinterConf
57 { renderCenter :: Put -> Put
58 , renderUnderline :: Put -> Put
59 , renderBeside :: [Put] -> Put
60 , renderOver :: [Put] -> Put
61 , renderParagraph :: Put -> Put
62 , renderCooked :: c -> Put
63 , finalize :: Put -> Put
64 , columns :: Integer
65 }
66
67instance Default (PrinterConf String) where
68 def = PrinterConf
69 { renderCenter = bracket [97, 1] [97, 0] . (>> enc "\n")
70 , renderUnderline = bracket [45, 2] [45, 0]
71 , renderBeside = sequence_
72 , renderOver = sequence_
73 , renderParagraph = (>> enc "\n")
74 , renderCooked = enc -- . wordBreak columns
75 , finalize = \t -> escSequence [64] >> t >> enc "\n"
76 , columns = columns
77 }
78 where
79 columns = 32 :: Integer
80 esc = 27 :: Word8
81 enc :: String -> Put
82 enc = encode CP437
83 escSequence :: [Word8] -> Put
84 escSequence = mapM_ putWord8 . (esc:)
85 bracket :: [Word8] -> [Word8] -> Put -> Put
86 bracket start end t = escSequence start >> t >> escSequence end
87 sequence_ :: Monad m => [m a] -> m ()
88 sequence_ xs = sequence xs >> return ()
89 ensureNewl :: String -> String
90 ensureNewl [] = "\n"
91 ensureNewl str
92 | last str == '\n' = str
93 | otherwise = str ++ "\n"
94 wordBreak :: Integer -> String -> String
95 wordBreak _ [] = []
96 wordBreak remains str
97 | w' > remains = (concat . intersperse "\n" $ chunk columns w) ++ wordBreak (w'' `div` columns) rest
98 | remains - w' == 0 = w ++ "\n" ++ wordBreak columns rest
99 | otherwise = w ++ wordBreak (remains - w') rest
100 where
101 (w:ws) = words str
102 rest = unwords ws
103 w' = genericLength w
104 w'' = w' - remains
105 chunk :: Integer -> [a] -> [[a]]
106 chunk _ [] = []
107
108render :: PrinterConf c -> Block c -> Lazy.ByteString
109render PrinterConf{..} = runPut . finalize . deconstruct
110 where
111 -- deconstruct :: Block c -> Put
112 deconstruct (Over xs) = renderOver $ map deconstruct xs
113 deconstruct (Center x) = renderCenter $ deconstruct x
114 deconstruct (Paragraph x) = renderParagraph $ deconstruct' x
115 -- deconstruct' :: Inline c -> Put
116 deconstruct' (Beside xs) = renderBeside $ map deconstruct' xs
117 deconstruct' (Underline x) = renderUnderline $ deconstruct' x
118 deconstruct' (Cooked x) = renderCooked x
119 deconstruct' (Raw x) = putLazyByteString x
120
121render' :: Block String -> Lazy.ByteString
122render' = render def
diff --git a/thermoprint/thermoprint.cabal b/thermoprint/thermoprint.cabal
index 6c8a395..ffd59dd 100644
--- a/thermoprint/thermoprint.cabal
+++ b/thermoprint/thermoprint.cabal
@@ -1,70 +1,36 @@
1-- Initial thermoprint.cabal generated by cabal init. For further
2-- documentation, see http://haskell.org/cabal/users-guide/
3
4-- The name of the package.
5name: thermoprint 1name: thermoprint
6
7-- The package version. See the Haskell package versioning policy (PVP)
8-- for standards guiding when and how versions should be incremented.
9-- http://www.haskell.org/haskellwiki/Package_versioning_policy
10-- PVP summary: +-+------- breaking API changes
11-- | | +----- non-breaking API additions
12-- | | | +--- code changes with no API change
13version: 0.0.0 2version: 0.0.0
14
15-- A short (one-line) description of the package.
16synopsis: Description of formatting supported by cheap thermoprinters 3synopsis: Description of formatting supported by cheap thermoprinters
17
18-- A longer description of the package.
19-- description: 4-- description:
20
21-- URL for the project homepage or repository.
22homepage: git://git.yggdrasil.li/thermoprint 5homepage: git://git.yggdrasil.li/thermoprint
23
24-- The license under which the package is released.
25license: PublicDomain 6license: PublicDomain
26
27-- The file containing the license text.
28license-file: LICENSE 7license-file: LICENSE
29
30-- The package author(s).
31author: Gregor Kleen 8author: Gregor Kleen
32
33-- An email address to which users can send suggestions, bug reports, and
34-- patches.
35maintainer: aethoago@141.li 9maintainer: aethoago@141.li
36
37-- A copyright notice.
38-- copyright: 10-- copyright:
39
40-- category: 11-- category:
41 12
42build-type: Simple 13build-type: Simple
43 14
44-- Extra files to be distributed with the package, such as examples or a
45-- README.
46-- extra-source-files: 15-- extra-source-files:
47
48-- Constraint on the version of Cabal needed to build this package.
49cabal-version: >=1.10 16cabal-version: >=1.10
50 17
51 18
52library 19library
53 -- Modules exported by the library.
54 exposed-modules: Thermoprint 20 exposed-modules: Thermoprint
55
56 -- Modules included in this library but not exported.
57 -- other-modules: 21 -- other-modules:
22 hs-source-dirs: src
58 23
59 -- LANGUAGE extensions used by modules in this package. 24 default-language: Haskell2010
60 -- other-extensions: 25 other-extensions: DeriveFunctor
26 , DeriveGeneric
27 , RecordWildCards
28 , FlexibleInstances
61 29
62 -- Other library packages from which modules are imported.
63 build-depends: base >=4.8 && <4.9 30 build-depends: base >=4.8 && <4.9
31 , bytestring >=0.10.6 && <0.11
32 , binary >=0.7.5 && <0.8
33 , encoding >=0.8 && <0.9
34 , data-default >=0.5.3 && <0.6
64 35
65 -- Directories containing source files.
66 hs-source-dirs: src
67
68 -- Base language which the package is written in.
69 default-language: Haskell2010
70 \ No newline at end of file 36 \ No newline at end of file
diff --git a/thermoprint/thermoprint.nix b/thermoprint/thermoprint.nix
index 5453c35..76b8875 100644
--- a/thermoprint/thermoprint.nix
+++ b/thermoprint/thermoprint.nix
@@ -1,6 +1,7 @@
1{ mkDerivation 1{ mkDerivation
2, stdenv 2, stdenv
3, base 3, base
4, encoding, data-default
4}: 5}:
5 6
6mkDerivation { 7mkDerivation {
@@ -9,8 +10,8 @@ mkDerivation {
9 src = ./.; 10 src = ./.;
10 isLibrary = true; 11 isLibrary = true;
11 isExecutable = false; 12 isExecutable = false;
12 executableHaskellDepends = [ 13 libraryHaskellDepends = [
13 base 14 base encoding data-default
14 ]; 15 ];
15 homepage = "git://git.yggdrasil.li/thermoprint"; 16 homepage = "git://git.yggdrasil.li/thermoprint";
16 description = "Description of formatting supported by cheap thermoprinters"; 17 description = "Description of formatting supported by cheap thermoprinters";
diff --git a/tprint/LICENSE b/tprint/LICENSE
new file mode 100644
index 0000000..4ad71e2
--- /dev/null
+++ b/tprint/LICENSE
@@ -0,0 +1,27 @@
1Statement of Purpose
2
3The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
4
5Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
6
7For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
8
91. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
10
11the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
12moral rights retained by the original author(s) and/or performer(s);
13publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
14rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
15rights protecting the extraction, dissemination, use and reuse of data in a Work;
16database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
17other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
182. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
19
203. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
21
224. Limitations and Disclaimers.
23
24No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
25Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
26Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
27Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. \ No newline at end of file
diff --git a/tprint/Setup.hs b/tprint/Setup.hs
new file mode 100644
index 0000000..9a994af
--- /dev/null
+++ b/tprint/Setup.hs
@@ -0,0 +1,2 @@
1import Distribution.Simple
2main = defaultMain
diff --git a/tprint/src/Main.hs b/tprint/src/Main.hs
new file mode 100644
index 0000000..565295b
--- /dev/null
+++ b/tprint/src/Main.hs
@@ -0,0 +1,77 @@
1{-# LANGUAGE RecordWildCards #-}
2
3import Thermoprint
4import Thermoprint.Api
5
6import qualified BBCode (parse)
7
8import Options.Applicative
9
10import Data.Either
11import Control.Monad
12import Control.Monad.Trans.Either
13
14import System.IO
15import System.Exit
16
17import Data.Proxy
18import Servant.Client
19
20thermoprintApi :: Proxy ThermoprintApi
21thermoprintApi = Proxy
22
23data Options = Options
24 { baseUrl :: BaseUrl
25 , printerId :: Integer
26 , dryRun :: Bool
27 }
28
29options :: Parser Options
30options = Options
31 <$> option baseUrlReader (
32 long "url"
33 <> short 'u'
34 <> metavar "URL"
35 <> help "The base url of the api"
36 <> value (BaseUrl Http "localhost" 8080)
37 <> showDefaultWith showBaseUrl
38 )
39 <*> option auto (
40 long "printer"
41 <> short 'p'
42 <> metavar "INT"
43 <> help "The number of the printer to use"
44 <> value 0
45 <> showDefault
46 )
47 <*> flag False True (
48 long "dry-run"
49 <> short 'd'
50 <> help "Instead of sending data to printer output the parsed stream to stderr"
51 <> showDefault
52 )
53 where
54 baseUrlReader = str >>= either readerError return . parseBaseUrl
55
56main :: IO ()
57main = execParser opts >>= main'
58 where
59 opts = info (helper <*> options) (
60 fullDesc
61 <> header "tprint - A cli tool for interfacing with the REST api as provided by thermoprint-servant"
62 )
63
64 main' Options{..} = do
65 let
66 print :: Integer -> Block String -> EitherT ServantError IO ()
67 print = client thermoprintApi baseUrl
68 input <- BBCode.parse `liftM` getContents
69 input' <- either (\err -> hPutStrLn stderr ("Parse error: " ++ err) >> exitFailure) return input
70 case dryRun of
71 False -> do
72 res <- runEitherT $ print printerId input'
73 case res of
74 Left err -> hPutStrLn stderr $ show err
75 Right _ -> exitSuccess
76 True -> do
77 hPutStrLn stderr $ show input'
diff --git a/tprint/tprint.cabal b/tprint/tprint.cabal
new file mode 100644
index 0000000..a5d2a61
--- /dev/null
+++ b/tprint/tprint.cabal
@@ -0,0 +1,31 @@
1-- Initial tprint.cabal generated by cabal init. For further
2-- documentation, see http://haskell.org/cabal/users-guide/
3
4name: tprint
5version: 0.0.0
6synopsis: A cli-tool for interfacing with thermoprint-servant
7-- description:
8homepage: git://git.yggdrasil.li/thermoprint
9license: PublicDomain
10license-file: LICENSE
11author: Gregor Kleen
12maintainer: aethoago@141.li
13-- copyright:
14-- category:
15build-type: Simple
16-- extra-source-files:
17cabal-version: >=1.10
18
19executable tprint
20 main-is: Main.hs
21 -- other-modules:
22 -- other-extensions:
23 hs-source-dirs: src
24 default-language: Haskell2010
25 build-depends: base >=4.8 && <4.9
26 , thermoprint
27 , thermoprint-servant
28 , bbcode
29 , optparse-applicative >=0.11.0 && <1
30 , servant-client >=0.4.4 && <1
31 , either >=4.4.1 && <5 \ No newline at end of file
diff --git a/tprint/tprint.nix b/tprint/tprint.nix
new file mode 100644
index 0000000..cce38c4
--- /dev/null
+++ b/tprint/tprint.nix
@@ -0,0 +1,20 @@
1{ mkDerivation
2, stdenv
3, base
4, thermoprint-servant, thermoprint, bbcode
5, optparse-applicative, servant-client
6}:
7mkDerivation {
8 pname = "tprint";
9 version = "0.0.0";
10 src = ./.;
11 isLibrary = false;
12 isExecutable = true;
13 executableHaskellDepends = [ base
14 thermoprint thermoprint-servant bbcode
15 optparse-applicative servant-client
16 ];
17 homepage = "git://git.yggdrasil.li/thermoprint";
18 description = "A cli-tool for interfacing with thermoprint-servant";
19 license = stdenv.lib.licenses.publicDomain;
20}