Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / static / snf / js / ui / web / ui_icon_view.js @ 32a58fdf

History | View | Annotate | Download (32.4 kB)

1
// Copyright 2011 GRNET S.A. All rights reserved.
2
// 
3
// Redistribution and use in source and binary forms, with or
4
// without modification, are permitted provided that the following
5
// conditions are met:
6
// 
7
//   1. Redistributions of source code must retain the above
8
//      copyright notice, this list of conditions and the following
9
//      disclaimer.
10
// 
11
//   2. Redistributions in binary form must reproduce the above
12
//      copyright notice, this list of conditions and the following
13
//      disclaimer in the documentation and/or other materials
14
//      provided with the distribution.
15
// 
16
// THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
// POSSIBILITY OF SUCH DAMAGE.
28
// 
29
// The views and conclusions contained in the software and
30
// documentation are those of the authors and should not be
31
// interpreted as representing official policies, either expressed
32
// or implied, of GRNET S.A.
33
// 
34

    
35
;(function(root){
36

    
37
    // root
38
    var root = root;
39
    
40
    // setup namepsaces
41
    var snf = root.synnefo = root.synnefo || {};
42
    var models = snf.models = snf.models || {}
43
    var storage = snf.storage = snf.storage || {};
44
    var ui = snf.ui = snf.ui || {};
45
    var util = snf.util = snf.util || {};
46

    
47
    var views = snf.views = snf.views || {}
48

    
49
    // shortcuts
50
    var bb = root.Backbone;
51
    
52
    // handle extended info toggler
53
    views.VMActionErrorView = views.View.extend({
54
    
55
        initialize: function (vm, view) {
56
            this.vm = vm;
57
            this.view = view;
58
            this.vm_view = this.view.vm(vm);
59

    
60
            this.has_error = false;
61
            
62
            this.error = this.vm_view.find(".action-error");
63
            this.close = this.vm_view.find(".close-action-error");
64
            this.show_btn = this.vm_view.find(".show-action-error");
65

    
66
            this.init_handlers();
67
            this.update_layout();
68
        },
69

    
70
        init_handlers: function() {
71
            // action call failed notify the user
72
            this.vm.bind("action:fail", _.bind(function(args){
73
                if (this.vm.action_error) {
74
                    this.has_error = true;
75
                    var action = "undefined";
76
                    try {
77
                        action = _.last(args).error_params.extra_details['Action'];
78
                    } catch (err) {console.log(err)};
79
                    
80
                    this.error.find(".action").text(action);
81
                    this.error.show();
82
                }
83
            }, this));
84
            
85
            // show error overlay
86
            this.show_btn.click(_.bind(function() {
87
                if (this.vm.action_error) {
88
                    this.show_error_overlay(this.vm.action_error);
89
                }
90
                this.vm.reset_action_error();
91
            }, this));
92
            
93
            // user requests to forget about the error
94
            this.close.click(_.bind(_.bind(function() {
95
                this.error.hide();
96
                this.vm.reset_action_error();
97
            }, this)));
98
            
99
            // hide error message if action fail get reset
100
            this.vm.bind("action:fail:reset", _.bind(function(){
101
                this.error.hide();
102
            }, this));
103
        },
104

    
105
        show_error_overlay: function(args) {
106
            var args = util.parse_api_error.apply(util, args);
107
            
108
            // force logout if UNAUTHORIZED request arrives
109
            if (args.code == 401) { snf.ui.logout(); return };
110
            
111
            var error_entry = [args.ns, args.code, args.message, args.type, args.details, args];
112
            ui.main.error_view.show_error.apply(ui.main.error_view, error_entry);
113
        },
114

    
115
        update_layout: function() {
116
            if (this.vm.action_error) {
117
                this.error.show();
118
            }
119
        }
120
    });
121

    
122
    // handle extended info toggler
123
    views.IconInfoView = views.View.extend({
124
    
125
        initialize: function (vm, view) {
126
            this.vm = vm;
127
            this.view = view;
128
            this.vm_view = this.view.vm(vm);
129
            
130
            this.info_toggle = $(".cont-toggler-wrapper.info .toggler", this.vm_view);
131
            this.ips_toggle = $(".cont-toggler-wrapper.ips .toggler", this.vm_view);
132
            this.info_el = $("div.info-content.vm-info", this.vm_view);
133
            this.ips_el = $("div.info-content.ips", this.vm_view);
134
            this.label = $(".label", this.vm_view);
135

    
136
            this.set_handlers();
137
        },
138

    
139
        set_handlers: function() {
140
            this.info_toggle.click(_.bind(function(){
141
                this.ips_el.slideUp();
142
                this.ips_toggle.removeClass("open");
143

    
144
                this.info_el.slideToggle();
145
                this.view.vm(this.vm).toggleClass("light-background");
146

    
147
                if (this.info_toggle.hasClass("open")) {
148
                    this.info_toggle.removeClass("open");
149
                    this.vm.stop_stats_update();
150
                } else {
151
                    this.info_toggle.addClass("open");
152
                    this.view.details_views[this.vm.id].update_layout();
153
                    this.view.tags_views[this.vm.id].update_layout();
154
                    this.view.stats_views[this.vm.id].update_layout();
155
                }
156
                
157
                var self = this;
158
                window.setTimeout(function() {$(self.view).trigger("resize")}, 300);
159
            }, this));
160

    
161
            this.ips_toggle.click(_.bind(function(){
162
                this.info_el.slideUp();
163
                this.info_toggle.removeClass("open");
164

    
165
                this.ips_el.slideToggle();
166
                this.view.vm(this.vm).toggleClass("light-background");
167
                var self = this;
168
                if (this.ips_toggle.hasClass("open")) {
169
                    this.ips_toggle.removeClass("open");
170
                } else {
171
                    this.ips_toggle.addClass("open");
172
                }
173
                window.setTimeout(function() {$(self.view).trigger("resize")}, 300);
174
            }, this));
175

    
176

    
177
            this.$(".stats-report").click(_.bind(function(e){
178
                e.preventDefault();
179
                snf.ui.main.show_vm_details(this.vm);
180
            }, this))
181
        }
182
    
183
    })
184

    
185
    // rename handler view
186
    // only icon view contains rename capability
187
    views.IconRenameView = views.View.extend({
188
        
189
        initialize: function(vm, view) {
190
            this.vm = vm;
191
            this.view = view;
192
            // name container
193
            this.el = $('div#' + this.view.id_tpl + vm.id + " div.name").get(0);
194
            // name inline element
195
            this.name = this.$('span.name');
196
            // rename button
197
            this.rename = this.$('span.rename');
198
            // save button
199
            this.save = this.$('.save');
200
            // cancel rename button
201
            this.cancel = this.$('.cancel');
202
            // where to place the input field
203
            this.edit_cont = this.$(".namecontainer");
204
            // buttons container
205
            this.buttons = this.$(".editbuttons");
206
            // current state
207
            this.renaming = false;
208
            // init event handlers
209
            this.set_handlers();
210
            // paint
211
            this.update_layout();
212
            views.IconRenameView.__super__.initialize.call(this);
213
        },
214
        
215
        // update elements visibility/state
216
        update_layout: function() {
217
            // if in renaming state
218
            if (this.renaming) {
219
                // if name is hidden we are already in renaming state
220
                // dont do nothing
221
                if (this.name.is(":hidden")){return}
222
                
223
                // hide name element to make space for the 
224
                // text input
225
                this.name.hide();
226
                this.rename.hide();
227
                // show confirm/cancel buttons
228
                this.buttons.show();
229
                // create text element
230
                this.create_input();
231
            } else {
232
                // name is visible not in edit mode
233
                if (this.name.is(":visible")){return}
234

    
235
                this.name.show();
236
                this.rename.show();
237
                this.buttons.hide();
238
                this.remove_input();
239
            }
240
        },
241
        
242
        // create rename input field and set appropriate 
243
        // event handlers
244
        create_input: function() {
245
            var self = this;
246
            this.edit_cont.append('<input class="vm-rename nametextbox" type="text" />');
247
            this.$('input').val(this.vm.get('name'));
248
            // give edit focus
249
            this.$('input').focus();
250
            // handle enter press
251
            this.$('input').keydown(function(ev){
252
                ev.keyCode = ev.keyCode || ev.which;
253
                if (ev.keyCode == 13) { self.submit(); }
254
                if (ev.keyCode == 27) { self.renaming = false; self.update_layout(); }
255
            })
256
        },
257
        
258
        // remove input element
259
        remove_input: function() {
260
            this.$('input').remove();
261
        },
262
        
263
        // initialize event handlers
264
        set_handlers: function() {
265
            var self = this;
266
            // start rename when rename button is pressed
267
            this.rename.click(function() {
268
                self.renaming = true;
269
                self.update_layout();
270
            });
271
            
272
            // double click on name
273
            $(this.el).dblclick(function() {
274
                self.renaming = true;
275
                self.update_layout();
276
            });
277

    
278
            // cancel rename
279
            this.cancel.click(function() {
280
                self.renaming = false;
281
                self.update_layout();
282
            })
283
            
284
            // apply the rename
285
            // TODO: check if name is equal than the previous value
286
            this.save.click(function() {
287
                self.submit();
288
            })
289
        },
290

    
291
        submit: function() {
292
            var value = _(self.$('input').val()).trim();
293
            if (value == "") { return };
294
            this.renaming = false;
295
            this.vm.rename(self.$('input').val());
296
            this.update_layout();
297
        }
298
    });
299
    
300
    // VM connect interaction view
301
    views.IconVMConnectView = views.View.extend({
302
        
303
        initialize: function(vm, view) {
304
            // parent view (single, icon, list)
305
            this.parent = view;
306
            this.vm = vm;
307
            this.el = view.vm(vm);
308
            this.set_handlers();
309
            views.IconVMConnectView.__super__.initialize.call(this);
310
        },
311
        
312
        // set the appropriate handlers
313
        set_handlers: function() {
314
            // setup connect handler on vm icon interaction
315
            var el = this.el;
316
            var vm = this.vm;
317

    
318
            // element that triggers the connect handler
319
            var connect = el.find("div.connect-arrow, .logo");
320
            // connect status handler
321
            var handler = _.bind(this.connect_handler, {vm:vm, el:el, view:this.parent});
322
            $(connect).bind({'mouseover': handler, 'mouseleave': handler, 
323
                            'mousedown': handler, 'mouseup': handler,
324
                            'click': handler });
325
            
326
            // setup connect arrow display handlers 
327
            // while hovering vm container
328
            el.bind("mouseover", function(){
329
                if (vm.is_connectable()) {
330
                    el.find(".connect-border").show();
331
                    el.find(".connect-arrow").show();
332
                    el.find(".logo").css({cursor:"pointer"});
333
                } else {
334
                    el.find(".connect-border").hide();
335
                    el.find(".connect-arrow").hide();
336
                    el.find(".logo").css({cursor: "default"});
337
                }
338
            }).bind("mouseleave", function(){
339
                el.find(".connect-border").hide();
340
                el.find(".connect-arrow").hide();
341
            });
342
        },
343
        
344
        // connect arrow interaction handlers
345
        // BEWARE, this function has different context
346
        // than the View object itself, see set_vm_handlers
347
        connect_handler: function(event) {
348
            // nothing to do if we cannot connect to the vm
349
            if (!this.vm.is_connectable()) {return}
350
            
351
            var logo = this.el.find(".logo");
352
            var arrow = this.el.find(".connect-arrow");
353
            var border = this.el.find(".connect-border");
354
            
355
            // clear icon states
356
            logo.removeClass('single-image-state1 single-image-state2 single-image-state3 single-image-state4');
357
            
358
            // append the appropriate state class
359
            switch (event.type) {
360
                case "mouseover":       
361
                    logo.addClass('single-image-state4');
362
                    arrow.addClass('border-hover');
363
                    break;
364
                
365
                case "mouseleave":
366
                    logo.addClass('single-image-state1');
367
                    arrow.removeClass('border-hover');
368
                    break;
369

    
370
                case "mouseup":
371
                    logo.addClass('single-image-state4');
372
                    //this.view.connect_overlay.show(this.vm);
373
                    break;
374

    
375
                case "mousedown":
376
                    logo.addClass('single-image-state2');
377
                    break;
378

    
379
                case "click":
380
                    //logo.addCLass('single-image-state4');
381
                    //this.view.connect_to_console(vm);
382
                    this.view.connect_overlay.show(this.vm);
383
                    break;
384

    
385
                default:
386
                    ;
387
            }
388
        },
389
        
390
        update_layout: function() {
391
        }
392

    
393
    });
394
    
395
    // vm metadata subview for icon and single view
396
    views.VMTagsView = views.View.extend({
397
        view_id: 'vm_tags',
398
        // metadata container selector
399
        el_sel: '.vm-metadata',
400
        // metadata row template
401
        tag_tpl: '<span class="tag-item"><span class="key">{0}</span><span class="value">{1}</span></span>',
402
        // how many tags to show
403
        tag_limit: 4,
404
        // truncate options (because container has different size on icon/single views)
405
        tag_key_truncate: 7,
406
        tag_value_truncate: 15,
407

    
408
        initialize: function(vm, view, toggle, limit, tag_key_truncate, tag_value_truncate) {
409
            this.tag_limit = limit || this.tag_limit;
410

    
411
            this.tag_key_truncate = tag_key_truncate || this.tag_key_truncate;
412
            this.tag_value_truncate = tag_value_truncate || this.tag_value_truncate;
413

    
414
            // does the view toggles the metadata container (single view)
415
            this.toggle = toggle || false;
416
            // parent view
417
            this.parent = view;
418
            this.vm = vm;
419
            this.el = this.parent.vm(vm);
420
            this.view_id = this.view_id + "_" + vm.id;
421

    
422
            // link to raise the metadata manager overlay
423
            this.link = this.$('a.manage-metadata');
424

    
425
            views.VMTagsView.__super__.initialize.call(this);
426
            this.set_handlers();
427
            this.update_layout();
428
        },
429
        
430
        // set the appropriate handlers
431
        set_handlers: function() {
432
            var self = this;
433
            // show the metadata editor overlay
434
            this.link.click(_.bind(function(ev) {
435
                ev.preventDefault();
436
                this.parent.metadata_view.show(this.vm);
437
            }, this));
438

    
439
            // tags/ips have show/hide control ? bind events for them
440
            var self = this;
441
            if (this.toggle) {
442
                $(this.el).find(".tags-header").click(_.bind(function(){
443
                    $(self.el).find(".tags-content").slideToggle(600);
444
                    var details_toggler = $(this.el).find(".tags-header " +
445
                                                          ".cont-toggler");
446
                    if (details_toggler.hasClass("open")) {
447
                        details_toggler.removeClass("open");
448
                    } else {
449
                        details_toggler.addClass("open");
450
                    }
451
                }, this));
452
                $(this.el).find(".tags-header").find(".toggler").removeClass("open");
453
                $(self.el).find(".tags-content").hide();
454
            }
455
        },
456
        
457
        // update metadata container and data
458
        update_layout: function() {
459

    
460
            // api metadata object
461
            var meta =  this.vm.get('metadata');
462

    
463
            var i = 0;
464
            var cont = $(this.el).find(".items");
465

    
466
            // clear existing items
467
            cont.find(".tag-item").remove();
468
            
469
            // create tag elements
470
            _.each(meta, function(value, key){
471
                // respect the limit
472
                if (i > this.tag_limit) {
473
                    return;
474
                }
475
                
476
                // create element
477
                var new_el = $(this.tag_tpl.format(util.truncate(key, this.tag_key_truncate), 
478
                                                 util.truncate(": " + _.escape(value), this.tag_value_truncate)));
479

    
480
                // add title attributes, improve accesibility
481
                // truncated values
482
                new_el.find("span.key").attr("title", key);
483
                new_el.find("span.value").attr("title", _.escape(value));
484

    
485
                cont.append(new_el);
486
            }, this);
487
        }
488
    });
489
    
490

    
491
    // stats subview for single/icon views
492
    views.VMStatsView = views.View.extend({
493

    
494
        initialize: function(vm, view, options) {
495
            if (!options) {options = {}};
496
            this.vm = vm;
497
            this.parent = view;
498
            this.sel = options.el || this.el_sel || ".lower";
499
            this.el = this.parent.vm(vm).find(this.sel);
500
            this.selected_stats_period = 'hourly';
501
            
502
            // elements shortcuts
503
            this.cpu_loading = this.el.find(".cpu-graph .stat-busy");
504
            this.cpu_error = this.el.find(".cpu-graph .stat-error");
505
            this.cpu_img = this.el.find(".cpu-graph .stat-img");
506
            this.net_loading = this.el.find(".network-graph .stat-busy");
507
            this.net_error = this.el.find(".network-graph .stat-error");
508
            this.net_img = this.el.find(".network-graph .stat-img");
509

    
510
            this.loading = this.el.find(".stat-busy");
511
            this.error = this.el.find(".stat-error");
512
            this.img = this.el.find(".stat-img");
513
            this.stats_period_options = this.el.find(".stats-select-option");
514
            
515

    
516
            // handle stats period option select
517
            var self = this;
518
            this.stats_period_options.click(function(){
519
                // skip if current selection is clicked
520
                if ($(this).filter(".stats-" + self.selected_stats_period).length) {
521
                    return
522
                } else {
523
                    // identify class
524
                    var cls = $(this).attr("class");
525
                    regex = /.*\sstats-(\w+)/;
526
                    self.set_stats_period(cls.match(regex)[1]);
527
                }
528
            });
529
            
530
            // initial state paremeters
531
            this.stats = this.vm.get("stats");
532

    
533
            // timeseries or bar images ?
534
            this.stats_type = options.stats_type || "bar";
535

    
536
            views.VMStatsView.__super__.initialize.apply(this, arguments);
537
            this.set_handlers();
538
            this.update_layout();
539

    
540
            this.net_loading.show();
541
            this.net_error.hide();
542
            this.cpu_loading.show();
543
            this.cpu_error.hide();
544

    
545
            this.net_img.hide();
546
            this.cpu_img.hide();
547
            
548
            if (!window.t) {
549
                window.t = [];
550
            }
551
            if (this.parent.menu) {
552
                window.t[window.t.length] = this;
553
            }
554
        },
555

    
556
        
557
        set_stats_period: function(period) {
558
            this.selected_stats_period = period;
559
            this.update_layout();
560
        },
561

    
562
        set_handlers: function() {
563
            // update view state when vm stats update gets triggered
564
            this.vm.bind("stats:update", _.bind(function(){
565
                // update the layout
566
                this.update_layout();
567
            }, this));
568
        },
569
        
570
        get_images: function (type, period) {
571
            var period = period || 'hourly';
572
            var images;
573

    
574
            if (type == 'bar') {
575
                images = {'cpu': this.stats.cpuBar, 'net': this.stats.netBar };
576
            } else {
577
                images = {'cpu': this.stats.cpuTimeSeries, 
578
                          'net': this.stats.netTimeSeries };
579
            }
580

    
581
            if (period == 'weekly' && type != 'bar') {
582
                if (images.cpu)
583
                    images.cpu = images.cpu.replace('cpu-ts', 'cpu-ts-w')
584
                if (images.net)
585
                    images.net = images.net.replace('net-ts', 'net-ts-w')
586
            }
587
            return images
588
        },
589

    
590
        update_layout: function() {
591
            if (!this.vm.stats_available) {
592
                this.loading.show();
593
                this.img.hide();
594
                this.error.hide();
595
            } else {
596
                this.loading.hide();
597
                this.stats = this.vm.get("stats");
598
                var images = this.get_images(this.stats_type, 
599
                                             this.selected_stats_period)
600

    
601
                if (images.cpu) {
602
                    this.cpu_img.attr({src:images.cpu}).show();
603
                    this.cpu_error.hide();
604
                } else {
605
                    this.cpu_img.hide();
606
                    this.cpu_error.show();
607
                }
608

    
609
                if (images.net) {
610
                    this.net_img.attr({src:images.net}).show();
611
                    this.net_error.hide();
612
                } else {
613
                    this.net_img.hide();
614
                    this.net_error.show();
615
                }
616
            }
617
                
618
            // update selected stats period
619
            this.stats_period_options.removeClass("selected");
620
            this.stats_period_options.filter(".stats-" + this.selected_stats_period).addClass("selected")
621

    
622
            $(window).trigger("resize");
623
        }
624
    });
625

    
626
    views.VMDetailsView = views.View.extend({
627
        view_id: "vm_details",
628
        el_sel: '.vm-details',
629
        
630

    
631
        selectors: {
632
            'cpu': '.cpu-data',
633
            'ram': '.ram-data',
634
            'disk': '.disk-data',
635
            'image_name': '.image-data',
636
            'image_size': '.image-size-data'
637
        },
638

    
639
        initialize: function(vm, view) {
640
            this.parent = view;
641
            this.vm = vm;
642
            this.el = $(this.parent.vm(vm)).find(this.el_sel).get(0);
643
            this.view_id = "vm_{0}_details".format(vm.id);
644
            
645
            views.VMDetailsView.__super__.initialize.call(this);
646
            
647
            this.resize_actions = this.$(".trigger-resize");
648
            this.init_handlers();
649
            this.update_layout();
650
        },
651
        
652
        init_handlers: function() {
653
          this.resize_actions.bind('click', _.bind(function(e){
654
              ui.main.vm_resize_view.show(this.vm);
655
          }, this));
656
        },
657

    
658
        update_layout: function() {
659
            if (!this.visible() && this.parent.details_hidden) { return };
660

    
661
            var image = this.vm.get_image(_.bind(function(image){
662
                this.sel('image_name').text(util.truncate(image.escape('name'), 17)).attr("title", image.escape('name'));
663
                this.sel('image_size').text(image.get_readable_size()).attr('title', image.get_readable_size());
664
            }, this));
665

    
666
            var flavor = this.vm.get_flavor();
667
            if (!flavor || !image) {
668
                return;
669
            }
670

    
671

    
672
            this.sel('cpu').text(flavor.get('cpu'));
673
            this.sel('ram').text(flavor.get('ram'));
674
            this.sel('disk').text(flavor.get('disk'));
675

    
676
            this.parent.tags_views[this.vm.id].update_layout();
677
            this.parent.stats_views[this.vm.id].update_layout();
678
            
679
            if (this.parent.details_hidden) {
680
                this.vm.start_stats_update(true);
681
            }
682
        }
683
    });
684
    
685
    // VMs icon view
686
    views.IconView = views.VMListView.extend({
687
        
688
        // view id (this could be used to identify 
689
        // the view object from global context
690
        view_id: 'vm_icon',
691
        
692
        details_hidden: true,
693

    
694
        el: '#machinesview-icon',
695
        id_tpl: 'icon-vm-',
696

    
697
        selectors: {
698
            'vms': '.machine-container',
699
            'vm': '#icon-vm-',
700
            'view': '#machinesview-icon',
701
            'tpl': '#machinesview-icon.standard #machine-container-template',
702
            'spinner': '.large-spinner',
703
            'vm_spinner': '#icon-vm-{0} .state .spinner',
704
            'vm_wave': '#icon-vm-{0} .wave',
705
            'vm_cont_active': '#machinesview-icon.standard .running',
706
            'vm_cont_terminated': '#machinesview-icon.standard .terminated'
707
        },
708
            
709
        reset: function() {},
710
        // overload show function
711
        show_view: function() {
712
            $(this.el).show();
713
            this.__update_layout();
714
        },
715

    
716
        post_update_vm: function(vm) {
717
        },
718

    
719
        // identify vm model instance id based on DOM element
720
        vm_id_for_element: function(el) {
721
            return el.attr('id').replace("icon-vm-","");
722
        },
723
        
724
        // set generic view handlers
725
        set_handlers: function() {
726
        },  
727
        
728
        // stuff to do when a new vm has been created.
729
        // - create vm subviews
730
        post_add: function(vm) {
731
            // rename views index
732
            this.rename_views = this.rename_views || {};
733
            this.stats_views = this.stats_views || {};
734
            this.connect_views = this.connect_views || {};
735
            this.tags_views = this.tags_views || {};
736
            this.details_views = this.details_views || {};
737
            this.info_views = this.info_views || {};
738
            this.action_error_views = this.action_error_views || {};
739
            this.action_views = this.action_views || {};
740
            this.ports_views = this.ports_views || {};
741

    
742
            this.action_views[vm.id] = new views.VMActionsView(vm, this, this.vm(vm), this.hide_actions);
743
            this.rename_views[vm.id] = new views.IconRenameView(vm, this);
744
            this.stats_views[vm.id] = new views.VMStatsView(vm, this, {el:'.vm-stats'});
745
            this.connect_views[vm.id] = new views.IconVMConnectView(vm, this);
746
            this.tags_views[vm.id] = new views.VMTagsView(vm, this);
747
            this.details_views[vm.id] = new views.VMDetailsView(vm, this);
748
            this.action_error_views[vm.id] = new views.VMActionErrorView(vm, this);
749
            
750
            var ports_container = this.vm(vm).find(".machine-data");
751
            var ports_view = new views.VMPortListView({
752
              collection: vm.ports, 
753
              container: ports_container,
754
              parent: this
755
            });
756
            this.ports_views[vm.id] = ports_view
757
            ports_view.show();
758
            ports_view.el.hide();
759

    
760
            this.info_views[vm.id] = new views.IconInfoView(vm, this);
761
        },
762
        
763
        // vm specific event handlers
764
        set_vm_handlers: function(vm) {
765
        },
766

    
767
        check_terminated_is_empty: function() {
768
            // hide/show terminated container
769
            if (this.$(".terminated .machine-container").length == 0) {
770
                this.$(".terminated").hide()
771
            } else {
772
                this.$(".terminated").show()
773
            }
774

    
775
            $(window).trigger("resize");
776
        },
777
        
778
        // generic stuff to do on each view update
779
        // called once after each vm has been updated
780
        update_layout: function() {
781
            // TODO: why do we do this ??
782
            if (storage.vms.models.length > 0) {
783
                this.$(".running").removeClass("disabled");
784
            } else {
785
                this.$(".running").addClass("disabled");
786
            }
787
            
788
            this.check_terminated_is_empty();
789
    
790
            // FIXME: code from old js api
791
            this.$("div.separator").show();
792
            this.$("div.machine-container:last-child").find("div.separator").hide();
793
            fix_v6_addresses();
794
        },
795
  
796
        update_status_message: function(vm) {
797
            var el = this.vm(vm);
798
            var message = vm.get_status_message();
799
            if (message) {
800
                // update bulding progress
801
                el.find("div.machine-ips").hide();
802
                el.find("div.build-progress").show();
803
                el.find("div.build-progress .message").text(util.truncate(message, 42));
804

    
805
                if (vm.in_error_state()) {
806
                    el.find("div.build-progress .btn").show();
807
                } else {
808
                    el.find("div.build-progress .btn").hide();
809
                }
810
            } else {
811
                // hide building progress
812
                el.find("div.machine-ips").show()
813
                el.find("div.build-progress").hide();
814
                el.find("div.build-progress .btn").hide();
815
            }
816
        },
817

    
818
        // update vm details
819
        update_details: function(vm) {
820
            var el = this.vm(vm);
821
            // truncate name
822
            el.find("span.name").text(util.truncate(vm.get("name"), 40));
823

    
824
            el.find('.fqdn').text(vm.get('fqdn'));
825
            el.find("div.status").text(STATE_TEXTS[vm.state()]);
826
            // set state class
827
            el.find("div.state").removeClass().addClass(views.IconView.STATE_CLASSES[vm.state()].join(" "));
828
            // os icon
829
            el.find("div.logo").css({'background-image': "url(" + this.get_vm_icon_path(vm, "medium") + ")"});
830
            
831
            el.removeClass("connectable");
832
            if (vm.is_connectable()) {
833
                el.addClass("connectable");
834
            }
835
            
836
            var status = vm.get("status");
837
            var state = vm.get("state");
838
            
839
            this.update_status_message(vm);
840

    
841
            icon_state = vm.is_active() ? "on" : "off";
842
            set_machine_os_image(el, "icon", icon_state, this.get_vm_icon_os(vm));
843
            
844
            // update subviews
845
            this.rename_views[vm.id].update_layout();
846
            this.connect_views[vm.id].update_layout();
847
            this.details_views[vm.id].update_layout();
848
        },
849

    
850
        post_remove_vm: function(vm) {
851
            this.check_terminated_is_empty();
852
            $(window).trigger("resize");
853
        },
854
            
855
        get_vm_icon_os: function(vm) {
856
            var os = vm.get_os();
857
            var icons = window.os_icons || views.IconView.VM_OS_ICONS;
858

    
859
            if (icons.indexOf(os) == -1) {
860
                os = "unknown";
861
            }
862

    
863
            return os;
864
        },
865

    
866
        // TODO: move to views.utils (the method and the VM_OS_ICON vars)
867
        get_vm_icon_path: function(vm, icon_type) {
868
            var os = vm.get_os();
869
            var icons = window.os_icons || views.IconView.VM_OS_ICONS;
870

    
871
            if (icons.indexOf(os) == -1) {
872
                os = "unknown";
873
            }
874

    
875
            return views.IconView.VM_OS_ICON_TPLS()[icon_type].format(os);
876
        }
877
    })
878

    
879
    views.IconView.VM_OS_ICON_TPLS = function() {
880
        return {
881
            "medium": snf.config.machines_icons_url + "medium/{0}-sprite.png"
882
        }
883
    }
884

    
885
    views.IconView.VM_OS_ICONS = window.os_icons || [];
886

    
887
    views.IconView.STATE_CLASSES = {
888
        'UNKNOWN':          ['state', 'error-state'],
889
        'BUILD':            ['state', 'build-state'],
890
        'REBOOT':           ['state', 'rebooting-state'],
891
        'STOPPED':          ['state', 'terminated-state'],
892
        'ACTIVE':           ['state', 'running-state'],
893
        'ERROR':            ['state', 'error-state'],
894
        'DELETED':          ['state', 'destroying-state'],
895
        'DESTROY':          ['state', 'destroying-state'],
896
        'SHUTDOWN':         ['state', 'shutting-state'],
897
        'START':            ['state', 'starting-state'],
898
        'CONNECT':          ['state', 'connecting-state'],
899
        'DISCONNECT':       ['state', 'disconnecting-state'],
900
        'RESIZE':           ['state', 'rebooting-state']
901
    };
902

    
903
})(this);