Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (34.3 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({display_name:name, display_description:desc}, _.bind(function() {
127
              this.hide();
128
            }, this));
129
        },
130
        
131
        _default_values: function() {
132
          var d = new Date();
133
          var vmname = this.vm.get('name');
134
          var vmid = this.vm.id;
135
          var index = this.volume_index;
136
          var id = this.vm.id;
137
          var date = '{0}-{1}-{2} {3}:{4}:{5}'.format(
138
            d.getFullYear(), d.getMonth()+1, d.getDate(), d.getHours(), 
139
            d.getMinutes(), d.getSeconds());
140
          var name = "\"{0}\" snapshot [{1}]".format(vmname, date);
141
          if (this.volume) { name += "[volume:" + this.volume + "]" }
142
          var description = "Volume id: {0}".format(this.volume || 'primary');
143
          description += "\n" + "Server id: {0}".format(vmid);
144
          description += "\n" + "Server name: {0}".format(vmname);
145
          description += "\n" + "Timestamp: {0}".format(d.toJSON());
146

    
147
          return {
148
            'name': name,
149
            'description': description
150
          }
151
        },
152

    
153
        beforeOpen: function() {
154
            this.create_button.removeClass("in-progress")
155
            this.text.closest(".form-field").removeClass("error");
156
            var defaults = this._default_values();
157

    
158
            this.text.val(defaults.name);
159
            this.description.val(defaults.description);
160
            this.text.show();
161
            this.text.focus();
162
            this.description.show();
163
        },
164

    
165
        onOpen: function() {
166
            this.text.focus();
167
        }
168
    });
169

    
170
    // base class for views that contain/handle VMS
171
    views.VMListView = views.View.extend({
172

    
173
        // just a flag to identify that
174
        // views of this type handle vms
175
        vms_view: true,
176

    
177
        selectors: {},
178
        hide_actions: true,
179
        pane: "#machines-pane",
180
        metadata_view: undefined,
181

    
182
        initialize: function() {
183
            views.VMListView.__super__.initialize.call(this);
184
            this._vm_els = {};
185
            this.set_storage_handlers();
186
            this.set_handlers();
187
            this.vms_updated_handler();
188
            this.connect_overlay = new views.VMConnectView();
189
        },
190

    
191
        // display vm diagnostics detail overlay view, update based on
192
        // diagnostics_update_interval config value.
193
        show_build_details_for_vm: function(vm) {
194
            var cont = null;
195
            var success = function(data) {
196
                var message = "";
197
                var title = vm.get('name');
198
                var info = '<em>Status log messages:</em>';
199

    
200
                var list_el = $('<div class="diagnostics-list">');
201
                list_el.append('<div class="empty">No data available</div>');
202

    
203
                cont = list_el;
204
                var messages = _.clone(data);
205

    
206
                update_overlay_diagnostics(data, cont);
207
                synnefo.ui.main.details_view.show(title, info, cont);
208
            }
209

    
210
            var update_overlay_diagnostics = function(data) {
211
                var existing = cont.find(".msg-log-entry");
212
                var messages = _.clone(data);
213
                
214
                var to_append = messages.slice(0, messages.length - existing.length);
215
                to_append.reverse();
216

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

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

    
246
                    if (appending) { el.fadeIn(800); }
247
                });
248
                
249
                window.setTimeout(function(){
250
                    if (cont.is(":visible")) {
251
                        vm.get_diagnostics(update_overlay_diagnostics);
252
                    }
253
                }, synnefo.config.diagnostics_update_interval);
254
            }
255

    
256
            vm.get_diagnostics(success);
257
        },
258

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

    
275
            return ret;
276
        },
277
        
278
        // get vm model instance from DOM element
279
        vm_for_element: function(el) {
280
            return storage.vms.sel(this.vm_id_for_element(el));
281
        },
282
        
283

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

    
300
            if (method == "remove") {
301
                this.remove_vm(model)
302
                return;
303
            }
304
            
305
            this.update_vms(updated);
306
        },
307

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

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

    
336
        // get proper vm container
337
        get_vm_container: function(vm) {
338
            if (vm.is_active()) {
339
                return this.sel("vm_cont_active");
340
            } else {
341
                return this.sel("vm_cont_terminated");
342
            }
343
        },
344

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

    
356
            return this.vm(vm);
357
        },
358

    
359
        init_vm_view_handlers: function(vm) {
360
            var self = this;
361
            var el = this.vm(vm);
362

    
363
            // hidden feature, double click on indicators to display 
364
            // vm diagnostics.
365
            el.find(".indicators").bind("dblclick", function(){
366
                self.show_build_details_for_vm(vm);
367
            });
368

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

    
399
        show: function() {
400
            views.VMListView.__super__.show.apply(this, arguments);
401
            if (storage.vms.length == 0) { this.hide() };
402
            if (!snf.config.update_hidden_views) {
403
                this.update_vms(storage.vms.models);
404
            }
405
        },
406

    
407
        // do update for provided vms, then update the view layout
408
        update_vms: function(vms) {
409
            if (!this.visible() && !snf.config.update_hidden_views) { return };
410

    
411
            _.each(vms, _.bind(function(vm){
412
                // vm will be removed
413
                // no need to update
414
                if (vm.get("status") == "DELETED") {
415
                    return;
416
                }
417

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

    
435
        // update ui for the given vm
436
        update_vm: function(vm) {
437
            // do not update deleted state vms
438
            if (!vm || vm.get("status") == 'DELETED') { return };
439
            this.check_vm_container(vm);
440

    
441
            this.update_details(vm);
442
            this.update_transition_state(vm);
443
            this.update_toggles_visibility(vm);
444

    
445
            if (this.action_views) {
446
                this.action_views[vm.id].update();
447
                this.action_views[vm.id].update_layout();
448
            }
449
            
450
            var el = this.vm(vm);
451
            if (vm.can_resize()) {
452
              el.addClass("can-resize");
453
            } else {
454
              el.removeClass("can-resize");
455
            }
456

    
457
            if (vm.get('suspended')) {
458
              el.addClass("suspended");
459
            } else {
460
              el.removeClass("suspended");
461
            }
462

    
463
            try {
464
                this.post_update_vm(vm);
465
            } catch (err) {};
466
        },
467

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

    
480
                el.hide().appendTo(cont).fadeIn(300);
481
                $(window).trigger('resize');
482

    
483
                //el.fadeOut(200, function() {
484
                    //el.appendTo(cont); 
485
                    //el.fadeIn(200);
486
                    //self.sel(selector).show(function(){
487
                        //$(window).trigger("resize");
488
                    //});
489
                //});
490
            }
491
        },
492

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

    
520
        hide_indicator: function(vm) {
521
            this.vm(vm).find(".action-indicator").removeClass().addClass("action-indicator").hide();
522
            this.update_transition_state(vm);
523
        },
524

    
525
        // display transition animations
526
        show_transition: function(vm) {
527
            var wave = this.sel('vm_wave', vm.id);
528
            if (!wave || !wave.length) { return }
529

    
530
            var src = wave.attr('src');
531
            // change src to force gif play from the first frame
532
            // animate for 500 ms then hide
533
            wave.attr('src', "").show();
534
            wave.attr('src', src).fadeIn(200).delay(700).fadeOut(300, function() {
535
                wave.hide();
536
            });
537
        },
538

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

    
553
            vm.call("console", function(console_data) {
554
                var url = vm.get_console_url(console_data);
555
                snf.util.open_window(url, "VM_" + vm.get("id") + "_CONSOLE", {'scrollbars': 1, 'fullscreen': 0});
556
            }, undefined, {async: use_async});
557
        }
558

    
559
    });
560
    
561
    // empty message view (just a wrapper to the element containing 
562
    // the empty information message)
563
    views.EmptyView = views.View.extend({
564
        el: '#emptymachineslist'
565
    })
566

    
567
    views.VMActionsView = views.View.extend({
568
        
569
        initialize: function(vm, parent, el, hide) {
570
            this.hide = hide || false;
571
            this.view = parent;
572
            this.vm = vm;
573
            this.vm_el = el;
574
            this.el = $("#" + parent.view_id + "-actions-" + vm.id);
575
            this.all_action_names = _.keys(views.VMActionsView.STATUS_ACTIONS);
576
            
577
            // state params
578
            this.selected_action = false;
579

    
580
            _.bindAll(this);
581
            window.acts = this;
582
            this.view_id = "vm_" + vm.id + "_actions";
583
            views.VMActionsView.__super__.initialize.call(this);
584

    
585
            this.hovered = false;
586
            this.set_hover_handlers();
587
        },
588

    
589
        action: function(name) {
590
            return $(this.el).find(".action-container." + name);
591
        },
592

    
593
        action_link: function(name) {
594
            return this.action(name).find("a");
595
        },
596
        
597
        action_confirm_cont: function(name) {
598
            return this.action_confirm(name).parent();
599
        },
600

    
601
        action_confirm: function(name) {
602
            return this.action(name).find("button.yes");
603
        },
604

    
605
        action_cancel: function(name) {
606
            return this.action(name).find("button.no");
607
        },
608

    
609
        hide_actions: function() {
610
            $(this.el).find("a").css("visibility", "hidden");
611
        },
612
        
613
        set_can_start: function() {
614
          var el = $(this.el).find("a.action-start").parent();
615
          el.removeClass("disabled-visible");
616
        },
617

    
618
        set_cannot_start: function() {
619
          var el = $(this.el).find("a.action-start").parent();
620
          el.addClass("disabled-visible")
621
        },
622

    
623
        // update the actions layout, depending on the selected actions
624
        update_layout: function() {
625
            
626
            if (this.vm.get('status') == 'STOPPED') {
627
              if (this.vm.can_start()) {
628
                this.set_can_start();
629
              } else {
630
                this.set_cannot_start();
631
              }
632
            }
633

    
634
            if (!this.vm_handlers_initialized) {
635
                this.vm = storage.vms.get(this.vm.id);
636
                this.init_vm_handlers();
637
            }
638

    
639
            if (!this.vm) { return }
640
            
641
            if (!this.hovered && !this.vm.has_pending_action() && this.hide && !this.vm.action_error) { 
642
                this.el.hide();
643
                this.view.hide_indicator(this.vm);
644
                return 
645
            };
646

    
647
            if (!this.el.is(":visible") && !this.hide) { return };
648
            if (!this.handlers_initialized) { this.set_handlers(); }
649

    
650

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

    
696
                    if (inactive && !_.contains(inactive, this.vm.get('status'))) {
697
                      this.action(action).addClass("inactive");
698
                    } else {
699
                      this.action(action).removeClass("inactive");
700
                    }
701

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

    
729
            this.vm_handlers_initialized = true;
730
        },
731
        
732
        set_hover_handlers: function() {
733
            // vm container hover (icon view)
734
            this.view.vm(this.vm).hover(_.bind(function() {
735
                this.hovered = true;
736
                this.update_layout();
737

    
738
            }, this),  _.bind(function() {
739
                this.hovered = false;
740
                this.update_layout();
741
            }, this));
742
        },
743

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

    
780
                    if (action == "resize") {
781
                        ui.main.vm_resize_view.show(self.vm);
782
                        return;
783
                    } else {
784
                        self.set(action);
785
                    }
786
                }).data("action", action);
787

    
788
                // confirms
789
                $(this.el).find(".action-container."+action+" button.no").click(function(ev) {
790
                    ev.preventDefault();
791
                    self.reset();
792
                });
793

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

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

    
829
        update: function() {
830
        }
831
    })
832

    
833

    
834
    views.VMActionsView.STATUS_ACTIONS = { 
835
        'reboot':        ['UNKOWN', 'ACTIVE', 'REBOOT'],
836
        'shutdown':      ['UNKOWN', 'ACTIVE', 'REBOOT'],
837
        'console':       ['ACTIVE'],
838
        'start':         ['UNKOWN', 'STOPPED'],
839
        'resize':        ['UNKOWN', 'ACTIVE', 'STOPPED', 'REBOOT', 'ERROR', 'BUILD'],
840
        'snapshot':      ['ACTIVE', 'STOPPED'],
841
        'destroy':       ['UNKOWN', 'ACTIVE', 'STOPPED', 'REBOOT', 'ERROR', 'BUILD']
842
    };
843

    
844
    // UI helpers
845
    var uihelpers = snf.ui.helpers = {};
846
    
847
    // OS icon helpers
848
    var os_icon = uihelpers.os_icon = function(os) {
849
        var icons = window.os_icons;
850
        if (!icons) { return "unknown" }
851
        if (icons.indexOf(os) == -1) {
852
            os = "unknown";
853
        }
854
        return os;
855
    }
856

    
857
    var os_icon_path = uihelpers.os_icon_path = function(os, size, active) {
858
        size = size || "small";
859
        if (active == undefined) { active = true };
860

    
861
        var icon = os_icon(os);
862
        if (active) {
863
            icon = icon + "-on";
864
        } else {
865
            icon = icon + "-off";
866
        }
867

    
868
        return (snf.config.machines_icons_url + "{0}/{1}.png").format(size, icon)
869
    }
870

    
871
    var os_icon_tag = uihelpers.os_icon_tag = function (os, size, active, attrs) {
872
        attrs = attrs || {};
873
        return '<img src="{0}" />'.format(os_icon_path(os, size, active));
874
    }
875

    
876
    // VM Icon helpers
877
    //
878
    // identify icon
879
    var vm_icon = uihelpers.vm_icon = function(vm) {
880
        return os_icon(vm.get_os());
881
    }
882
    
883
    // get icon url
884
    var vm_icon_path = uihelpers.vm_icon_path = function(vm, size) {
885
        return os_icon_path(vm.get_os(), size, vm.is_active());
886
    }
887
    
888
    // get icon IMG tag
889
    var vm_icon_tag = uihelpers.vm_icon_tag = function (vm, size, attrs) {
890
       return os_icon_tag(vm.get_os(), size, vm.is_active(), attrs);
891
    }
892
    
893

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

    
916
      set_in_progress: function() {
917
        this.el.find(".type").hide();
918
        this.el.find(".in-progress").removeClass("hidden").show();
919
      },
920

    
921
      unset_in_progress: function() {
922
        this.el.find(".type").show();
923
        this.el.find(".in-progress").hide();
924
      },
925

    
926
      disconnect_port: function(model, e) {
927
        e && e.stopPropagation();
928
        var network = this.model.get("network");
929
        this.model.actions.reset_pending();
930
        this.model.disconnect(_.bind(this.disconnect_port_complete, this));
931
      },
932

    
933
      disconnect_port_complete: function() {
934
      },
935

    
936
      get_network_name: function() {
937
        var network = this.model.get('network');
938
        var name = network && network.get('name');
939
        if (!name) {
940
          if (network && network.get('is_public')) {
941
            name = 'Internet'
942
          } else {
943
            name = '(no network name)'
944
          }
945
        }
946
        var truncate_length = this.parent_view.options.truncate || 40;
947
        name = synnefo.util.truncate(name, truncate_length, '...');
948
        return name || 'Loading...';
949
      },
950

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

    
968
    views.VMPortIpView = views.ext.ModelView.extend({
969
      tpl: '#vm-port-ip-tpl',
970
      css_classes: "clearfix"
971
    });
972

    
973
    views.VMPortIpsView = views.ext.CollectionView.extend({
974
      tpl: '#vm-port-ips-tpl',
975
      model_view_cls: views.VMPortIpView
976
    });
977

    
978
})(this);