1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
use enumx::export::*;
use enumx::predefined::*;
use cex::*;

use crate::{
    InterpResult,
    OptPair,
    PathOptsWidgets,
    Tk,
    TkInstance,
    TkOption,
    Widget,
    cmd::append_opts,
    opt::TkFontOpt,
};

use std::os::raw::{c_int, c_longlong};

use tcl::{
    Obj,
    error::{
        NotList,
        NotSeqOf,
        InterpError,
    },
};

use tuplex::*;

#[derive( Copy, Clone )]
pub enum Style {
    Normal,
    Bold,
    Roman,
    Italic,
    Underline,
    Overstrike,
}

impl From<Style> for Obj {
    fn from( style: Style ) -> Obj {
        match style {
            Style::Normal       => "normal"     .into(),
            Style::Bold         => "bold"       .into(),
            Style::Roman        => "roman"      .into(),
            Style::Italic       => "italic"     .into(),
            Style::Underline    => "underline"  .into(),
            Style::Overstrike   => "overstrike" .into(),
        }
    }
}

pub enum Font<'a, Opts> {
    Name( &'a str ),
    System( &'a str ),
    Family{ family: &'a str, size: Option<c_int>, styles: &'a [Style] },
    XFont( &'a str ),
    Opts( Opts ),
}

impl<'a, Opts> From<Font<'a, Opts>> for Obj
    where Opts : IntoHomoTuple<TkFontOpt>
               + IntoHomoTuple<OptPair>
{
    fn from( font: Font<'a, Opts> ) -> Obj {
        match font {
            Font::Name(   name ) |
            Font::System( name ) |
            Font::XFont(  name ) => name.into(),
            Font::Family{ family, size, styles } => {
                (family, size, styles.to_vec() ).into()
            },
            Font::Opts( opts ) => {
                let mut v = Vec::new();
                append_opts( &mut v, opts );
                v.into()
            },
        }
    }
}

impl<Inst:TkInstance> Tk<Inst> {
    /// Returns the value of the actual attribute that are obtained when font is used on
    /// the main window's display; the actual attribute obtained may differ from the
    /// attribute requested due to platform-dependent limitations, such as the
    /// availability of font families and point sizes. If the char argument is supplied,
    /// the font attribute returned will be those of the specific font used to render
    /// that character, which will be different from the base font if the base font does
    /// not contain the given character.
    pub fn font_actual<'a, Opt, Opts>( &self, font: Font<'a, Opts>, _option: Opt, ch: Option<char> ) -> InterpResult<Obj>
        where Opt  : TkOption
                   + Into<TkFontOpt>
            , Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let font = Obj::from( font );
        let option = Obj::from( <Opt as TkOption>::NAME );

        match ch {
            Some( '-' ) => self.eval(( "font", "actual", font, option, "--", "-" )),
            Some( ch ) => self.eval(( "font", "actual", font, option, Obj::from(ch) )),
            None => self.eval(( "font", "actual", font, option )),
        }
    }

    /// Returns a list of all the atual attributes and their values that are obtained
    /// when font is used on the main window's display; the actual attributes obtained
    /// may differ from the attributes requested due to platform-dependent limitations,
    /// such as the availability of font families and point sizes. If the char argument
    /// is supplied, the font attributes returned will be those of the specific font
    /// used to render that character, which will be different from the base font if the
    /// base font does not contain the given character.
    pub fn font_actual_get_all<'a, Opts>( &self, font: Font<'a, Opts> ) -> InterpResult<Obj>
        where Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let font = Obj::from( font );
        self.eval(( "font", "actual", font ))
    }

    pub fn font_configure<Opts>( &self, fontname: &str, opts: impl Into<PathOptsWidgets<Opts,()>> ) -> InterpResult<()>
        where Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let mut command = Vec::<Obj>::with_capacity( <<Opts as IntoHomoTuple<OptPair>>::Output as tuplex::Len>::LEN * 2 + 3 );

        command.push( "font".into() );
        command.push( "configure".into() );
        command.push( fontname.into() );

        append_opts( &mut command, opts.into().opts );
        self.run( command )
    }

    pub fn font_configure_get<Opt>( &self, fontname: &str, _opt: Opt ) -> InterpResult<Obj>
        where Opt : TkOption
                  + Into<TkFontOpt>
    {
        self.eval(( "font", "configure", fontname, <Opt as TkOption>::NAME ))
    }

    #[cex]
    pub fn font_configure_get_all( &self, fontname: &str ) -> Result!( Vec<OptPair>
        throws InterpError, NotList, NotSeqOf<OptPair> )
    {
        let mut opt_pairs = Vec::new();
        let obj = self.eval(( "font", "configure", fontname ))?;
        let mut pairs = obj.clone().get_elements()?;
        while let Some( name ) = pairs.next() {
            let value = if let Some( value ) = pairs.next() {
                value.clone()
            } else {
                throw!( NotSeqOf::new( obj.clone() ));
            };
            let name = match name.get_string().as_str() {
                "-family"     => "family"    ,
                "-size"       => "size"      ,
                "-weight"     => "weight"    ,
                "-slant"      => "slant"     ,
                "-underline"  => "underline" ,
                "-overstrike" => "overstrike",
                _             => throw!( NotSeqOf::new( obj )),
            };
            opt_pairs.push( OptPair{ name, value });
        }
        Ok( opt_pairs )
    }

    pub fn font_create<Opts>( &self, fontname: &str, opts: impl Into<PathOptsWidgets<Opts,()>> ) -> InterpResult<Obj>
        where Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let mut command = Vec::<Obj>::with_capacity( <<Opts as IntoHomoTuple<OptPair>>::Output as tuplex::Len>::LEN * 2 + 3 );

        command.push( "font".into() );
        command.push( "create".into() );
        command.push( fontname.into() );

        append_opts( &mut command, opts.into().opts );
        self.eval( command )
    }

    pub fn font_create_with_auto_name<Opts>( &self, opts: impl Into<PathOptsWidgets<Opts,()>> ) -> InterpResult<Obj>
        where Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let mut command = Vec::<Obj>::with_capacity( <<Opts as IntoHomoTuple<OptPair>>::Output as tuplex::Len>::LEN * 2 + 2 );

        command.push( "font".into() );
        command.push( "create".into() );

        append_opts( &mut command, opts.into().opts );
        self.eval( command )
    }

    pub fn font_delete( &self, names: &[Obj] ) -> InterpResult<()> {
        let mut command = Vec::<Obj>::with_capacity( names.len() + 2 );
        command.push( "font".into() );
        command.push( "delete".into() );
        command.extend( names.iter().map( |name| name.clone() ));
        self.run( command )
    }

    #[cex]
    pub fn font_families( &self ) -> Result!( Vec<String> throws InterpError, NotList ) {
        let list = self.eval(( "font", "families" ))?;
        Ok( list.get_elements()?.map( |obj| obj.get_string() ).collect() )
    }

    pub fn font_measure<'a, Opts>( &self, font: Font<'a, Opts>, text: impl Into<String> ) -> InterpResult<c_longlong>
        where Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let font = Obj::from( font );
        self.longlong( self.eval(( "font", "measure", font, text.into() ))? )
    }

    pub fn font_metrics<'a, Opt, Opts>( &self, font: Font<'a, Opts>, _opt: Opt ) -> InterpResult<Obj>
        where Opt  : TkOption
                   + Into<TkFontOpt>
            , Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let font = Obj::from( font );
        let option = Obj::from( <Opt as TkOption>::NAME );
        self.eval(( "font", "metrics", font, option ))
    }

    #[cex]
    pub fn font_metrics_get_all<'a, Opts>( &self, font: Font<'a, Opts> ) -> Result!( Vec<OptPair>
        throws InterpError, NotList, NotSeqOf<OptPair> )
        where Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let font = Obj::from( font );
        let mut opt_pairs = Vec::new();
        let obj = self.eval(( "font", "metrics", font ))?;
        let mut pairs = obj.clone().get_elements()?;
        while let Some( name ) = pairs.next() {
            let value = if let Some( value ) = pairs.next() {
                value.clone()
            } else {
                throw!( NotSeqOf::new( obj.clone() ));
            };
            let name = match name.get_string().as_str() {
                "-ascent"    => "ascent"   ,
                "-descent"   => "descent"  ,
                "-linespace" => "linespace",
                "-fixed"     => "fixed"    ,
                _            => throw!( NotSeqOf::new( obj )),
            };
            opt_pairs.push( OptPair{ name, value });
        }
        Ok( opt_pairs )
    }

    /// The return value is a list of all the named fonts that are currently defined.
    ///
    /// # Examples
    ///
    /// ```
    /// use tcl::*;
    /// use tk::*;
    /// use tk::cmd::*;
    ///
    /// let tk = make_tk!()?;
    /// let font_names = tk.font_names().unwrap();
    /// assert!( font_names.len() > 0 );
    ///
    /// # TkResult::Ok(())
    /// ```
    #[cex]
    pub fn font_names( &self ) -> Result!( Vec<String> throws InterpError, NotList ) {
        let list = self.eval(( "font", "names" ))?;
        Ok( list.get_elements()?.map( |obj| obj.get_string() ).collect() )
    }
}

impl<Inst:TkInstance> Widget<Inst> {
    /// Returns the value of the actual attributes that are obtained when font is used
    /// on window's display; the actual attribute obtained may differ from the attribute
    /// requested due to platform-dependent limitations, such as the availability of
    /// font families and point sizes. If the char argument is supplied, the font
    /// attributes returned will be those of the specific font used to render that
    /// character, which will be different from the base font if the base font does not
    /// contain the given character.
    pub fn font_actual<'a, Opt, Opts>( &self, font: Font<'a, Opts>, _option: Opt, ch: Option<char> ) -> InterpResult<Obj>
        where Opt  : TkOption
                   + Into<TkFontOpt>
            , Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let font = Obj::from( font );
        let option = Obj::from( <Opt as TkOption>::NAME );

        match ch {
            Some( '-' ) => self.tk().eval(( "font", "actual", font, "-displayof", self.path, option, "--", "-" )),
            Some( ch ) => self.tk().eval(( "font", "actual", font, "-displayof", self.path, option, Obj::from(ch) )),
            None => self.tk().eval(( "font", "actual", font, "-displayof", self.path, option )),
        }
    }

    /// Returns a list of all the atual attributes and their values that are obtained
    /// when font is used on window's display; the actual attributes obtained may differ
    /// from the attributes requested due to platform-dependent limitations, such as the
    /// availability of font families and point sizes. If the char argument is supplied,
    /// the font attributes returned will be those of the specific font used to render
    /// that character, which will be different from the base font if the base font does
    /// not contain the given character.
    pub fn font_actual_get_all<'a, Opts>( &self, font: Font<'a, Opts> ) -> InterpResult<Obj>
        where Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let font = Obj::from( font );
        self.tk().eval(( "font", "actual", font, "-displayof", self.path ))
    }

    #[cex]
    pub fn font_families( &self ) -> Result!( Vec<String> throws InterpError, NotList ) {
        let list = self.tk().eval(( "font", "families", "-displayof", self.path ))?;
        Ok( list.get_elements()?.map( |obj| obj.get_string() ).collect() )
    }

    pub fn font_measure<'a, Opts>( &self, font: Font<'a, Opts>, text: impl Into<String> ) -> InterpResult<c_longlong>
        where Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let font = Obj::from( font );
        self.tk().longlong( self.tk().eval(( "font", "measure", font, "-displayof", self.path, text.into() ))? )
    }

    pub fn font_metrics<'a, Opt, Opts>( &self, font: Font<'a, Opts>, _opt: Opt ) -> InterpResult<Obj>
        where Opt  : TkOption
                   + Into<TkFontOpt>
            , Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let font = Obj::from( font );
        let option = Obj::from( <Opt as TkOption>::NAME );
        self.tk().eval(( "font", "metrics", font, "-displayof", self.path, option ))
    }

    #[cex]
    pub fn font_metrics_get_all<'a, Opts>( &self, font: Font<'a, Opts> ) -> Result!( Vec<OptPair>
        throws InterpError, NotList, NotSeqOf<OptPair> )
        where Opts : IntoHomoTuple<TkFontOpt>
                   + IntoHomoTuple<OptPair>
    {
        let font = Obj::from( font );
        let mut opt_pairs = Vec::new();
        let obj = self.tk().eval(( "font", "metrics", font, "-displayof", self.path ))?;
        let mut pairs = obj.clone().get_elements()?;
        while let Some( name ) = pairs.next() {
            let value = if let Some( value ) = pairs.next() {
                value.clone()
            } else {
                throw!( NotSeqOf::new( obj.clone() ));
            };
            let name = match name.get_string().as_str() {
                "-ascent"    => "ascent"   ,
                "-descent"   => "descent"  ,
                "-linespace" => "linespace",
                "-fixed"     => "fixed"    ,
                _           => throw!( NotSeqOf::new( obj )),
            };
            opt_pairs.push( OptPair{ name, value });
        }
        Ok( opt_pairs )
    }
}