Index: src/wp-includes/js/mce-view.js
===================================================================
--- src/wp-includes/js/mce-view.js	(revision 31485)
+++ src/wp-includes/js/mce-view.js	(working copy)
@@ -1,279 +1,23 @@
 /* global tinymce */
-/**
+
+/*
+ * The TinyMCE view API.
+ *
  * Note: this API is "experimental" meaning that it will probably change
  * in the next few releases based on feedback from 3.9.0.
  * If you decide to use it, please follow the development closely.
  */
-
-// Ensure the global `wp` object exists.
-window.wp = window.wp || {};
-
 ( function( $ ) {
 	'use strict';
 
 	var views = {},
 		instances = {},
-		media = wp.media,
-		mediaWindows = [],
-		windowIdx = 0,
-		waitInterval = 50,
-		viewOptions = ['encodedText'];
+		viewOptions = [ 'encodedText' ];
 
-	// Create the `wp.mce` object if necessary.
+	window.wp = window.wp || {};
 	wp.mce = wp.mce || {};
 
 	/**
-	 * wp.mce.View
-	 *
-	 * A Backbone-like View constructor intended for use when rendering a TinyMCE View. The main difference is
-	 * that the TinyMCE View is not tied to a particular DOM node.
-	 *
-	 * @param {Object} [options={}]
-	 */
-	wp.mce.View = function( options ) {
-		options = options || {};
-		this.type = options.type;
-		_.extend( this, _.pick( options, viewOptions ) );
-		this.initialize.apply( this, arguments );
-	};
-
-	_.extend( wp.mce.View.prototype, {
-		initialize: function() {},
-		getHtml: function() {
-			return '';
-		},
-		loadingPlaceholder: function() {
-			return '' +
-				'<div class="loading-placeholder">' +
-					'<div class="dashicons dashicons-admin-media"></div>' +
-					'<div class="wpview-loading"><ins></ins></div>' +
-				'</div>';
-		},
-		render: function( force ) {
-			if ( force || ! this.rendered() ) {
-				this.unbind();
-
-				this.setContent(
-					'<p class="wpview-selection-before">\u00a0</p>' +
-					'<div class="wpview-body" contenteditable="false">' +
-						'<div class="toolbar mce-arrow-down">' +
-							( _.isFunction( views[ this.type ].edit ) ? '<div class="dashicons dashicons-edit edit"></div>' : '' ) +
-							'<div class="dashicons dashicons-no remove"></div>' +
-						'</div>' +
-						'<div class="wpview-content wpview-type-' + this.type + '">' +
-							( this.getHtml() || this.loadingPlaceholder() ) +
-						'</div>' +
-						( this.overlay ? '<div class="wpview-overlay"></div>' : '' ) +
-					'</div>' +
-					'<p class="wpview-selection-after">\u00a0</p>',
-					'wrap'
-				);
-
-				$( this ).trigger( 'ready' );
-
-				this.rendered( true );
-			}
-		},
-		unbind: function() {},
-		getEditors: function( callback ) {
-			var editors = [];
-
-			_.each( tinymce.editors, function( editor ) {
-				if ( editor.plugins.wpview ) {
-					if ( callback ) {
-						callback( editor );
-					}
-
-					editors.push( editor );
-				}
-			}, this );
-
-			return editors;
-		},
-		getNodes: function( callback ) {
-			var nodes = [],
-				self = this;
-
-			this.getEditors( function( editor ) {
-				$( editor.getBody() )
-				.find( '[data-wpview-text="' + self.encodedText + '"]' )
-				.each( function ( i, node ) {
-					if ( callback ) {
-						callback( editor, node, $( node ).find( '.wpview-content' ).get( 0 ) );
-					}
-
-					nodes.push( node );
-				} );
-			} );
-
-			return nodes;
-		},
-		setContent: function( html, option ) {
-			this.getNodes( function ( editor, node, content ) {
-				var el = ( option === 'wrap' || option === 'replace' ) ? node : content,
-					insert = html;
-
-				if ( _.isString( insert ) ) {
-					insert = editor.dom.createFragment( insert );
-				}
-
-				if ( option === 'replace' ) {
-					editor.dom.replace( insert, el );
-				} else {
-					el.innerHTML = '';
-					el.appendChild( insert );
-				}
-			} );
-		},
-		/* jshint scripturl: true */
-		setIframes: function ( head, body ) {
-			var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
-				importStyles = this.type === 'video' || this.type === 'audio' || this.type === 'playlist';
-
-			if ( head || body.indexOf( '<script' ) !== -1 ) {
-				this.getNodes( function ( editor, node, content ) {
-					var dom = editor.dom,
-						styles = '',
-						bodyClasses = editor.getBody().className || '',
-						iframe, iframeDoc, i, resize;
-
-					content.innerHTML = '';
-					head = head || '';
-
-					if ( importStyles ) {
-						if ( ! wp.mce.views.sandboxStyles ) {
-							tinymce.each( dom.$( 'link[rel="stylesheet"]', editor.getDoc().head ), function( link ) {
-								if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
-									link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
-
-									styles += dom.getOuterHTML( link ) + '\n';
-								}
-							});
-
-							wp.mce.views.sandboxStyles = styles;
-						} else {
-							styles = wp.mce.views.sandboxStyles;
-						}
-					}
-
-					// Seems Firefox needs a bit of time to insert/set the view nodes, or the iframe will fail
-					// especially when switching Text => Visual.
-					setTimeout( function() {
-						iframe = dom.add( content, 'iframe', {
-							src: tinymce.Env.ie ? 'javascript:""' : '',
-							frameBorder: '0',
-							allowTransparency: 'true',
-							scrolling: 'no',
-							'class': 'wpview-sandbox',
-							style: {
-								width: '100%',
-								display: 'block'
-							}
-						} );
-
-						iframeDoc = iframe.contentWindow.document;
-
-						iframeDoc.open();
-						iframeDoc.write(
-							'<!DOCTYPE html>' +
-							'<html>' +
-								'<head>' +
-									'<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
-									head +
-									styles +
-									'<style>' +
-										'html {' +
-											'background: transparent;' +
-											'padding: 0;' +
-											'margin: 0;' +
-										'}' +
-										'body#wpview-iframe-sandbox {' +
-											'background: transparent;' +
-											'padding: 1px 0 !important;' +
-											'margin: -1px 0 0 !important;' +
-										'}' +
-										'body#wpview-iframe-sandbox:before,' +
-										'body#wpview-iframe-sandbox:after {' +
-											'display: none;' +
-											'content: "";' +
-										'}' +
-									'</style>' +
-								'</head>' +
-								'<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
-									body +
-								'</body>' +
-							'</html>'
-						);
-						iframeDoc.close();
-
-						resize = function() {
-							var $iframe, iframeDocHeight;
-
-							// Make sure the iframe still exists.
-							if ( iframe.contentWindow ) {
-								$iframe = $( iframe );
-								iframeDocHeight = $( iframeDoc.body ).height();
-
-								if ( $iframe.height() !== iframeDocHeight ) {
-									$iframe.height( iframeDocHeight );
-									editor.nodeChanged();
-								}
-							}
-						};
-
-						if ( MutationObserver ) {
-							new MutationObserver( _.debounce( function() {
-								resize();
-							}, 100 ) )
-							.observe( iframeDoc.body, {
-								attributes: true,
-								childList: true,
-								subtree: true
-							} );
-						} else {
-							for ( i = 1; i < 6; i++ ) {
-								setTimeout( resize, i * 700 );
-							}
-						}
-
-						if ( importStyles ) {
-							editor.on( 'wp-body-class-change', function() {
-								iframeDoc.body.className = editor.getBody().className;
-							});
-						}
-					}, waitInterval );
-				});
-			} else {
-				this.setContent( body );
-			}
-		},
-		setError: function( message, dashicon ) {
-			this.setContent(
-				'<div class="wpview-error">' +
-					'<div class="dashicons dashicons-' + ( dashicon ? dashicon : 'no' ) + '"></div>' +
-					'<p>' + message + '</p>' +
-				'</div>'
-			);
-		},
-		rendered: function( value ) {
-			var notRendered;
-
-			this.getNodes( function( editor, node ) {
-				if ( value != null ) {
-					$( node ).data( 'rendered', value === true );
-				} else {
-					notRendered = notRendered || ! $( node ).data( 'rendered' );
-				}
-			} );
-
-			return ! notRendered;
-		}
-	} );
-
-	// take advantage of the Backbone extend method
-	wp.mce.View.extend = Backbone.View.extend;
-
-	/**
 	 * wp.mce.views
 	 *
 	 * A set of utilities that simplifies adding custom UI within a TinyMCE editor.
@@ -283,66 +27,65 @@
 	wp.mce.views = {
 
 		/**
-		 * wp.mce.views.register( type, view )
-		 *
 		 * Registers a new TinyMCE view.
 		 *
-		 * @param type
-		 * @param constructor
-		 *
+		 * @param {String} The view type.
+		 * @param {Object} Options.
 		 */
-		register: function( type, constructor ) {
-			var defaultConstructor = {
-					type: type,
-					View: {},
-					toView: function( content ) {
-						var match = wp.shortcode.next( this.type, content );
+		register: function( type, options ) {
+			if ( ! options.View ) {
+				options = { View: options };
 
-						if ( ! match ) {
-							return;
-						}
+				if ( options.View.toView ) {
+					options.toView = options.View.toView;
+					delete options.View.toView;
+				}
+			}
 
-						return {
-							index: match.index,
-							content: match.content,
-							options: {
-								shortcode: match.shortcode
-							}
-						};
+			options = _.defaults( options, {
+				type: type,
+				View: {},
+				toView: function( content ) {
+					var match = wp.shortcode.next( this.type, content );
+
+					if ( ! match ) {
+						return;
 					}
-				};
 
-			constructor = _.defaults( constructor, defaultConstructor );
-			constructor.View = wp.mce.View.extend( constructor.View );
+					return {
+						index: match.index,
+						content: match.content,
+						options: {
+							shortcode: match.shortcode
+						}
+					};
+				}
+			} );
 
-			views[ type ] = constructor;
-		},
+			options.View = wp.mce.View.extend( options.View );
 
-		/**
-		 * wp.mce.views.get( id )
-		 *
-		 * Returns a TinyMCE view constructor.
-		 *
-		 * @param type
-		 */
-		get: function( type ) {
-			return views[ type ];
+			views[ type ] = options;
 		},
 
 		/**
-		 * wp.mce.views.unregister( type )
-		 *
 		 * Unregisters a TinyMCE view.
 		 *
-		 * @param type
+		 * @param {String} The view type.
 		 */
 		unregister: function( type ) {
 			delete views[ type ];
 		},
 
 		/**
-		 * wp.mce.views.unbind( editor )
+		 * Returns a TinyMCE view constructor.
 		 *
+		 * @param {String} The view type.
+		 */
+		get: function( type ) {
+			return views[ type ];
+		},
+
+		/**
 		 * The editor DOM is being rebuilt, run cleanup.
 		 */
 		unbind: function() {
@@ -352,18 +95,18 @@
 		},
 
 		/**
-		 * toViews( content )
-		 * Scans a `content` string for each view's pattern, replacing any
-		 * matches with wrapper elements, and creates a new instance for
-		 * every match, which triggers the related data to be fetched.
+		 * Scans a given string for each view's pattern,
+		 * replacing any matches with markers,
+		 * and creates a new instance for every match,
+		 * which triggers the related data to be fetched.
 		 *
-		 * @param content
+		 * @param {String} String to scan.
 		 */
 		toViews: function( content ) {
 			var pieces = [ { content: content } ],
 				current;
 
-			_.each( views, function( view, viewType ) {
+			_.each( views, function( view, type ) {
 				current = pieces.slice();
 				pieces  = [];
 
@@ -379,17 +122,17 @@
 
 					// Iterate through the string progressively matching views
 					// and slicing the string as we go.
-					while ( remaining && (result = view.toView( remaining )) ) {
+					while ( remaining && ( result = view.toView( remaining ) ) ) {
 						// Any text before the match becomes an unprocessed piece.
 						if ( result.index ) {
-							pieces.push({ content: remaining.substring( 0, result.index ) });
+							pieces.push( { content: remaining.substring( 0, result.index ) } );
 						}
 
 						// Add the processed piece for the match.
-						pieces.push({
-							content: wp.mce.views.toView( viewType, result.content, result.options ),
+						pieces.push( {
+							content: wp.mce.views.toView( type, result.content, result.options ),
 							processed: true
-						});
+						} );
 
 						// Update the remaining content.
 						remaining = remaining.slice( result.index + result.content.length );
@@ -398,91 +141,81 @@
 					// There are no additional matches. If any content remains,
 					// add it as an unprocessed piece.
 					if ( remaining ) {
-						pieces.push({ content: remaining });
+						pieces.push( { content: remaining } );
 					}
-				});
-			});
+				} );
+			} );
 
-			return _.pluck( pieces, 'content' ).join('');
+			return _.pluck( pieces, 'content' ).join( '' );
 		},
 
 		/**
-		 * Create a placeholder for a particular view type
-		 *
-		 * @param viewType
-		 * @param text
-		 * @param options
+		 * Returns the marked text for a particular view type,
+		 * and creates a new instance for that view type if it does not exist.
+		 * The text will be returned unmarked if no view of that type is registered.
+		 *
+		 * @param {String} The view type.
+		 * @param {String} The textual representation of the view.
+		 * @param {Object} Options.
 		 *
+		 * @return {String} The markered text.
 		 */
-		toView: function( viewType, text, options ) {
-			var view = wp.mce.views.get( viewType ),
-				encodedText = window.encodeURIComponent( text ),
-				instance, viewOptions;
-
+		toView: function( type, text, options ) {
+			var view = this.get( type ),
+				encodedText = window.encodeURIComponent( text );
 
 			if ( ! view ) {
 				return text;
 			}
 
-			if ( ! wp.mce.views.getInstance( encodedText ) ) {
-				viewOptions = options;
-				viewOptions.type = viewType;
-				viewOptions.encodedText = encodedText;
-				instance = new view.View( viewOptions );
-				instances[ encodedText ] = instance;
+			if ( ! this.getInstance( encodedText ) ) {
+				instances[ encodedText ] = new view.View( _.extend( options, {
+					encodedText: encodedText,
+					type: type
+				} ) );
 			}
 
-			return wp.html.string({
-				tag: 'div',
-
-				attrs: {
-					'class': 'wpview-wrap',
-					'data-wpview-text': encodedText,
-					'data-wpview-type': viewType
-				},
-
-				content: '\u00a0'
-			});
+			return '<p data-wpview-marker="' + encodedText + '">' + text + '</p>';
 		},
 
 		/**
-		 * Refresh views after an update is made
+		 * Refresh views after an update is made.
 		 *
-		 * @param view {object} being refreshed
-		 * @param text {string} textual representation of the view
-		 * @param force {Boolean} whether to force rendering
+		 * @param {Object} The view to refresh.
+		 * @param {String} The textual representation of the view.
+		 * @param {Boolean} Whether or not to force rendering.
 		 */
 		refreshView: function( view, text, force ) {
-			var encodedText = window.encodeURIComponent( text ),
-				viewOptions,
-				result, instance;
-
-			instance = wp.mce.views.getInstance( encodedText );
-
-			if ( ! instance ) {
-				result = view.toView( text );
-				viewOptions = result.options;
-				viewOptions.type = view.type;
-				viewOptions.encodedText = encodedText;
-				instance = new view.View( viewOptions );
-				instances[ encodedText ] = instance;
+			var encodedText = encodeURIComponent( text );
+
+			if ( ! this.getInstance( encodedText ) ) {
+				instances[ encodedText ] = new view.View( _.extend( view.toView( text ).options, {
+					encodedText: encodedText,
+					type: view.type
+				} ) );
 			}
 
-			instance.render( force );
+			instances[ encodedText ].render( force );
 		},
 
+		/**
+		 * @param {String} The textual representation of the view, encoded.
+		 */
 		getInstance: function( encodedText ) {
 			return instances[ encodedText ];
 		},
 
+		getInstances: function() {
+			return instances;
+		},
+
 		/**
-		 * render( scope )
+		 * Renders any view instances.
 		 *
-		 * Renders any view instances inside a DOM node `scope`.
+		 * View instances are detected by the presence of markers.
+		 * To generate markers, pass your content through `toViews`.
 		 *
-		 * View instances are detected by the presence of wrapper elements.
-		 * To generate wrapper elements, pass your content through
-		 * `wp.mce.view.toViews( content )`.
+		 * @param {Boolean} Whether or not to force rendering.
 		 */
 		render: function( force ) {
 			_.each( instances, function( instance ) {
@@ -490,298 +223,579 @@
 			} );
 		},
 
-		edit: function( node ) {
-			var viewType = $( node ).data('wpview-type'),
-				view = wp.mce.views.get( viewType );
+		/**
+		 * @param {HTMLElement} A view node.
+		 */
+		edit: function( editor, node ) {
+			var instance = this.getInstance( $( node ).data( 'wpview-text' ) ),
+				view = wp.mce.views.get( instance.type ),
+				self = this;
 
-			if ( view ) {
+			if ( view && view.edit ) {
 				view.edit( node );
+			} else if ( instance && instance.edit ) {
+				instance.edit( decodeURIComponent( instance.encodedText ), function( text ) {
+					$( node ).data( 'rendered', false );
+					editor.dom.setAttrib( node, 'data-wpview-text', encodeURIComponent( text ) );
+					self.refreshView( view, text );
+				} );
 			}
 		}
 	};
 
-	wp.mce.views.register( 'gallery', {
-		View: {
-			template: media.template( 'editor-gallery' ),
-
-			// The fallback post ID to use as a parent for galleries that don't
-			// specify the `ids` or `include` parameters.
-			//
-			// Uses the hidden input on the edit posts page by default.
-			postID: $('#post_ID').val(),
+	/**
+	 * A Backbone-like View constructor intended for use when rendering a TinyMCE View. The main difference is
+	 * that the TinyMCE View is not tied to a particular DOM node.
+	 *
+	 * @param {Object} Options.
+	 */
+	wp.mce.View = function( options ) {
+		options = options || {};
+		this.type = options.type;
+		_.extend( this, _.pick( options, viewOptions ) );
+		this.initialize.apply( this, arguments );
+	};
 
-			initialize: function( options ) {
-				this.shortcode = options.shortcode;
-				this.fetch();
-			},
+	_.extend( wp.mce.View.prototype, {
 
-			fetch: function() {
-				var self = this;
+		/**
+		 * Whether or not to display a loader.
+		 *
+		 * @type {Boolean}
+		 */
+		loader: true,
 
-				this.attachments = wp.media.gallery.attachments( this.shortcode, this.postID );
-				this.dfd = this.attachments.more().done( function() {
-					self.render( true );
-				} );
-			},
+		/**
+		 * Runs after the view instance is created.
+		 */
+		initialize: function() {},
 
-			getHtml: function() {
-				var attrs = this.shortcode.attrs.named,
-					attachments = false,
-					options;
-
-				// Don't render errors while still fetching attachments
-				if ( this.dfd && 'pending' === this.dfd.state() && ! this.attachments.length ) {
-					return '';
-				}
-
-				if ( this.attachments.length ) {
-					attachments = this.attachments.toJSON();
-
-					_.each( attachments, function( attachment ) {
-						if ( attachment.sizes ) {
-							if ( attrs.size && attachment.sizes[ attrs.size ] ) {
-								attachment.thumbnail = attachment.sizes[ attrs.size ];
-							} else if ( attachment.sizes.thumbnail ) {
-								attachment.thumbnail = attachment.sizes.thumbnail;
-							} else if ( attachment.sizes.full ) {
-								attachment.thumbnail = attachment.sizes.full;
-							}
-						}
-					} );
-				}
+		/**
+		 * Retuns the HTML string to render in the view.
+		 *
+		 * @return {*}
+		 */
+		getHtml: function() {},
+
+		/**
+		 * Retuns the HTML string to render in the view.
+		 *
+		 * @param {Boolean} Whether or not to rerender.
+		 */
+		render: function( rerender ) {
+			var i = 0;
 
-				options = {
-					attachments: attachments,
-					columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns
-				};
+			// If there's nothing to render an no loader needs to be shown, stop.
+			if ( ! this.loader && ! this.getHtml() ) {
+				return;
+			}
+
+			// We're about to rerender all views of this instance, so unbind rendered views.
+			rerender && this.unbind();
+
+			// Replace any left over markers.
+			this.replaceMarkers();
 
-				return this.template( options );
+			if ( this.getHtml() ) {
+				this.setContent( this.getHtml(), function( editor, node ) {
+					$( node ).data( 'rendered', true );
+					this.bindNodes.apply( this, arguments );
+					i++;
+				}, rerender ? null : false );
+
+				// Use `bindNodes` if possible.
+				i && $( this ).trigger( 'ready' );
+			} else {
+				this.setLoader();
 			}
 		},
 
-		edit: function( node ) {
-			var gallery = wp.media.gallery,
-				self = this,
-				frame, data;
+		/**
+		 * Runs after a view is added to the DOM.
+		 *
+		 * @param {tinymce.Editor} The editor instance the view node is in.
+		 * @param {HTMLElement} The view node.
+		 * @param {HTMLElement} The view's content node.
+		 */
+		bindNodes: function() {},
 
-			data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
-			frame = gallery.edit( data );
+		/**
+		 * Runs before a view is removed from the DOM.
+		 */
+		unbind: function() {
+			this.getNodes( function() {
+				this.unbindNodes.apply( this, arguments );
+			}, true );
+		},
 
-			frame.state('gallery-edit').on( 'update', function( selection ) {
-				var shortcode = gallery.shortcode( selection ).string();
-				$( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
-				wp.mce.views.refreshView( self, shortcode, true );
-			});
+		/**
+		 * Runs before a view is removed from the DOM.
+		 *
+		 * @param {tinymce.Editor} The editor instance the view node is in.
+		 * @param {HTMLElement} The view node.
+		 * @param {HTMLElement} The view's content node.
+		 */
+		unbindNodes: function() {},
 
-			frame.on( 'close', function() {
-				frame.detach();
-			});
-		}
-	} );
+		/**
+		 * Gets all the TinyMCE editors that support views.
+		 *
+		 * @param {Function} A callback (optional).
+		 *
+		 * @return {tinymce.Editor[]} An array of TinyMCE editor instances.
+		 */
+		getEditors: function( callback ) {
+			var editors = [];
 
-	/**
-	 * These are base methods that are shared by the audio and video shortcode's MCE controller.
-	 *
-	 * @mixin
-	 */
-	wp.mce.av = {
-		View: {
-			overlay: true,
+			_.each( tinymce.editors, function( editor ) {
+				if ( editor.plugins.wpview ) {
+					editors.push( editor );
+					callback && callback.call( this, editor );
+				}
+			}, this );
 
-			action: 'parse-media-shortcode',
+			return editors;
+		},
 
-			initialize: function( options ) {
-				var self = this;
+		/**
+		 * Gets all the view nodes in each editor.
+		 *
+		 * @param {Function} A callback (optional).
+		 * @param {Boolean} Get (un)rendered nodes (optional).
+		 *
+		 * @return {HTMLElement[]} An array of view nodes.
+		 */
+		getNodes: function( callback, rendered ) {
+			var nodes = [];
 
-				this.shortcode = options.shortcode;
+			this.getEditors( function( editor ) {
+				var self = this;
 
-				_.bindAll( this, 'setIframes', 'setNodes', 'fetch', 'stopPlayers' );
-				$( this ).on( 'ready', this.setNodes );
+				$( editor.getBody() )
+					.find( '[data-wpview-text="' + self.encodedText + '"]' )
+					.filter( function() {
+						var data;
 
-				$( document ).on( 'media:edit', this.stopPlayers );
+						if ( rendered == null ) {
+							return true;
+						}
 
-				this.fetch();
+						data = $( this ).data( 'rendered' ) === true;
 
-				this.getEditors( function( editor ) {
-					editor.on( 'hide', function () {
-						mediaWindows = [];
-						windowIdx = 0;
-						self.stopPlayers();
+						return rendered ? data : ! data;
+					} )
+					.each( function ( i, node ) {
+						nodes.push( node );
+						callback && callback.call( self, editor, node, $( node ).find( '.wpview-content' ).get( 0 ) );
 					} );
-				});
-			},
+			} );
 
-			pauseOtherWindows: function ( win ) {
-				_.each( mediaWindows, function ( mediaWindow ) {
-					if ( mediaWindow.sandboxId !== win.sandboxId ) {
-						_.each( mediaWindow.mejs.players, function ( player ) {
-							player.pause();
-						} );
-					}
-				} );
-			},
+			return nodes;
+		},
 
-			iframeLoaded: function (win) {
-				return _.bind( function () {
-					var callback;
-					if ( ! win.mejs || _.isEmpty( win.mejs.players ) ) {
-						return;
-					}
+		/**
+		 * Gets all the markers in each editor.
+		 *
+		 * @param {Function} A callback (optional).
+		 *
+		 * @return {HTMLElement[]} An array of marker nodes.
+		 */
+		getMarkers: function( callback ) {
+			var markers = [];
 
-					win.sandboxId = windowIdx;
-					windowIdx++;
-					mediaWindows.push( win );
-
-					callback = _.bind( function () {
-						this.pauseOtherWindows( win );
-					}, this );
-
-					if ( ! _.isEmpty( win.mejs.MediaPluginBridge.pluginMediaElements ) ) {
-						_.each( win.mejs.MediaPluginBridge.pluginMediaElements, function ( mediaElement ) {
-							mediaElement.addEventListener( 'play', callback );
-						} );
-					}
+			this.getEditors( function( editor ) {
+				var self = this;
 
-					_.each( win.mejs.players, function ( player ) {
-						$( player.node ).on( 'play', callback );
-					}, this );
-				}, this );
-			},
-
-			listenToSandboxes: function () {
-				_.each( this.getNodes(), function ( node ) {
-					var win, iframe = $( '.wpview-sandbox', node ).get( 0 );
-					if ( iframe && ( win = iframe.contentWindow ) ) {
-						$( win ).load( _.bind( this.iframeLoaded( win ), this ) );
-					}
-				}, this );
-			},
+				$( editor.getBody() )
+					.find( '[data-wpview-marker="' + this.encodedText + '"]' )
+					.each( function( i, node ) {
+						markers.push( node );
+						callback && callback.call( self, editor, node );
+					} );
+			} );
 
-			deferredListen: function () {
-				window.setTimeout( _.bind( this.listenToSandboxes, this ), this.getNodes().length * waitInterval );
-			},
-
-			setNodes: function () {
-				if ( this.parsed ) {
-					this.setIframes( this.parsed.head, this.parsed.body );
-					this.deferredListen();
-				} else {
-					this.fail();
+			return markers;
+		},
+
+		/**
+		 * Replaces all markers with view nodes.
+		 */
+		replaceMarkers: function() {
+			this.getMarkers( function( editor, node ) {
+				if ( $( node ).text() !== decodeURIComponent( this.encodedText ) ) {
+					editor.dom.setAttrib( node, 'data-wpview-marker', null );
+					return;
 				}
-			},
 
-			fetch: function () {
-				var self = this;
+				editor.dom.replace(
+					editor.dom.createFragment(
+						'<div class="wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '">' +
+							'<p class="wpview-selection-before">\u00a0</p>' +
+							'<div class="wpview-body" contenteditable="false">' +
+								'<div class="toolbar mce-arrow-down">' +
+									( this.edit || views[ this.type ].edit ? '<div class="dashicons dashicons-edit edit"></div>' : '' ) +
+									'<div class="dashicons dashicons-no remove"></div>' +
+								'</div>' +
+								'<div class="wpview-content wpview-type-' + this.type + '"></div>' +
+								( this.overlay ? '<div class="wpview-overlay"></div>' : '' ) +
+							'</div>' +
+							'<p class="wpview-selection-after">\u00a0</p>' +
+						'</div>'
+					),
+					node
+				);
+			} );
+		},
 
-				wp.ajax.send( this.action, {
-					data: {
-						post_ID: $( '#post_ID' ).val() || 0,
-						type: this.shortcode.tag,
-						shortcode: this.shortcode.string()
-					}
-				} )
-				.done( function( response ) {
-					if ( response ) {
-						self.parsed = response;
-						self.setIframes( response.head, response.body );
-						self.deferredListen();
-					} else {
-						self.fail( true );
-					}
-				} )
-				.fail( function( response ) {
-					self.fail( response || true );
-				} );
-			},
+		/**
+		 * Removes all markers.
+		 */
+		removeMarkers: function() {
+			this.getMarkers( function( editor, node ) {
+				editor.dom.setAttrib( node, 'data-wpview-marker', null );
+			} );
+		},
+
+		/**
+		 * Gets all the markers in each editor.
+		 *
+		 * @param {(String|HTMLElement)} The content to set.
+		 * @param {Function} A callback (optional).
+		 * @param {Boolean} Only set for (un)rendered nodes (optional).
+		 */
+		setContent: function( content, callback, rendered ) {
+			if ( _.isObject( content ) && content.body.indexOf( '<script' ) !== -1 ) {
+				this.setIframes( content.head, content.body, callback, rendered );
+			} else if ( _.isString( content ) && content.indexOf( '<script' ) !== -1 ) {
+				this.setIframes( null, content, callback, rendered );
+			} else {
+				this.getNodes( function( editor, node, contentNode ) {
+					content = content.body || content;
+
+					contentNode.innerHTML = '';
+					contentNode.appendChild( _.isString( content ) ? editor.dom.createFragment( content ) : content );
+
+					callback && callback.apply( this, arguments );
+				}, rendered );
+			}
+		},
+
+		/**
+		 * Set an iframe as the view content.
+		 */
+		setIframes: function( head, body, callback, rendered ) {
+			var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
+				importStyles = this.type === 'video' || this.type === 'audio' || this.type === 'playlist';
+
+			this.getNodes( function( editor, node, content ) {
+				var dom = editor.dom,
+					styles = '',
+					bodyClasses = editor.getBody().className || '',
+					iframe, iframeDoc, i, resize;
+
+				content.innerHTML = '';
+				head = head || '';
+
+				if ( importStyles ) {
+					if ( ! wp.mce.views.sandboxStyles ) {
+						tinymce.each( dom.$( 'link[rel="stylesheet"]', editor.getDoc().head ), function( link ) {
+							if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
+								link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
 
-			fail: function( error ) {
-				if ( ! this.error ) {
-					if ( error ) {
-						this.error = error;
+								styles += dom.getOuterHTML( link ) + '\n';
+							}
+						});
+
+						wp.mce.views.sandboxStyles = styles;
 					} else {
-						return;
+						styles = wp.mce.views.sandboxStyles;
 					}
 				}
 
-				if ( this.error.message ) {
-					if ( ( this.error.type === 'not-embeddable' && this.type === 'embed' ) || this.error.type === 'not-ssl' ||
-						this.error.type === 'no-items' ) {
+				// Seems Firefox needs a bit of time to insert/set the view nodes,
+				// or the iframe will fail especially when switching Text => Visual.
+				setTimeout( function() {
+					iframe = dom.add( content, 'iframe', {
+						/* jshint scripturl: true */
+						src: tinymce.Env.ie ? 'javascript:""' : '',
+						frameBorder: '0',
+						allowTransparency: 'true',
+						scrolling: 'no',
+						'class': 'wpview-sandbox',
+						style: {
+							width: '100%',
+							display: 'block'
+						}
+					} );
 
-						this.setError( this.error.message, 'admin-media' );
-					} else {
-						this.setContent( '<p>' + this.original + '</p>', 'replace' );
-					}
-				} else if ( this.error.statusText ) {
-					this.setError( this.error.statusText, 'admin-media' );
-				} else if ( this.original ) {
-					this.setContent( '<p>' + this.original + '</p>', 'replace' );
-				}
-			},
-
-			stopPlayers: function( remove ) {
-				var rem = remove === 'remove';
-
-				this.getNodes( function( editor, node, content ) {
-					var p, win,
-						iframe = $( 'iframe.wpview-sandbox', content ).get(0);
+					iframeDoc = iframe.contentWindow.document;
 
-					if ( iframe && ( win = iframe.contentWindow ) && win.mejs ) {
-						// Sometimes ME.js may show a "Download File" placeholder and player.remove() doesn't exist there.
-						try {
-							for ( p in win.mejs.players ) {
-								win.mejs.players[p].pause();
+					iframeDoc.open();
 
-								if ( rem ) {
-									win.mejs.players[p].remove();
-								}
+					iframeDoc.write(
+						'<!DOCTYPE html>' +
+						'<html>' +
+							'<head>' +
+								'<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
+								head +
+								styles +
+								'<style>' +
+									'html {' +
+										'background: transparent;' +
+										'padding: 0;' +
+										'margin: 0;' +
+									'}' +
+									'body#wpview-iframe-sandbox {' +
+										'background: transparent;' +
+										'padding: 1px 0 !important;' +
+										'margin: -1px 0 0 !important;' +
+									'}' +
+									'body#wpview-iframe-sandbox:before,' +
+									'body#wpview-iframe-sandbox:after {' +
+										'display: none;' +
+										'content: "";' +
+									'}' +
+								'</style>' +
+							'</head>' +
+							'<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
+								body +
+							'</body>' +
+						'</html>'
+					);
+
+					iframeDoc.close();
+
+					resize = function() {
+						var $iframe, iframeDocHeight;
+
+						// Make sure the iframe still exists.
+						if ( iframe.contentWindow ) {
+							$iframe = $( iframe );
+							iframeDocHeight = $( iframeDoc.body ).height();
+
+							if ( $iframe.height() !== iframeDocHeight ) {
+								$iframe.height( iframeDocHeight );
+								editor.nodeChanged();
 							}
-						} catch( er ) {}
+						}
+					};
+
+					if ( MutationObserver ) {
+						new MutationObserver( _.debounce( function() {
+							resize();
+						}, 100 ) )
+						.observe( iframeDoc.body, {
+							attributes: true,
+							childList: true,
+							subtree: true
+						} );
+					} else {
+						for ( i = 1; i < 6; i++ ) {
+							setTimeout( resize, i * 700 );
+						}
 					}
-				});
-			},
 
-			unbind: function() {
-				this.stopPlayers( 'remove' );
-			}
+					if ( importStyles ) {
+						editor.on( 'wp-body-class-change', function() {
+							iframeDoc.body.className = editor.getBody().className;
+						} );
+					}
+				}, 50 );
+
+				callback && callback.apply( this, arguments );
+			}, rendered );
 		},
 
 		/**
-		 * Called when a TinyMCE view is clicked for editing.
-		 * - Parses the shortcode out of the element's data attribute
-		 * - Calls the `edit` method on the shortcode model
-		 * - Launches the model window
-		 * - Bind's an `update` callback which updates the element's data attribute
-		 *   re-renders the view
+		 * Set a loader.
+		 */
+		setLoader: function() {
+			this.setContent(
+				'<div class="loading-placeholder">' +
+					'<div class="dashicons dashicons-admin-media"></div>' +
+					'<div class="wpview-loading"><ins></ins></div>' +
+				'</div>'
+			);
+		},
+
+		/**
+		 * Set an error.
 		 *
-		 * @param {HTMLElement} node
+		 * @param {String} The error message to set.
+		 * @param {String} A dashicon ID (optional). {@link https://developer.wordpress.org/resource/dashicons/}
 		 */
-		edit: function( node ) {
-			var media = wp.media[ this.type ],
-				self = this,
-				frame, data, callback;
+		setError: function( message, dashicon ) {
+			this.setContent(
+				'<div class="wpview-error">' +
+					'<div class="dashicons dashicons-' + ( dashicon || 'no' ) + '"></div>' +
+					'<p>' + message + '</p>' +
+				'</div>'
+			);
+		}
+	} );
+
+	// Take advantage of the Backbone extend method.
+	wp.mce.View.extend = Backbone.View.extend;
+} )( jQuery );
+
+/*
+ * The WordPress core TinyMCE views.
+ * Views for the gallery, audio, video, playlist and embed shortcodes,
+ * and a view for embeddable URLs.
+ */
+( function( $, views ) {
+	views.register( 'gallery', {
+		template: wp.media.template( 'editor-gallery' ),
+		postID: $( '#post_ID' ).val(),
+
+		initialize: function( options ) {
+			this.shortcode = options.shortcode;
+			this.fetch();
+		},
+
+		fetch: function() {
+			var self = this;
+
+			this.attachments = wp.media.gallery.attachments( this.shortcode, this.postID );
+			this.dfd = this.attachments.more().done( function() {
+				self.render();
+			} );
+		},
+
+		getHtml: function() {
+			var attrs = this.shortcode.attrs.named,
+				attachments = false,
+				options;
+
+			// Don't render errors while still fetching attachments
+			if ( this.dfd && 'pending' === this.dfd.state() && ! this.attachments.length ) {
+				return '';
+			}
+
+			if ( this.attachments.length ) {
+				attachments = this.attachments.toJSON();
+
+				_.each( attachments, function( attachment ) {
+					if ( attachment.sizes ) {
+						if ( attrs.size && attachment.sizes[ attrs.size ] ) {
+							attachment.thumbnail = attachment.sizes[ attrs.size ];
+						} else if ( attachment.sizes.thumbnail ) {
+							attachment.thumbnail = attachment.sizes.thumbnail;
+						} else if ( attachment.sizes.full ) {
+							attachment.thumbnail = attachment.sizes.full;
+						}
+					}
+				} );
+			}
+
+			options = {
+				attachments: attachments,
+				columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns
+			};
 
-			$( document ).trigger( 'media:edit' );
+			return this.template( options );
+		},
+
+		edit: function( text, callback ) {
+			var gallery = wp.media.gallery,
+				frame = gallery.edit( text );
+
+			frame.state( 'gallery-edit' ).on( 'update', function( selection ) {
+				callback( gallery.shortcode( selection ).string() );
+			} );
 
-			data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
-			frame = media.edit( data );
 			frame.on( 'close', function() {
 				frame.detach();
 			} );
+		}
+	} );
 
-			callback = function( selection ) {
-				var shortcode = wp.media[ self.type ].shortcode( selection ).string();
-				$( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
-				wp.mce.views.refreshView( self, shortcode );
-				frame.detach();
-			};
-			if ( _.isArray( self.state ) ) {
-				_.each( self.state, function (state) {
-					frame.state( state ).on( 'update', callback );
+	/**
+	 * These are base methods that are shared by the audio and video shortcode's MCE controller.
+	 *
+	 * @mixin
+	 */
+	wp.mce.av = {
+		overlay: true,
+		action: 'parse-media-shortcode',
+
+		initialize: function( options ) {
+			var self = this;
+
+			if ( options.url ) {
+				this.loader = false;
+				this.shortcode = wp.media.embed.shortcode( {
+					url: options.url
 				} );
 			} else {
-				frame.state( self.state ).on( 'update', callback );
+				this.shortcode = options.shortcode;
 			}
-			frame.open();
+
+			this.fetch();
+
+			this.getEditors( function( editor ) {
+				editor.on( 'wpview-selected', function() {
+					self.stopPlayers();
+				} );
+			} );
+		},
+
+		fetch: function () {
+			var self = this;
+
+			wp.ajax.send( this.action, {
+				data: {
+					post_ID: $( '#post_ID' ).val() || 0,
+					type: this.shortcode.tag,
+					shortcode: this.shortcode.string()
+				}
+			} )
+			.done( function( response ) {
+				self.parsed = response;
+				self.render();
+			} )
+			.fail( function( response ) {
+				if ( self.type === 'embedURL' ) {
+					self.removeMarkers();
+				} else {
+					self.setError( response.message || response.statusText, 'admin-media' );
+				}
+			} );
+		},
+
+		stopPlayers: function( remove ) {
+			this.getNodes( function( editor, node, content ) {
+				var win = $( 'iframe.wpview-sandbox', content ).get( 0 );
+
+				if ( win && ( win = win.contentWindow ) && win.mejs ) {
+					_.each( win.mejs.players, function( player ) {
+						try {
+							player[ remove ? 'remove' : 'pause' ]();
+						} catch ( e ) {}
+					} );
+				}
+			} );
+		},
+
+		getHtml: function() {
+			return this.parsed;
+		},
+
+		edit: function( text, callback ) {
+			var media = wp.media[ this.type ],
+				frame = media.edit( text );
+
+			this.stopPlayers();
+
+			_.each( this.state, function ( state ) {
+				frame.state( state ).on( 'update', function( selection ) {
+					callback( media.shortcode( selection ).string() );
+				} );
+			} );
+
+			frame.on( 'close', function() {
+				frame.detach();
+			} );
 		}
 	};
 
@@ -790,8 +804,8 @@
 	 *
 	 * @mixes wp.mce.av
 	 */
-	wp.mce.views.register( 'video', _.extend( {}, wp.mce.av, {
-		state: 'video-details'
+	views.register( 'video', _.extend( {}, wp.mce.av, {
+		state: [ 'video-details' ]
 	} ) );
 
 	/**
@@ -799,8 +813,8 @@
 	 *
 	 * @mixes wp.mce.av
 	 */
-	wp.mce.views.register( 'audio', _.extend( {}, wp.mce.av, {
-		state: 'audio-details'
+	views.register( 'audio', _.extend( {}, wp.mce.av, {
+		state: [ 'audio-details' ]
 	} ) );
 
 	/**
@@ -808,74 +822,48 @@
 	 *
 	 * @mixes wp.mce.av
 	 */
-	wp.mce.views.register( 'playlist', _.extend( {}, wp.mce.av, {
+	views.register( 'playlist', _.extend( {}, wp.mce.av, {
 		state: [ 'playlist-edit', 'video-playlist-edit' ]
 	} ) );
 
 	/**
 	 * TinyMCE handler for the embed shortcode
 	 */
-	wp.mce.embedMixin = {
-		View: _.extend( {}, wp.mce.av.View, {
-			overlay: true,
-			action: 'parse-embed',
-			initialize: function( options ) {
-				this.content = options.content;
-				this.original = options.url || options.shortcode.string();
-
-				if ( options.url ) {
-					this.shortcode = media.embed.shortcode( {
-						url: options.url
-					} );
-				} else {
-					this.shortcode = options.shortcode;
-				}
-
-				_.bindAll( this, 'setIframes', 'setNodes', 'fetch' );
-				$( this ).on( 'ready', this.setNodes );
-
-				this.fetch();
-			}
-		} ),
-		edit: function( node ) {
-			var embed = media.embed,
-				self = this,
-				frame,
-				data,
-				isURL = 'embedURL' === this.type;
-
-			$( document ).trigger( 'media:edit' );
+	wp.mce.embed = _.extend( {}, wp.mce.av, {
+		action: 'parse-embed',
 
-			data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
-			frame = embed.edit( data, isURL );
-			frame.on( 'close', function() {
-				frame.detach();
-			} );
-			frame.state( 'embed' ).props.on( 'change:url', function (model, url) {
-				if ( ! url ) {
-					return;
+		edit: function( text, callback ) {
+			var media = wp.media.embed,
+				isURL = 'embedURL' === this.type,
+				frame = media.edit( text, isURL );
+
+			this.stopPlayers();
+
+			frame.state( 'embed' ).props.on( 'change:url', function( model, url ) {
+				if ( url ) {
+					frame.state( 'embed' ).metadata = model.toJSON();
 				}
-				frame.state( 'embed' ).metadata = model.toJSON();
 			} );
-			frame.state( 'embed' ).on( 'select', function() {
-				var shortcode;
 
+			frame.state( 'embed' ).on( 'select', function() {
 				if ( isURL ) {
-					shortcode = frame.state( 'embed' ).metadata.url;
+					callback( frame.state( 'embed' ).metadata.url );
 				} else {
-					shortcode = embed.shortcode( frame.state( 'embed' ).metadata ).string();
+					callback( media.shortcode( frame.state( 'embed' ).metadata ).string() );
 				}
-				$( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
-				wp.mce.views.refreshView( self, shortcode );
+			} );
+
+			frame.on( 'close', function() {
 				frame.detach();
 			} );
+
 			frame.open();
 		}
-	};
+	} );
 
-	wp.mce.views.register( 'embed', _.extend( {}, wp.mce.embedMixin ) );
+	views.register( 'embed', _.extend( {}, wp.mce.embed ) );
 
-	wp.mce.views.register( 'embedURL', _.extend( {}, wp.mce.embedMixin, {
+	views.register( 'embedURL', _.extend( {}, wp.mce.embed, {
 		toView: function( content ) {
 			var re = /(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,
 				match = re.exec( tinymce.trim( content ) );
@@ -893,5 +881,4 @@
 			};
 		}
 	} ) );
-
-}(jQuery));
+} )( jQuery, wp.mce.views );
Index: src/wp-includes/js/tinymce/plugins/wpview/plugin.js
===================================================================
--- src/wp-includes/js/tinymce/plugins/wpview/plugin.js	(revision 31485)
+++ src/wp-includes/js/tinymce/plugins/wpview/plugin.js	(working copy)
@@ -341,7 +341,7 @@
 							editor.focus();
 						}
 
-						wp.mce.views.edit( view );
+						wp.mce.views.edit( editor, view );
 						return false;
 					} else if ( editor.dom.hasClass( event.target, 'remove' ) ) {
 						removeView( view );
