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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// ---- START CLIPPY CONFIG

#![cfg_attr(all(not(test), feature="clippy"), warn(result_unwrap_used))]
#![cfg_attr(feature="clippy", warn(unseparated_literal_suffix))]
#![cfg_attr(feature="clippy", warn(wrong_pub_self_convention))]

// Enable clippy if our Cargo.toml file asked us to do so.
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]

#![warn(missing_copy_implementations,
        trivial_numeric_casts,
        trivial_casts,
        unused_extern_crates,
        unused_import_braces,
        unused_qualifications)]
#![cfg_attr(feature="clippy", warn(cast_possible_truncation))]
#![cfg_attr(feature="clippy", warn(cast_possible_wrap))]
#![cfg_attr(feature="clippy", warn(cast_precision_loss))]
#![cfg_attr(feature="clippy", warn(cast_sign_loss))]
#![cfg_attr(feature="clippy", warn(missing_docs_in_private_items))]
#![cfg_attr(feature="clippy", warn(mut_mut))]

// Disallow `println!`. Use `debug!` for debug output
// (which is provided by the `log` crate).
#![cfg_attr(feature="clippy", warn(print_stdout))]

// This allows us to use `unwrap` on `Option` values (because doing makes
// working with Regex matches much nicer) and when compiling in test mode
// (because using it in tests is idiomatic).
#![cfg_attr(all(not(test), feature="clippy"), warn(result_unwrap_used))]
#![cfg_attr(feature="clippy", warn(unseparated_literal_suffix))]
#![cfg_attr(feature="clippy", warn(wrong_pub_self_convention))]

// ---- END CLIPPY CONFIG

#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
extern crate cassowary;
extern crate euclid;

use std::collections::HashSet;
use std::ops::Drop;
use std::mem;
use std::rc::Rc;
use std::cell::RefCell;

use cassowary::{Variable, Constraint};
use cassowary::WeightedRelation::*;
use cassowary::strength::*;

use euclid::{Point2D, Size2D, UnknownUnit};

use self::constraint::ConstraintBuilder;
use self::constraint::*;

pub type Length = euclid::Length<f32, UnknownUnit>;
pub type Size = Size2D<f32>;
pub type Point = Point2D<f32>;
pub type Rect = euclid::Rect<f32>;

pub type LayoutId = usize;

/// A set of cassowary `Variable`s representing the
/// bounding rectangle of a layout.
#[derive(Debug, Copy, Clone)]
pub struct LayoutVars {
    pub left: Variable,
    pub top: Variable,
    pub right: Variable,
    pub bottom: Variable,
    pub width: Variable,
    pub height: Variable,
}

impl LayoutVars {
    pub fn new() -> Self {
        LayoutVars {
            left: Variable::new(),
            top: Variable::new(),
            right: Variable::new(),
            bottom: Variable::new(),
            width: Variable::new(),
            height: Variable::new(),
        }
    }

    /// Returns the current inner state of this struct as an array
    pub fn array(&self) -> [Variable; 6] {
        [self.left,
         self.top,
         self.right,
         self.bottom,
         self.width,
         self.height]
    }

    /// If a `Variable` matches one of the variables in this layout, return it's type
    pub fn var_type(&self, var: Variable) -> VarType {
        if var == self.left { VarType::Left }
        else if var == self.top { VarType::Top }
        else if var == self.right { VarType::Right }
        else if var == self.bottom { VarType::Bottom }
        else if var == self.width { VarType::Width }
        else if var == self.height { VarType::Height }
        else { VarType::Other }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum VarType {
    Left,
    Top,
    Right,
    Bottom,
    Width,
    Height,
    Other,
}

pub trait LayoutRef {
    fn layout_ref(&self) -> LayoutVars;
}

impl<'a> LayoutRef for &'a mut Layout {
    fn layout_ref(&self) -> LayoutVars {
        self.vars
    }
}

impl LayoutRef for Layout {
    fn layout_ref(&self) -> LayoutVars {
        self.vars
    }
}

impl LayoutRef for LayoutVars {
    /// Returns a copy of the current `LayoutVars`
    fn layout_ref(&self) -> LayoutVars {
        *self
    }
}

/// Represents a single item in the overall layout hierarchy with a bounding rectangle and an id.
///
/// Modifying any properties of this layout only stores those changes here, they won't affect the
/// solver until this struct is passed to the solver.
pub struct Layout {
    pub vars: LayoutVars,
    pub name: Option<String>,
    pub id: LayoutId,
    container: Option<Rc<RefCell<LayoutContainer>>>,
    parent: Option<LayoutId>,
    children: Vec<LayoutId>,
    edit_vars: Vec<EditVariable>,
    constraints: HashSet<Constraint>,
    new_constraints: HashSet<Constraint>,
    removed_constraints: Vec<Constraint>,
    removed_children: Vec<LayoutId>,
    associated_vars: Vec<(Variable, String)>,
    pub hidden: bool,
}

impl Layout {

    /// Creates a new `Layout`.
    pub fn new(id: LayoutId, name: Option<String>) -> Self {
        let vars = LayoutVars::new();
        let mut new_constraints = HashSet::new();
        new_constraints.insert(vars.right - vars.left| EQ(REQUIRED) | vars.width);
        new_constraints.insert(vars.bottom - vars.top | EQ(REQUIRED) | vars.height);
        new_constraints.insert(vars.width | GE(REQUIRED) | 0.0);
        new_constraints.insert(vars.height | GE(REQUIRED) | 0.0);
        Layout {
            vars: vars,
            name: name,
            id: id,
            container: Some(Rc::new(RefCell::new(Frame::default()))),
            parent: None,
            children: Vec::new(),
            edit_vars: Vec::new(),
            constraints: HashSet::new(),
            new_constraints: new_constraints,
            removed_constraints: Vec::new(),
            removed_children: Vec::new(),
            associated_vars: Vec::new(),
            hidden: false,
        }
    }

    pub fn layout(&mut self) -> &mut Self {
        self
    }

    /// Clears the container of the current `Layout`.
    pub fn no_container(&mut self) {
        self.container = None;
    }

    /// Replaces the container of the current layout.
    /// The container is what determines what constraints will be added between this layout
    /// and it's children, as they are added, if any.
    pub fn set_container<T>(&mut self, container: T) where T: LayoutContainer + 'static {
        self.container = Some(Rc::new(RefCell::new(container)));
    }
    pub fn edit_left(&mut self) -> VariableEditable {
        let var = self.vars.left;
        VariableEditable::new(self, var)
    }
    pub fn edit_top(&mut self) -> VariableEditable {
        let var = self.vars.top;
        VariableEditable::new(self, var)
    }
    pub fn edit_right(&mut self) -> VariableEditable {
        let var = self.vars.right;
        VariableEditable::new(self, var)
    }
    pub fn edit_bottom(&mut self) -> VariableEditable {
        let var = self.vars.bottom;
        VariableEditable::new(self, var)
    }
    pub fn edit_width(&mut self) -> VariableEditable {
        let var = self.vars.width;
        VariableEditable::new(self, var)
    }
    pub fn edit_height(&mut self) -> VariableEditable {
        let var = self.vars.height;
        VariableEditable::new(self, var)
    }
    pub fn create_constraint<B: ConstraintBuilder>(&self, builder: B) -> Vec<Constraint> {
        builder.build(&self.vars)
    }
    pub fn add<B: ConstraintBuilder>(&mut self, builder: B) {
        let new_constraints = builder.build(&self.vars);
        self.new_constraints.extend(new_constraints);
    }
    pub fn remove_constraint(&mut self, constraint: Constraint) {
        if !self.new_constraints.remove(&constraint) {
            self.removed_constraints.push(constraint);
        }
    }
    pub fn remove_constraints(&mut self, constraints: Vec<Constraint>) {
        for constraint in constraints {
            if !self.new_constraints.remove(&constraint) {
                self.removed_constraints.push(constraint);
            }
        }
    }
    pub fn has_constraint(&mut self, constraints: &Vec<Constraint>) -> bool {
        for constraint in constraints {
            if self.new_constraints.contains(constraint) || self.constraints.contains(constraint) {
                return true
            }
        }
        false
    }
    pub fn get_constraints(&mut self) -> HashSet<Constraint> {
        let new_constraints = mem::replace(&mut self.new_constraints, HashSet::new());
        for constraint in new_constraints.clone() {
            self.constraints.insert(constraint);
        }
        new_constraints
    }
    pub fn get_removed_constraints(&mut self) -> Vec<Constraint> {
        let removed_constraints = mem::replace(&mut self.removed_constraints, Vec::new());
        for ref constraint in &removed_constraints {
            self.constraints.remove(constraint);
        }
        removed_constraints
    }
    pub fn get_edit_vars(&mut self) -> Vec<EditVariable> {
        mem::replace(&mut self.edit_vars, Vec::new())
    }
    pub fn add_child(&mut self, child: &mut Layout) {
        child.parent = Some(self.id);
        self.children.push(child.id);
        if let Some(container) = self.container.clone() {
            container.borrow_mut().add_child(self, child);
        }
    }
    pub fn remove_child(&mut self, child: &mut Layout) {
        if let Some(container) = self.container.clone() {
            container.borrow_mut().remove_child(self, child);
        }
        if let Some(pos) = self.children.iter().position(|id| child.id == *id) {
            self.children.remove(pos);
        }
        self.removed_children.push(child.id);
    }
    pub fn get_removed_children(&mut self) -> Vec<LayoutId> {
        mem::replace(&mut self.removed_children, Vec::new())
    }
    pub fn get_children(&self) -> &Vec<LayoutId> {
        &self.children
    }
    pub fn add_associated_vars(&mut self, vars: &LayoutVars, name: &str) {
        for var in vars.array().iter() {
            let var_type = format!("{:?}", vars.var_type(*var)).to_lowercase();
            self.associated_vars.push((*var, format!("{}.{}", name, var_type)));
        }
    }
    pub fn add_associated_var(&mut self, var: Variable, name: &str) {
        self.associated_vars.push((var, name.to_owned()));
    }
    pub fn get_associated_vars(&mut self) -> Vec<(Variable, String)> {
        mem::replace(&mut self.associated_vars, Vec::new())
    }
    pub fn hide(&mut self) {
        self.hidden = true;
    }
    pub fn show(&mut self) {
        self.hidden = false;
    }
}

pub struct VariableEditable<'a> {
    pub builder: &'a mut Layout,
    pub var: Variable,
    val: Option<f64>,
    strength: f64,
}

impl<'a> VariableEditable<'a> {
    pub fn new(builder: &'a mut Layout, var: Variable) -> Self {
        VariableEditable {
            builder: builder,
            var: var,
            val: None,
            strength: STRONG,
        }
    }
    pub fn strength(mut self, strength: f64) -> Self {
        self.strength = strength;
        self
    }
    pub fn set(mut self, val: f32) -> Self {
        self.val = Some(val as f64);
        self
    }
}

impl<'a> Drop for VariableEditable<'a> {
    fn drop(&mut self) {
        let edit_var = EditVariable::new(&self);
        self.builder.edit_vars.push(edit_var);
    }
}

#[derive(Debug, Copy, Clone)]
pub struct EditVariable {
    var: Variable,
    val: f64,
    strength: f64,
}

impl EditVariable {
    fn new(editable: &VariableEditable) -> Self {
        EditVariable {
            var: editable.var,
            val: editable.val.unwrap_or(0.0),
            strength: editable.strength,
        }
    }
}

/// Used to specify a list of constraints.
// Needed to box different ConstraintBuilder impls,
// can't be done without specifying Vec<Box<ConstraintBuilder>>.
// Can be removed if/when variadic generics are added to rust.
#[macro_export]
macro_rules! constraints {
    ( $ ( $ x : expr ) , * ) => {
        constraints!( $ ( $ x , ) * )
    };
    ( $ ( $ x : expr , ) * ) => {
        {
            let mut vec: Vec<Box<ConstraintBuilder>> = Vec::new();
            $(
                vec.push(Box::new($x));
            )*
            vec
        }
    };
}

/// Defines what constraints a parent applies to it's children as they are added
pub trait LayoutContainer {
    fn add_child(&mut self, parent: &mut Layout, child: &mut Layout);
    fn remove_child(&mut self, _: &mut Layout, _: &mut Layout) {}
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Frame {
    padding: f32,
}

impl LayoutContainer for Frame {

    /// Adds a weak constraint to a Frame
    fn add_child(&mut self, parent: &mut Layout, child: &mut Layout) {
        child.add(constraints![
            bound_by(&parent).padding(self.padding),
            match_layout(&parent).strength(WEAK),
        ]);
    }
}

#[derive(Debug, Copy, Clone)]
pub struct ExactFrame;

impl LayoutContainer for ExactFrame {
    fn add_child(&mut self, parent: &mut Layout, child: &mut Layout) {
        child.add(match_layout(&parent));
    }
}

pub mod solver;
pub mod constraint;
pub mod linear_layout;
pub mod grid_layout;

pub use self::solver::LimnSolver;

lazy_static! {
    pub static ref LAYOUT: LayoutVars = LayoutVars::new();
}