Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / static / snf / js / ui / web / ui_vms_base_view.js @ 8a6915df

History | View | Annotate | Download (33.9 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

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

    
48
    // shortcuts
49
    var bb = root.Backbone;
50
    
51
    // logging
52
    var logger = new snf.logging.logger("SNF-VIEWS");
53
    var debug = _.bind(logger.debug, logger);
54
    
55
    var hasKey = Object.prototype.hasOwnProperty;
56

    
57
    views.CreateSnapshotView = views.Overlay.extend({
58
        view_id: "snapshot_create_view",
59
        content_selector: "#snapshot-create-content",
60
        css_class: 'overlay-snapshot-create overlay-info',
61
        overlay_id: "snapshot-create-overlay",
62

    
63
        title: "Create new snapshot",
64
        subtitle: "Machines",
65

    
66
        initialize: function(options) {
67
            views.CreateSnapshotView.__super__.initialize.apply(this);
68

    
69
            this.create_button = this.$("form .form-action.create");
70
            this.text = this.$(".snapshot-create-name");
71
            this.description = this.$(".snapshot-create-desc");
72
            this.form = this.$("form");
73
            this.init_handlers();
74
        },
75
        
76
        show: function(vm) {
77
          this.vm = vm;
78
          views.CreateSnapshotView.__super__.show.apply(this);
79
        },
80

    
81
        init_handlers: function() {
82

    
83
            this.create_button.click(_.bind(function(e){
84
                this.submit();
85
            }, this));
86

    
87
            this.form.submit(_.bind(function(e){
88
                e.preventDefault();
89
                this.submit();
90
                return false;
91
            }, this))
92

    
93
            this.text.keypress(_.bind(function(e){
94
                if (e.which == 13) {this.submit()};
95
            },this))
96
        },
97

    
98
        submit: function() {
99
            if (this.validate()) {
100
                this.create();
101
            };
102
        },
103
        
104
        validate: function() {
105
            // sanitazie
106
            var t = this.text.val();
107
            t = t.replace(/^\s+|\s+$/g,"");
108
            this.text.val(t);
109

    
110
            if (this.text.val() == "") {
111
                this.text.closest(".form-field").addClass("error");
112
                this.text.focus();
113
                return false;
114
            } else {
115
                this.text.closest(".form-field").removeClass("error");
116
            }
117
            return true;
118
        },
119
        
120
        create: function() {
121
            this.create_button.addClass("in-progress");
122

    
123
            var name = this.text.val();
124
            var desc = this.description.val();
125
            
126
            this.vm.create_snapshot(name, desc, _.bind(function() {
127
              this.hide();
128
            }, this));
129
        },
130
        
131
        _default_values: function() {
132
          var date = (new Date()).toString();
133
          var vmname = this.vm.get('name');
134
          var id = this.vm.id;
135

    
136
          var name = "snf-{0} '{1}' snapshot ({2})".format(id, vmname, date);
137
          var description = "Snapshot created at: {0}".format(date);
138
          description += "\n" + "Machine name: '{0}'".format(vmname);
139
          description += "\n" + "Machine id: '{0}'".format(id);
140

    
141
          return {
142
            'name': name,
143
            'description': description
144
          }
145
        },
146

    
147
        beforeOpen: function() {
148
            this.create_button.removeClass("in-progress")
149
            this.text.closest(".form-field").removeClass("error");
150
            var defaults = this._default_values();
151

    
152
            this.text.val(defaults.name);
153
            this.description.val(defaults.description);
154
            this.text.show();
155
            this.text.focus();
156
            this.description.show();
157
        },
158

    
159
        onOpen: function() {
160
            this.text.focus();
161
        }
162
    });
163

    
164
    // base class for views that contain/handle VMS
165
    views.VMListView = views.View.extend({
166

    
167
        // just a flag to identify that
168
        // views of this type handle vms
169
        vms_view: true,
170

    
171
        selectors: {},
172
        hide_actions: true,
173
        pane: "#machines-pane",
174
        metadata_view: undefined,
175

    
176
        initialize: function() {
177
            views.VMListView.__super__.initialize.call(this);
178
            this._vm_els = {};
179
            this.set_storage_handlers();
180
            this.set_handlers();
181
            this.vms_updated_handler();
182
            this.connect_overlay = new views.VMConnectView();
183
        },
184

    
185
        // display vm diagnostics detail overlay view, update based on
186
        // diagnostics_update_interval config value.
187
        show_build_details_for_vm: function(vm) {
188
            var cont = null;
189
            var success = function(data) {
190
                var message = "";
191
                var title = vm.get('name');
192
                var info = '<em>Status log messages:</em>';
193

    
194
                var list_el = $('<div class="diagnostics-list">');
195
                list_el.append('<div class="empty">No data available</div>');
196

    
197
                cont = list_el;
198
                var messages = _.clone(data);
199

    
200
                update_overlay_diagnostics(data, cont);
201
                synnefo.ui.main.details_view.show(title, info, cont);
202
            }
203

    
204
            var update_overlay_diagnostics = function(data) {
205
                var existing = cont.find(".msg-log-entry");
206
                var messages = _.clone(data);
207
                
208
                var to_append = messages.slice(0, messages.length - existing.length);
209
                to_append.reverse();
210

    
211
                var appending = to_append.length != messages.length;
212
                
213
                if (to_append.length) { cont.find(".empty").hide() } else {
214
                    if (!messages.length) { cont.find(".empty").show() }
215
                }
216
                _.each(to_append, function(msg){
217
                    var el = $('<div class="clearfix msg-log-entry ' + msg.level.toLowerCase() + '">');
218
                    if (msg.details) {
219
                      el.addClass("with-details");
220
                    }
221
                    var display_source_date = synnefo.config.diagnostics_display_source_date;
222
                    var source_date = "";
223
                    if (display_source_date) {
224
                        source_date = '('+synnefo.util.formatDate(new Date(msg.source_date))+')';
225
                    }
226

    
227
                    el.append('<span class="date">' + synnefo.util.formatDate(new Date(msg.created)) + source_date + '</span>');
228
                    el.append('<span class="src">' + _.escape(msg.source) + '</span>');
229
                    el.append('<span class="msg">' + _.escape(msg.message) + '</span>');
230
                    if (msg.details) {
231
                        el.append('<pre class="details">' + _.escape(msg.details) + '</pre>');
232
                    }
233
                    if (appending) { el.hide(0); el.css({'display':'none'})}
234
                    cont.prepend(el);
235
                    el.click(function(el) {
236
                        $(this).find(".details").slideToggle();
237
                        $(this).toggleClass("expanded");
238
                    });
239

    
240
                    if (appending) { el.fadeIn(800); }
241
                });
242
                
243
                window.setTimeout(function(){
244
                    if (cont.is(":visible")) {
245
                        vm.get_diagnostics(update_overlay_diagnostics);
246
                    }
247
                }, synnefo.config.diagnostics_update_interval);
248
            }
249

    
250
            vm.get_diagnostics(success);
251
        },
252

    
253
        // Helpers
254
        //
255
        // get element based on this.selectors key/value pairs
256
        sel: function(id, params) {
257
            if (!this.selectors[id]){ return };
258
            return $(this.selectors[id].format(params));
259
        },
260
        
261
        // vm element based on vm model instance provided
262
        vm: function(vm) {
263
            if (hasKey.call(this._vm_els, vm.id)) {
264
                ret = this._vm_els[vm.id];
265
            } else {
266
                return $([]);
267
            }
268

    
269
            return ret;
270
        },
271
        
272
        // get vm model instance from DOM element
273
        vm_for_element: function(el) {
274
            return storage.vms.sel(this.vm_id_for_element(el));
275
        },
276
        
277

    
278
        // Event binding and stuff like that
279
        //
280
        set_storage_handlers: function() {
281
            storage.vms.bind("add", _.bind(this.vms_updated_handler, this, "add"));
282
            storage.vms.bind("change", _.bind(this.vms_updated_handler, this, "change"));
283
            storage.vms.bind("reset", _.bind(this.vms_updated_handler, this, "reset"));
284
            storage.vms.bind("remove", _.bind(this.vms_updated_handler, this, "remove"));
285
        },
286
        
287
        // vms updated triggered, update view vms
288
        vms_updated_handler: function (method, model, arg2, arg3) {
289
            var updated = storage.vms.models;
290
            if (method == "add") { updated = [model] };
291
            if (method == "change") { updated = [model] };
292
            if (method == "remove") { updated = [model] };
293

    
294
            if (method == "remove") {
295
                this.remove_vm(model)
296
                return;
297
            }
298
            
299
            this.update_vms(updated);
300
        },
301

    
302
        // create vm
303
        // append it on proper view container
304
        create_vm: function(vm) {
305
            // create dom element
306
            var vm_view = this.create_vm_element(vm);
307
            vm_view.find(".vm-actions").attr("id", this.view_id+"-actions-" + vm.id);
308
            this._vm_els[vm.id] = vm_view;
309
            var container = this.get_vm_container(vm);
310
            container.append(vm_view);
311
            vm_view.find(".action-indicator").text("");
312
            if (this.visible()) {
313
                container.show()
314
            }
315

    
316
            // initialize vm specific event handlers 
317
            this.__set_vm_handlers(vm);
318
            vm_view.find(".suspended-notice").click(function(){
319
              synnefo.ui.main.suspended_view.show(vm);
320
            })
321
            return vm_view;
322
        },
323
        
324
        // create vm dom element
325
        create_vm_element: function(vm) {
326
            // clone template
327
            return this.sel('tpl').clone().attr("id", this.id_tpl + vm.id)
328
        },
329

    
330
        // get proper vm container
331
        get_vm_container: function(vm) {
332
            if (vm.is_active()) {
333
                return this.sel("vm_cont_active");
334
            } else {
335
                return this.sel("vm_cont_terminated");
336
            }
337
        },
338

    
339
        // create and append inside the proper container the vm model
340
        // if it doesn't exist update vm data and make it visible
341
        add: function(vm) {
342
            // create if it does not exist
343
            if (!hasKey.call(this._vm_els, vm.id)) {
344
                var el = this.create_vm(vm);
345
                el.show();
346
                this.post_add(vm);
347
                this.init_vm_view_handlers(vm);
348
            }
349

    
350
            return this.vm(vm);
351
        },
352

    
353
        init_vm_view_handlers: function(vm) {
354
            var self = this;
355
            var el = this.vm(vm);
356

    
357
            // hidden feature, double click on indicators to display 
358
            // vm diagnostics.
359
            el.find(".indicators").bind("dblclick", function(){
360
                self.show_build_details_for_vm(vm);
361
            });
362

    
363
            // this button gets visible if vm creation failed.
364
            el.find("div.build-progress .btn").click(function(){
365
                self.show_build_details_for_vm(vm);
366
            });
367
        },
368
        
369
        // helpers for VMListView descendants
370
        post_add: function(vm) { throw "Not implemented" },
371
        set_vm_handlers: function(vm) { throw "Not implemented" },
372
        set_handlers: function() { throw "Not implemented" },
373
        update_layout: function() { throw "Not implemented" },
374
        post_update_vm: function(vm) { throw "Not implemented" },
375
        update_details: function(vm) {},
376
        
377
        // remove vm
378
        remove_vm: function(vm) {
379
            // FIXME: some kind of transiton ??? effect maybe ???
380
            this.vm(vm).remove();
381
            this.post_remove_vm(vm);
382
            if (hasKey.call(this._vm_els, vm.id)) {
383
                delete this._vm_els[vm.id];
384
            }
385
        },
386
        
387
        // remove all vms from view
388
        clear: function() {
389
            this.sel('vms').remove();
390
            this.__update_layout();
391
        },
392

    
393
        show: function() {
394
            views.VMListView.__super__.show.apply(this, arguments);
395
            if (storage.vms.length == 0) { this.hide() };
396
            if (!snf.config.update_hidden_views) {
397
                this.update_vms(storage.vms.models);
398
            }
399
        },
400

    
401
        // do update for provided vms, then update the view layout
402
        update_vms: function(vms) {
403
            if (!this.visible() && !snf.config.update_hidden_views) { return };
404

    
405
            _.each(vms, _.bind(function(vm){
406
                // vm will be removed
407
                // no need to update
408
                if (vm.get("status") == "DELETED") {
409
                    return;
410
                }
411

    
412
                // this won't add it additional times
413
                this.add(vm);
414
                this.update_vm(vm);
415
            }, this))
416
            
417
            // update view stuff
418
            this.__update_layout();
419
        },
420
        
421
        update_toggles_visibility: function(vm) {
422
          if (vm.is_building() || vm.in_error_state() || vm.get("status") == "DESTROY") {
423
            this.vm(vm).find(".cont-toggler-wrapper.ips").addClass("disabled");
424
          } else {
425
            this.vm(vm).find(".cont-toggler-wrapper.ips").removeClass("disabled");
426
          }
427
        },
428

    
429
        // update ui for the given vm
430
        update_vm: function(vm) {
431
            // do not update deleted state vms
432
            if (!vm || vm.get("status") == 'DELETED') { return };
433
            this.check_vm_container(vm);
434

    
435
            this.update_details(vm);
436
            this.update_transition_state(vm);
437
            this.update_toggles_visibility(vm);
438

    
439
            if (this.action_views) {
440
                this.action_views[vm.id].update();
441
                this.action_views[vm.id].update_layout();
442
            }
443
            
444
            var el = this.vm(vm);
445
            if (vm.can_resize()) {
446
              el.addClass("can-resize");
447
            } else {
448
              el.removeClass("can-resize");
449
            }
450

    
451
            if (vm.get('suspended')) {
452
              el.addClass("suspended");
453
            } else {
454
              el.removeClass("suspended");
455
            }
456

    
457
            try {
458
                this.post_update_vm(vm);
459
            } catch (err) {};
460
        },
461

    
462
        // check if vm is placed properly within the view
463
        // container (e.g. some views might have different
464
        // containers for terminated or running machines
465
        check_vm_container: function(vm){
466
            var el = this.vm(vm);
467
            if (!el.length) { return };
468
            var self = this;
469
            var selector = vm.is_active() ? 'vm_cont_active' : 'vm_cont_terminated';
470
            if (el.parent()[0] != this.sel(selector)[0]) {
471
                var cont = this.sel(selector);
472
                var self = this;
473

    
474
                el.hide().appendTo(cont).fadeIn(300);
475
                $(window).trigger('resize');
476

    
477
                //el.fadeOut(200, function() {
478
                    //el.appendTo(cont); 
479
                    //el.fadeIn(200);
480
                    //self.sel(selector).show(function(){
481
                        //$(window).trigger("resize");
482
                    //});
483
                //});
484
            }
485
        },
486

    
487
        __update_layout: function() {
488
            this.update_layout();
489
        },
490
        
491
        // append handlers for vm specific events
492
        __set_vm_handlers: function(vm) {
493
            // show transition on vm status transit
494
            vm.bind('transition', _.bind(function(){this.show_transition(vm)}, this));
495
            this.set_vm_handlers(vm);
496
        },
497
        
498
        // is vm in transition ??? show the progress spinner
499
        update_transition_state: function(vm) {
500
            if (vm.in_transition() && !vm.has_pending_action()){
501
                this.sel('vm_spinner', vm.id).show();
502
            } else {
503
                this.sel('vm_spinner', vm.id).hide();
504
            }
505
        },
506
        
507
        show_indicator: function(vm, action) {
508
            var action = action || vm.pending_action;
509
            this.sel('vm_wave', vm.id).hide();
510
            this.sel('vm_spinner', vm.id).hide();
511
            this.vm(vm).find(".action-indicator").removeClass().addClass(action + " action-indicator").show();
512
        },
513

    
514
        hide_indicator: function(vm) {
515
            this.vm(vm).find(".action-indicator").removeClass().addClass("action-indicator").hide();
516
            this.update_transition_state(vm);
517
        },
518

    
519
        // display transition animations
520
        show_transition: function(vm) {
521
            var wave = this.sel('vm_wave', vm.id);
522
            if (!wave || !wave.length) { return }
523

    
524
            var src = wave.attr('src');
525
            // change src to force gif play from the first frame
526
            // animate for 500 ms then hide
527
            wave.attr('src', "").show();
528
            wave.attr('src', src).fadeIn(200).delay(700).fadeOut(300, function() {
529
                wave.hide();
530
            });
531
        },
532

    
533
        connect_to_console: function(vm) {
534
            // It seems that Safari allows popup windows only if the window.open
535
            // call is made within an html element click event context. 
536
            // Otherwise its behaviour is based on "Block Pop-Up Windows" 
537
            // setting, which when enabled no notification appears for the user. 
538
            // Since there is no easy way to check for the setting value we use
539
            // async:false for the action call so that action success handler 
540
            // which opens the new window is called inside the click event 
541
            // context.
542
            var use_async = true;
543
            if ($.client.browser == "Safari") {
544
                use_async = false;
545
            }
546

    
547
            vm.call("console", function(console_data) {
548
                var url = vm.get_console_url(console_data);
549
                snf.util.open_window(url, "VM_" + vm.get("id") + "_CONSOLE", {'scrollbars': 1, 'fullscreen': 0});
550
            }, undefined, {async: use_async});
551
        }
552

    
553
    });
554
    
555
    // empty message view (just a wrapper to the element containing 
556
    // the empty information message)
557
    views.EmptyView = views.View.extend({
558
        el: '#emptymachineslist'
559
    })
560

    
561
    views.VMActionsView = views.View.extend({
562
        
563
        initialize: function(vm, parent, el, hide) {
564
            this.hide = hide || false;
565
            this.view = parent;
566
            this.vm = vm;
567
            this.vm_el = el;
568
            this.el = $("#" + parent.view_id + "-actions-" + vm.id);
569
            this.all_action_names = _.keys(views.VMActionsView.STATUS_ACTIONS);
570
            
571
            // state params
572
            this.selected_action = false;
573

    
574
            _.bindAll(this);
575
            window.acts = this;
576
            this.view_id = "vm_" + vm.id + "_actions";
577
            views.VMActionsView.__super__.initialize.call(this);
578

    
579
            this.hovered = false;
580
            this.set_hover_handlers();
581
        },
582

    
583
        action: function(name) {
584
            return $(this.el).find(".action-container." + name);
585
        },
586

    
587
        action_link: function(name) {
588
            return this.action(name).find("a");
589
        },
590
        
591
        action_confirm_cont: function(name) {
592
            return this.action_confirm(name).parent();
593
        },
594

    
595
        action_confirm: function(name) {
596
            return this.action(name).find("button.yes");
597
        },
598

    
599
        action_cancel: function(name) {
600
            return this.action(name).find("button.no");
601
        },
602

    
603
        hide_actions: function() {
604
            $(this.el).find("a").css("visibility", "hidden");
605
        },
606
        
607
        set_can_start: function() {
608
          var el = $(this.el).find("a.action-start").parent();
609
          el.removeClass("disabled-visible");
610
        },
611

    
612
        set_cannot_start: function() {
613
          var el = $(this.el).find("a.action-start").parent();
614
          el.addClass("disabled-visible")
615
        },
616

    
617
        // update the actions layout, depending on the selected actions
618
        update_layout: function() {
619
            
620
            if (this.vm.get('status') == 'STOPPED') {
621
              if (this.vm.can_start()) {
622
                this.set_can_start();
623
              } else {
624
                this.set_cannot_start();
625
              }
626
            }
627

    
628
            if (!this.vm_handlers_initialized) {
629
                this.vm = storage.vms.get(this.vm.id);
630
                this.init_vm_handlers();
631
            }
632

    
633
            if (!this.vm) { return }
634
            
635
            if (!this.hovered && !this.vm.has_pending_action() && this.hide && !this.vm.action_error) { 
636
                this.el.hide();
637
                this.view.hide_indicator(this.vm);
638
                return 
639
            };
640

    
641
            if (!this.el.is(":visible") && !this.hide) { return };
642
            if (!this.handlers_initialized) { this.set_handlers(); }
643

    
644

    
645
            // update selected action
646
            if (this.vm.pending_action) {
647
                this.selected_action = this.vm.pending_action;
648
            } else {
649
                this.selected_action = false;
650
            }
651
            
652
            // vm actions tha can be performed
653
            var actions = this.vm.get_available_actions();
654
            
655
            // had pending action but actions changed and now selected action is
656
            // not available, hide it from user
657
            if (this.selected_action && actions.indexOf(this.selected_action) == -1) {
658
                this.reset();
659
            }
660
            
661
            this.el.show();
662
            
663
            if ((this.selected_action || this.hovered) && !this.vm.action_error) {
664
                // show selected action
665
                $(this.el).show();
666
                $(this.el).find("a").css("visibility", "visible");
667
                // show action icon
668
                this.view.show_indicator(this.vm);
669
            } else {
670
                if (this.hide || this.vm.action_error) {
671
                    // view shows actions on machine hover
672
                    $(this.el).find("a").css("visibility", "hidden");
673
                } else {
674
                    if (!this.vm.action_error) {
675
                        // view shows actions always
676
                        $(this.el).find("a").css("visibility", "visible");
677
                        $(this.el).show();
678
                    }
679
                }
680
                
681
                this.view.hide_indicator(this.vm);
682
            }
683
                
684
            // update action link styles and shit
685
            _.each(models.VM.ACTIONS, function(action, index) {
686
                if (actions.indexOf(action) > -1) {
687
                    this.action(action).removeClass("disabled");
688
                    var inactive = models.VM.AVAILABLE_ACTIONS_INACTIVE[action];
689

    
690
                    if (inactive && !_.contains(inactive, this.vm.get('status'))) {
691
                      this.action(action).addClass("inactive");
692
                    } else {
693
                      this.action(action).removeClass("inactive");
694
                    }
695

    
696
                    if (this.selected_action == action) {
697
                        this.action_confirm_cont(action).css('display', 'block');
698
                        this.action_confirm(action).show();
699
                        this.action(action).removeClass("disabled");
700
                        this.action_link(action).addClass("selected");
701
                    } else {
702
                        this.action_confirm_cont(action).hide();
703
                        this.action_confirm(action).hide();
704
                        this.action_link(action).removeClass("selected");
705
                    }
706
                } else {
707
                    this.action().hide();
708
                    this.action(action).addClass("disabled");
709
                    this.action_confirm(action).hide();
710
                }
711
            }, this);
712
        },
713
        
714
        init_vm_handlers: function() {
715
            try {
716
                this.vm.unbind("action:fail", this.update_layout)
717
                this.vm.unbind("action:fail:reset", this.update_layout)
718
            } catch (err) { console.log("Error")};
719
            
720
            this.vm.bind("action:fail", this.update_layout)
721
            this.vm.bind("action:fail:reset", this.update_layout)
722

    
723
            this.vm_handlers_initialized = true;
724
        },
725
        
726
        set_hover_handlers: function() {
727
            // vm container hover (icon view)
728
            this.view.vm(this.vm).hover(_.bind(function() {
729
                this.hovered = true;
730
                this.update_layout();
731

    
732
            }, this),  _.bind(function() {
733
                this.hovered = false;
734
                this.update_layout();
735
            }, this));
736
        },
737

    
738
        // bind event handlers
739
        set_handlers: function() {
740
            var self = this;
741
            var vm = this.vm;
742
            
743
            // initial hide
744
            if (this.hide) { $(this.el).hide() };
745
            
746
            if (this.$('.snapshot').length) {
747
              this.$('.snapshot').click(_.bind(function() {
748
                synnefo.ui.main.create_snapshot_view.show(this.vm);
749
              }, this));
750
            }
751
            // action links events
752
            _.each(models.VM.ACTIONS, function(action) {
753
                var action = action;
754
                // indicator hovers
755
                this.view.vm(this.vm).find(".action-container."+action+" a").hover(function() {
756
                    self.view.show_indicator(self.vm, action);
757
                }, function() {
758
                    // clear or show selected action indicator
759
                    if (self.vm.pending_action) {
760
                        self.view.show_indicator(self.vm);
761
                    } else {
762
                        self.view.hide_indicator(self.vm);
763
                    }
764
                })
765
                
766
                // action links click events
767
                $(this.el).find(".action-container."+action+" a").click(function(ev) {
768
                    ev.preventDefault();
769
                    if (action == "start" && !self.vm.can_start() && !vm.in_error_state()) {
770
                        ui.main.vm_resize_view.show_with_warning(self.vm);
771
                        return;
772
                    }
773

    
774
                    if (action == "resize") {
775
                        ui.main.vm_resize_view.show(self.vm);
776
                        return;
777
                    } else {
778
                        self.set(action);
779
                    }
780
                }).data("action", action);
781

    
782
                // confirms
783
                $(this.el).find(".action-container."+action+" button.no").click(function(ev) {
784
                    ev.preventDefault();
785
                    self.reset();
786
                });
787

    
788
                // cancels
789
                $(this.el).find(".action-container."+action+" button.yes").click(function(ev) {
790
                    ev.preventDefault();
791
                    // override console
792
                    // ui needs to act (open the console window)
793
                    if (action == "console") {
794
                        self.view.connect_to_console(self.vm);
795
                    } else {
796
                        self.vm.call(action);
797
                    }
798
                    self.reset();
799
                });
800
            }, this);
801

    
802
            this.handlers_initialized = true;
803
        },
804
        
805
        // reset actions
806
        reset: function() {
807
            var prev_action = this.selected_action;
808
            this.selected_action = false;
809
            this.vm.clear_pending_action();
810
            this.trigger("change", {'action': prev_action, 'vm': this.vm, 'view': this, remove: true});
811
            this.trigger("remove", {'action': prev_action, 'vm': this.vm, 'view': this, remove: true});
812
        },
813
        
814
        // set selected action
815
        set: function(action_name) {
816
            if (action_name == "snapshot") { return }
817
            this.selected_action = action_name;
818
            this.vm.update_pending_action(this.selected_action);
819
            this.view.vm(this.vm).find(".action-indicator").show().removeClass().addClass(action_name + " action-indicator");
820
            this.trigger("change", {'action': this.selected_action, 'vm': this.vm, 'view': this});
821
        },
822

    
823
        update: function() {
824
        }
825
    })
826

    
827

    
828
    views.VMActionsView.STATUS_ACTIONS = { 
829
        'reboot':        ['UNKOWN', 'ACTIVE', 'REBOOT'],
830
        'shutdown':      ['UNKOWN', 'ACTIVE', 'REBOOT'],
831
        'console':       ['ACTIVE'],
832
        'start':         ['UNKOWN', 'STOPPED'],
833
        'resize':        ['UNKOWN', 'ACTIVE', 'STOPPED', 'REBOOT', 'ERROR', 'BUILD'],
834
        'snapshot':      ['ACTIVE', 'STOPPED'],
835
        'destroy':       ['UNKOWN', 'ACTIVE', 'STOPPED', 'REBOOT', 'ERROR', 'BUILD']
836
    };
837

    
838
    // UI helpers
839
    var uihelpers = snf.ui.helpers = {};
840
    
841
    // OS icon helpers
842
    var os_icon = uihelpers.os_icon = function(os) {
843
        var icons = window.os_icons;
844
        if (!icons) { return "unknown" }
845
        if (icons.indexOf(os) == -1) {
846
            os = "unknown";
847
        }
848
        return os;
849
    }
850

    
851
    var os_icon_path = uihelpers.os_icon_path = function(os, size, active) {
852
        size = size || "small";
853
        if (active == undefined) { active = true };
854

    
855
        var icon = os_icon(os);
856
        if (active) {
857
            icon = icon + "-on";
858
        } else {
859
            icon = icon + "-off";
860
        }
861

    
862
        return (snf.config.machines_icons_url + "{0}/{1}.png").format(size, icon)
863
    }
864

    
865
    var os_icon_tag = uihelpers.os_icon_tag = function (os, size, active, attrs) {
866
        attrs = attrs || {};
867
        return '<img src="{0}" />'.format(os_icon_path(os, size, active));
868
    }
869

    
870
    // VM Icon helpers
871
    //
872
    // identify icon
873
    var vm_icon = uihelpers.vm_icon = function(vm) {
874
        return os_icon(vm.get_os());
875
    }
876
    
877
    // get icon url
878
    var vm_icon_path = uihelpers.vm_icon_path = function(vm, size) {
879
        return os_icon_path(vm.get_os(), size, vm.is_active());
880
    }
881
    
882
    // get icon IMG tag
883
    var vm_icon_tag = uihelpers.vm_icon_tag = function (vm, size, attrs) {
884
       return os_icon_tag(vm.get_os(), size, vm.is_active(), attrs);
885
    }
886
    
887

    
888
    snf.ui = _.extend(snf.ui, bb.Events);
889
    snf.ui.trigger_error = function(code, msg, error, extra) {
890
        if (msg.match(/Script error/i)) {
891
          // No usefull information to display in this case. Plus it's an
892
          // exception that probably doesn't affect our app.
893
          return 0;
894
        }
895
        snf.ui.trigger("error", { code:code, msg:msg, error:error, extra:extra || {} });
896
    };
897
    
898
    views.VMPortView = views.ext.ModelView.extend({
899
      tpl: '#vm-port-view-tpl',
900
      classes: 'port-item clearfix',
901
      
902
      update_in_progress: function() {
903
        if (this.model.get("in_progress_no_vm")) {
904
          this.set_in_progress();
905
        } else {
906
          this.unset_in_progress();
907
        }
908
      },
909

    
910
      set_in_progress: function() {
911
        this.el.find(".type").hide();
912
        this.el.find(".in-progress").removeClass("hidden").show();
913
      },
914

    
915
      unset_in_progress: function() {
916
        this.el.find(".type").show();
917
        this.el.find(".in-progress").hide();
918
      },
919

    
920
      disconnect_port: function(model, e) {
921
        e && e.stopPropagation();
922
        var network = this.model.get("network");
923
        this.model.actions.reset_pending();
924
        this.model.disconnect(_.bind(this.disconnect_port_complete, this));
925
      },
926

    
927
      disconnect_port_complete: function() {
928
      },
929

    
930
      get_network_name: function() {
931
        var network = this.model.get('network');
932
        var name = network && network.get('name');
933
        if (!name) {
934
          if (network && network.get('is_public')) {
935
            name = 'Internet'
936
          } else {
937
            name = '(no network name)'
938
          }
939
        }
940
        var truncate_length = this.parent_view.options.truncate || 40;
941
        name = synnefo.util.truncate(name, truncate_length, '...');
942
        return name || 'Loading...';
943
      },
944

    
945
      get_network_icon: function() {
946
        var ico;
947
        var network = this.model.get('network');
948
        if (network) {
949
          ico = network.get('is_public') ? 'internet-small.png' : 'network-small.png';
950
        } else {
951
          ico = 'network-small.png';
952
        }
953
        return synnefo.config.media_url + 'images/' + ico;
954
      },
955
    });
956
    
957
    views.VMPortListView = views.ext.CollectionView.extend({
958
      tpl: '#vm-port-list-view-tpl',
959
      model_view_cls: views.VMPortView
960
    });
961

    
962
    views.VMPortIpView = views.ext.ModelView.extend({
963
      tpl: '#vm-port-ip-tpl',
964
      css_classes: "clearfix"
965
    });
966

    
967
    views.VMPortIpsView = views.ext.CollectionView.extend({
968
      tpl: '#vm-port-ips-tpl',
969
      model_view_cls: views.VMPortIpView
970
    });
971

    
972
})(this);