<commit_before>Paperpile.PatternSettings = Ext.extend(Ext.Panel, {

    title: 'Location and patterns settings',

    initComponent: function() {
		Ext.apply(this, {
            closable:true,
            autoLoad:{url:Paperpile.Url('/screens/patterns'),
                      callback: this.setupFields,
                      scope:this
                     },
            bodyStyle:'pp-settings',
            iconCls:'pp-icon-tools',
            autoScroll: true,
        });

        Paperpile.PatternSettings.superclass.initComponent.call(this);

        this.isDirty=false;

    },

    //
    // Creates textfields, buttons and installs event handlers
    //

    setupFields: function(){

        this.textfields={};

        Ext.get('patterns-cancel-button').on('click',
                                             function(){
                                                 Paperpile.main.tabs.remove(Paperpile.main.tabs.getActiveTab(), true);
                                             });

        Ext.each(['library_db','paper_root','key_pattern','pdf_pattern','attachment_pattern'],
                 function(item){
                     var field=new Ext.form.TextField({value:Paperpile.main.globalSettings[item],
                                                       enableKeyEvents: true,
                                                       width: 300,
                                                      });

                     field.render(item+'_textfield',0);

                     this.textfields[item]=field;

                     if (item == 'library_db' || item == 'paper_root'){
                         field.addClass('pp-textfield-with-button');
                         var b=new Ext.Button({text: item=='library_db'?'Choose file':'Choose folder',
                                               renderTo:item+'_button'});

                         b.on('click', function(){
                             var parts=Paperpile.utils.splitPath(this.textfields[item].getValue());
                             new Paperpile.FileChooser({
                                 saveMode: item == 'library_db' ? true : false,
                                 selectionMode: item == 'library_db' ? 'FILE' : 'DIR',
                                 saveDefault: item == 'library_db' ? parts.file : '',
                                 currentRoot: parts.dir,
                                 warnOnExisting:false,
                                 callback:function(button,path){
                                     if (button == 'OK'){
                                         this.textfields[item].setValue(path);
                                     }
                                 },
                                 scope:this
                             }).show();
                         },this);
                     }

                     if (item == 'key_pattern' || item == 'pdf_pattern' || item == 'attachment_pattern'){

                         var task = new Ext.util.DelayedTask(this.updateFields, this);

                         field.on('keypress', function(){
                             this.isDirty=true;
                             task.delay(500);
                         }, this);
                     }

                 }, this);

        this.updateFields();

        this.setSaveDisabled(true);

    },

    //
    // Validates inputs and updates example fields
    //

    updateFields: function(){

        var params={};

        Ext.each(['library_db','paper_root','key_pattern','pdf_pattern','attachment_pattern'],
                 function(key){
                     params[key]=Ext.get(key+'_textfield').first().getValue();
                 }, this
                );

        Ext.Ajax.request({
            url: Paperpile.Url('/ajax/settings/pattern_example'),
            params: params,
            success: function(response){
                var data = Ext.util.JSON.decode(response.responseText).data;

                var hasErrors=false;

                for (var f in data){
                    if (data[f].error){
                        this.textfields[f].markInvalid(data[f].error);
                        Ext.get(f+'_example').update('');
                        hasErrors=true;
                    } else {
                        Ext.get(f+'_example').update(data[f].string);
                    }
                }

                console.log(this.isDirty, hasErrors);

                if (this.isDirty){
                    this.setSaveDisabled(hasErrors);
                }
            },
            failure: Paperpile.main.onError,
            scope:this
        });

    },

    setSaveDisabled: function(disabled){

        var button=Ext.get('patterns-save-button');

        button.un('click',this.submit,this);

        if (disabled){
            button.replaceClass('pp-save-button','pp-save-button-disabled');
        } else {
            button.replaceClass('pp-save-button-disabled','pp-save-button');
            button.on('click', this.submit, this);
        }
    },

    submit: function(){

        var params={};

        Ext.each(['library_db','paper_root','key_pattern','pdf_pattern','attachment_pattern'],
                 function(item){
                     params[item]=this.textfields[item].getValue();
                 }, this);

        Paperpile.status.showBusy('Applying changes.');

        Ext.Ajax.request({
            url: Paperpile.Url('/ajax/settings/update_patterns'),
            params: params,
            success: function(response){
                var error = Ext.util.JSON.decode(response.responseText).error;
                if (error) {
                    Paperpile.main.onError(response);
                    return;
                }
                Paperpile.main.tabs.remove(Paperpile.main.tabs.getActiveTab(), true);
                var old_library_db=Paperpile.main.globalSettings.library_db;
                Paperpile.main.loadSettings(
                    function(){
                        // Complete reload only if database has
                        // changed. This is not necessary if the
                        // database has only be renamed but we
                        // update also in this case.
                        if (old_library_db != Paperpile.main.globalSettings.library_db){
                            Paperpile.main.tree.getRootNode().reload();
                            Paperpile.main.tree.expandAll();

                            // Note that this as async. Tags
                            // should be loaded before results for
                            // grid appear but it is not
                            // guaranteed.
                            Ext.StoreMgr.lookup('tag_store').reload();

                            var tab;
                            while(tab = Paperpile.main.tabs.items.first()){
                                Paperpile.main.tabs.remove(tab,true);
                            }

                            Paperpile.main.tabs.newDBtab('');
                            Paperpile.main.tabs.setActiveTab(0);
                            Paperpile.main.tabs.doLayout();
                        }
                        Paperpile.status.clearMsg();
                    }, this
                );
            },

            failure: function(response){
                var json = Ext.util.JSON.decode(response.responseText);
                Ext.Msg.show({
                    title:'Error',
                    msg: "
Your settings could not be applied
"+json.errors[0],
                    buttons: Ext.Msg.OK,
                    animEl: 'elId',
                    icon: Ext.MessageBox.ERROR,
                    fn: function(){
                        Paperpile.main.tabs.remove(Paperpile.main.tabs.getActiveTab());
                    },
                    scope:this
                });
                Paperpile.main.loadSettings();
            },
            scope:this
        });

    }

});

<commit_msg>Pattern-examples do not get updated in preferenes screen. Apparently, in Webkit "keypress" only fires for  a textfield when "enter" is pressed. Changed to "keydown" and works fine (closes #57).<commit_after>Paperpile.PatternSettings = Ext.extend(Ext.Panel, {

    title: 'Location and patterns settings',

    initComponent: function() {
		Ext.apply(this, {
            closable:true,
            autoLoad:{url:Paperpile.Url('/screens/patterns'),
                      callback: this.setupFields,
                      scope:this
                     },
            bodyStyle:'pp-settings',
            iconCls:'pp-icon-tools',
            autoScroll: true,
        });

        Paperpile.PatternSettings.superclass.initComponent.call(this);

        this.isDirty=false;

    },

    //
    // Creates textfields, buttons and installs event handlers
    //

    setupFields: function(){

        this.textfields={};

        Ext.get('patterns-cancel-button').on('click',
                                             function(){
                                                 Paperpile.main.tabs.remove(Paperpile.main.tabs.getActiveTab(), true);
                                             });

        Ext.each(['library_db','paper_root','key_pattern','pdf_pattern','attachment_pattern'],
                 function(item){
                     var field=new Ext.form.TextField({value:Paperpile.main.globalSettings[item],
                                                       enableKeyEvents: true,
                                                       width: 300,
                                                      });

                     field.render(item+'_textfield',0);

                     this.textfields[item]=field;

                     if (item == 'library_db' || item == 'paper_root'){
                         field.addClass('pp-textfield-with-button');
                         var b=new Ext.Button({text: item=='library_db'?'Choose file':'Choose folder',
                                               renderTo:item+'_button'});

                         b.on('click', function(){
                             var parts=Paperpile.utils.splitPath(this.textfields[item].getValue());
                             new Paperpile.FileChooser({
                                 saveMode: item == 'library_db' ? true : false,
                                 selectionMode: item == 'library_db' ? 'FILE' : 'DIR',
                                 saveDefault: item == 'library_db' ? parts.file : '',
                                 currentRoot: parts.dir,
                                 warnOnExisting:false,
                                 callback:function(button,path){
                                     if (button == 'OK'){
                                         this.textfields[item].setValue(path);
                                     }
                                 },
                                 scope:this
                             }).show();
                         },this);
                     }

                     if (item == 'key_pattern' || item == 'pdf_pattern' || item == 'attachment_pattern'){

                         var task = new Ext.util.DelayedTask(this.updateFields, this);

                         field.on('keydown', function(){
                             this.isDirty=true;
                             task.delay(500);
                         }, this);
                     }

                 }, this);

        this.updateFields();

        this.setSaveDisabled(true);

    },

    //
    // Validates inputs and updates example fields
    //

    updateFields: function(){

        var params={};

        Ext.each(['library_db','paper_root','key_pattern','pdf_pattern','attachment_pattern'],
                 function(key){
                     params[key]=Ext.get(key+'_textfield').first().getValue();
                 }, this
                );

        Ext.Ajax.request({
            url: Paperpile.Url('/ajax/settings/pattern_example'),
            params: params,
            success: function(response){
                var data = Ext.util.JSON.decode(response.responseText).data;

                var hasErrors=false;

                for (var f in data){
                    if (data[f].error){
                        this.textfields[f].markInvalid(data[f].error);
                        Ext.get(f+'_example').update('');
                        hasErrors=true;
                    } else {
                        Ext.get(f+'_example').update(data[f].string);
                    }
                }

                console.log(this.isDirty, hasErrors);

                if (this.isDirty){
                    this.setSaveDisabled(hasErrors);
                }
            },
            failure: Paperpile.main.onError,
            scope:this
        });

    },

    setSaveDisabled: function(disabled){

        var button=Ext.get('patterns-save-button');

        button.un('click',this.submit,this);

        if (disabled){
            button.replaceClass('pp-save-button','pp-save-button-disabled');
        } else {
            button.replaceClass('pp-save-button-disabled','pp-save-button');
            button.on('click', this.submit, this);
        }
    },

    submit: function(){

        var params={};

        Ext.each(['library_db','paper_root','key_pattern','pdf_pattern','attachment_pattern'],
                 function(item){
                     params[item]=this.textfields[item].getValue();
                 }, this);

        Paperpile.status.showBusy('Applying changes.');

        Ext.Ajax.request({
            url: Paperpile.Url('/ajax/settings/update_patterns'),
            params: params,
            success: function(response){
                var error = Ext.util.JSON.decode(response.responseText).error;
                if (error) {
                    Paperpile.main.onError(response);
                    return;
                }
                Paperpile.main.tabs.remove(Paperpile.main.tabs.getActiveTab(), true);
                var old_library_db=Paperpile.main.globalSettings.library_db;
                Paperpile.main.loadSettings(
                    function(){
                        // Complete reload only if database has
                        // changed. This is not necessary if the
                        // database has only be renamed but we
                        // update also in this case.
                        if (old_library_db != Paperpile.main.globalSettings.library_db){
                            Paperpile.main.tree.getRootNode().reload();
                            Paperpile.main.tree.expandAll();

                            // Note that this as async. Tags
                            // should be loaded before results for
                            // grid appear but it is not
                            // guaranteed.
                            Ext.StoreMgr.lookup('tag_store').reload();

                            var tab;
                            while(tab = Paperpile.main.tabs.items.first()){
                                Paperpile.main.tabs.remove(tab,true);
                            }

                            Paperpile.main.tabs.newDBtab('');
                            Paperpile.main.tabs.setActiveTab(0);
                            Paperpile.main.tabs.doLayout();
                        }
                        Paperpile.status.clearMsg();
                    }, this
                );
            },

            failure: function(response){
                var json = Ext.util.JSON.decode(response.responseText);
                Ext.Msg.show({
                    title:'Error',
                    msg: "
Your settings could not be applied
"+json.errors[0],
                    buttons: Ext.Msg.OK,
                    animEl: 'elId',
                    icon: Ext.MessageBox.ERROR,
                    fn: function(){
                        Paperpile.main.tabs.remove(Paperpile.main.tabs.getActiveTab());
                    },
                    scope:this
                });
                Paperpile.main.loadSettings();
            },
            scope:this
        });

    }

});

<|endoftext|>


<commit_before>/* Copyright (c) 2017 Dmitri Kourennyi */
/* See the file COPYING for copying permission. */
/* exported contrast */
/* globals getDefaultComputedStyle:false color:false */
'use strict';

const contrast = {
  kInputElems: [
    'INPUT', 'TEXTAREA', 'SELECT', 'BUTTON', 'TOOLBARBUTTON',
  ],
  kInvisibleElems: [
    'HEAD', 'TITLE', 'META', 'SCRIPT', 'IMG', 'STYLE', 'BR', 'LINK', '#text',
    'FRAMESET',
  ],

  IFRAME_DELAY: 500,

  userInverted: false,

  checkDoc() {
    // Check from root recursively
    this.checkElement(document.documentElement, true);

    // Other checks required when browser is in quirks mode
    if (document.compatMode === 'BackCompat') {
      // Tables don't inherit color
      const tables = document.getElementsByTagName('table');

      for (let i = 0; i < tables.length; i += 1) {
        if (getComputedStyle(tables[i]).color ===
            getDefaultComputedStyle(tables[i]).color) {
          // If color has not been set explicitely, then force inherit
          tables[i].style.color = 'inherit';
        }
      }
    }
  },

  checkElement(element, recurse, delay) {
    if (element == null) {
      return;
    }

    // If element has already been examined before, don't do any processing
    if (element.dataset._extensionTextContrast != null) {
      return;
    }

    const fg_color_defined = this.is_fg_defined(element);
    const bg_color_defined = this.is_bg_defined(element);
    const bg_img_defined = this.is_bg_img_defined(element);

    if (fg_color_defined && bg_color_defined) {
      // Both colors explicitely defined, nothing to do
      element.dataset._extensionTextContrast = '';
      this.fix_embeds(element, 'std');

      return;
    } else if (!fg_color_defined && bg_color_defined) {
      // Only set fg if original contrast is poor
      const fg_color = color.to_rgb(getComputedStyle(element).color);
      const bg_color = color.to_rgb(getComputedStyle(element).backgroundColor);

      if (color.is_transparent(bg_color) ||
          !color.is_contrasty(fg_color, bg_color)) {
        element.dataset._extensionTextContrast = 'fg';
        this.fix_embeds(element, 'std');

        return;
      }
    } else if (fg_color_defined && !bg_color_defined) {
      // Only set bg if it will improve contrast
      const fg_color = color.to_rgb(getComputedStyle(element).color);
      const bg_color = color.to_rgb(getComputedStyle(element).backgroundColor);

      if (!color.is_contrasty(fg_color, bg_color)) {
        element.dataset._extensionTextContrast = 'bg';
        this.fix_embeds(element, 'std');

        return;
      }
    } else if (bg_img_defined) {
      const default_bg =
        color.to_rgb(getDefaultComputedStyle(element).backgroundColor);

      if (!this.isInputNode(element) && color.is_transparent(default_bg)) {
        // If the background is supposed to be transparent, keep the
        // transparency and only fix foreground. Don't do this for input
        // elements as they have an inverted style from the get-go.
        element.dataset._extensionTextContrast = 'fg';
      } else {
        // No FG or BG color, but may have a transparent bg image. BG color is
        // not transparent, so need to set both colors.
        element.dataset._extensionTextContrast = 'both';
      }
      this.fix_embeds(element, 'std');

      return;
    }

    if (recurse === true) {
      const {children} = element;
      const len = children.length;

      for (let i = 0; i < len; i += 1) {
        // Don't look at non-renderable elements
        if (!this.isInVisibleNode(element.children[i])) {
          this.checkElement(element.children[i], true);
        }
      }

      if (this.is_subdoc(element)) {
        if (delay) {
          setTimeout(() => {
            this.fix_embeds(element, 'fix');
          }, this.IFRAME_DELAY);
        } else {
          this.fix_embeds(element, 'fix');
        }
      }
      // this.checkElement(this.get_subdoc(element), true);
    }
  },

  checkInputs(elem) {
    // Check all input elements under elem
    const nodeIterator = document.createNodeIterator(elem,
      NodeFilter.SHOW_ELEMENT, {acceptNode: this.isInputNode.bind(this)});

    // Can't use for-in loop because a NodeIterator is not an iterator. Thanks
    // Javascript.
    let node; // eslint-disable-line init-declarations

    while ((node = nodeIterator.nextNode()) != null) {
      this.checkElement(node, false);
    }
  },

  clear_overrides(doc) {
    const elems = doc.querySelectorAll('[data-_extension-text-contrast]');

    for (const e of elems) {
      e.removeAttribute('data-_extension-text-contrast');
    }
  },

  fix_embeds(e, mode) {
    const nodeIterator = document.createNodeIterator(
        e, NodeFilter.SHOW_ELEMENT, {acceptNode: this.is_subdoc});

    // Can't use for-in loop because a NodeIterator is not an iterator. Thanks
    // Javascript.
    let node; // eslint-disable-line init-declarations

    while ((node = nodeIterator.nextNode()) != null) {
      if (node.contentDocument != null) {
        if (mode === 'std') {
          node.contentWindow.postMessage('_tcfdt_subdoc_std', '*');
        } else if (mode === 'fix') {
          node.contentWindow.postMessage('_tcfdt_subdoc_fix', '*');
        } else if (mode === 'clr') {
          node.contentWindow.postMessage('_tcfdt_subdoc_clr', '*');
        }
      } else if (node.getSVGDocument != null && node.getSVGDocument() != null &&
            mode === 'std') {
        this.clear_overrides(node.getSVGDocument().documentElement);
        // Node is an <embed> SVG file, which will use the local stylesheet, so
        // set its dataset directly.
        node.getSVGDocument().documentElement.dataset._extensionTextContrast =
          'default';
      }
    }
  },

  get_subdoc(node) {
    if (node.contentDocument != null) {
      return node.contentDocument.documentElement;
    }

    if (node.getSVGDocument != null && node.getSVGDocument() != null) {
      return node.getSVGDocument().documentElement;
    }

    return null;
  },

  is_fg_defined(e) {
    return getComputedStyle(e).color !== getDefaultComputedStyle(e).color;
  },

  is_bg_defined(e) {
    return getComputedStyle(e).backgroundColor !==
      getDefaultComputedStyle(e).backgroundColor;
  },

  is_bg_img_defined(e) {
    return getComputedStyle(e).backgroundImage !== 'none';
  },

  isInputNode(node) {
    return this.kInputElems.indexOf(node.nodeName) > -1;
  },

  isInVisibleNode(node) {
    return this.kInvisibleElems.indexOf(node.nodeName) > -1;
  },

  is_subdoc(node) {
    if (node.contentDocument != null ||
      node.getSVGDocument != null && node.getSVGDocument() != null) {
      return true;
    }

    return false;
  },

  recolor_parent_check(elem) {
    if (this.userInverted === true) {
      let parent = elem.parentElement;
      let defined = false;

      while (parent !== null) {
        if (parent.dataset._extensionTextContrast != null) {
          // If any parents' were already handled,
          // new elements don't need recolor.
          defined = true;
          break;
        }
        parent = parent.parentElement;
      }
      if (defined) {
        // Color was set, adjust any child embeds
        setTimeout(() => {
          this.fix_embeds(elem, 'std');
        }, this.IFRAME_DELAY);
      } else {
        this.checkElement(elem, true, true);
      }
    }
  },

  updateUserInverted() {
    const defaultFg = color.to_rgb(getDefaultComputedStyle(
      document.documentElement).color);

    if (!color.is_contrasty(defaultFg, {r: 255, g: 255, b: 255, a: 1})) {
      // Contrast check against what sites will assume to be default
      // (black fg, white bg) failed, so user most likely has 'Use system
      // colors' on
      contrast.userInverted = true;
    }
  },
};
<commit_msg>Check for contentWindow when detecting embedded documents<commit_after>/* Copyright (c) 2017 Dmitri Kourennyi */
/* See the file COPYING for copying permission. */
/* exported contrast */
/* globals getDefaultComputedStyle:false color:false */
'use strict';

const contrast = {
  kInputElems: [
    'INPUT', 'TEXTAREA', 'SELECT', 'BUTTON', 'TOOLBARBUTTON',
  ],
  kInvisibleElems: [
    'HEAD', 'TITLE', 'META', 'SCRIPT', 'IMG', 'STYLE', 'BR', 'LINK', '#text',
    'FRAMESET',
  ],

  IFRAME_DELAY: 500,

  userInverted: false,

  checkDoc() {
    // Check from root recursively
    this.checkElement(document.documentElement, true);

    // Other checks required when browser is in quirks mode
    if (document.compatMode === 'BackCompat') {
      // Tables don't inherit color
      const tables = document.getElementsByTagName('table');

      for (let i = 0; i < tables.length; i += 1) {
        if (getComputedStyle(tables[i]).color ===
            getDefaultComputedStyle(tables[i]).color) {
          // If color has not been set explicitely, then force inherit
          tables[i].style.color = 'inherit';
        }
      }
    }
  },

  checkElement(element, recurse, delay) {
    if (element == null) {
      return;
    }

    // If element has already been examined before, don't do any processing
    if (element.dataset._extensionTextContrast != null) {
      return;
    }

    const fg_color_defined = this.is_fg_defined(element);
    const bg_color_defined = this.is_bg_defined(element);
    const bg_img_defined = this.is_bg_img_defined(element);

    if (fg_color_defined && bg_color_defined) {
      // Both colors explicitely defined, nothing to do
      element.dataset._extensionTextContrast = '';
      this.fix_embeds(element, 'std');

      return;
    } else if (!fg_color_defined && bg_color_defined) {
      // Only set fg if original contrast is poor
      const fg_color = color.to_rgb(getComputedStyle(element).color);
      const bg_color = color.to_rgb(getComputedStyle(element).backgroundColor);

      if (color.is_transparent(bg_color) ||
          !color.is_contrasty(fg_color, bg_color)) {
        element.dataset._extensionTextContrast = 'fg';
        this.fix_embeds(element, 'std');

        return;
      }
    } else if (fg_color_defined && !bg_color_defined) {
      // Only set bg if it will improve contrast
      const fg_color = color.to_rgb(getComputedStyle(element).color);
      const bg_color = color.to_rgb(getComputedStyle(element).backgroundColor);

      if (!color.is_contrasty(fg_color, bg_color)) {
        element.dataset._extensionTextContrast = 'bg';
        this.fix_embeds(element, 'std');

        return;
      }
    } else if (bg_img_defined) {
      const default_bg =
        color.to_rgb(getDefaultComputedStyle(element).backgroundColor);

      if (!this.isInputNode(element) && color.is_transparent(default_bg)) {
        // If the background is supposed to be transparent, keep the
        // transparency and only fix foreground. Don't do this for input
        // elements as they have an inverted style from the get-go.
        element.dataset._extensionTextContrast = 'fg';
      } else {
        // No FG or BG color, but may have a transparent bg image. BG color is
        // not transparent, so need to set both colors.
        element.dataset._extensionTextContrast = 'both';
      }
      this.fix_embeds(element, 'std');

      return;
    }

    if (recurse === true) {
      const {children} = element;
      const len = children.length;

      for (let i = 0; i < len; i += 1) {
        // Don't look at non-renderable elements
        if (!this.isInVisibleNode(element.children[i])) {
          this.checkElement(element.children[i], true);
        }
      }

      if (this.is_subdoc(element)) {
        if (delay) {
          setTimeout(() => {
            this.fix_embeds(element, 'fix');
          }, this.IFRAME_DELAY);
        } else {
          this.fix_embeds(element, 'fix');
        }
      }
      // this.checkElement(this.get_subdoc(element), true);
    }
  },

  checkInputs(elem) {
    // Check all input elements under elem
    const nodeIterator = document.createNodeIterator(elem,
      NodeFilter.SHOW_ELEMENT, {acceptNode: this.isInputNode.bind(this)});

    // Can't use for-in loop because a NodeIterator is not an iterator. Thanks
    // Javascript.
    let node; // eslint-disable-line init-declarations

    while ((node = nodeIterator.nextNode()) != null) {
      this.checkElement(node, false);
    }
  },

  clear_overrides(doc) {
    const elems = doc.querySelectorAll('[data-_extension-text-contrast]');

    for (const e of elems) {
      e.removeAttribute('data-_extension-text-contrast');
    }
  },

  fix_embeds(e, mode) {
    const nodeIterator = document.createNodeIterator(
        e, NodeFilter.SHOW_ELEMENT, {acceptNode: this.is_subdoc});

    // Can't use for-in loop because a NodeIterator is not an iterator. Thanks
    // Javascript.
    let node; // eslint-disable-line init-declarations

    while ((node = nodeIterator.nextNode()) != null) {
      if (node.contentWindow != null) {
        if (mode === 'std') {
          node.contentWindow.postMessage('_tcfdt_subdoc_std', '*');
        } else if (mode === 'fix') {
          node.contentWindow.postMessage('_tcfdt_subdoc_fix', '*');
        } else if (mode === 'clr') {
          node.contentWindow.postMessage('_tcfdt_subdoc_clr', '*');
        }
      } else if (node.getSVGDocument != null && node.getSVGDocument() != null &&
            mode === 'std') {
        this.clear_overrides(node.getSVGDocument().documentElement);
        // Node is an <embed> SVG file, which will use the local stylesheet, so
        // set its dataset directly.
        node.getSVGDocument().documentElement.dataset._extensionTextContrast =
          'default';
      }
    }
  },

  get_subdoc(node) {
    if (node.contentDocument != null) {
      return node.contentDocument.documentElement;
    }

    if (node.getSVGDocument != null && node.getSVGDocument() != null) {
      return node.getSVGDocument().documentElement;
    }

    return null;
  },

  is_fg_defined(e) {
    return getComputedStyle(e).color !== getDefaultComputedStyle(e).color;
  },

  is_bg_defined(e) {
    return getComputedStyle(e).backgroundColor !==
      getDefaultComputedStyle(e).backgroundColor;
  },

  is_bg_img_defined(e) {
    return getComputedStyle(e).backgroundImage !== 'none';
  },

  isInputNode(node) {
    return this.kInputElems.indexOf(node.nodeName) > -1;
  },

  isInVisibleNode(node) {
    return this.kInvisibleElems.indexOf(node.nodeName) > -1;
  },

  is_subdoc(node) {
    if (node.contentWindow != null ||
      node.getSVGDocument != null && node.getSVGDocument() != null) {
      return true;
    }

    return false;
  },

  recolor_parent_check(elem) {
    if (this.userInverted === true) {
      let parent = elem.parentElement;
      let defined = false;

      while (parent !== null) {
        if (parent.dataset._extensionTextContrast != null) {
          // If any parents' were already handled,
          // new elements don't need recolor.
          defined = true;
          break;
        }
        parent = parent.parentElement;
      }
      if (defined) {
        // Color was set, adjust any child embeds
        setTimeout(() => {
          this.fix_embeds(elem, 'std');
        }, this.IFRAME_DELAY);
      } else {
        this.checkElement(elem, true, true);
      }
    }
  },

  updateUserInverted() {
    const defaultFg = color.to_rgb(getDefaultComputedStyle(
      document.documentElement).color);

    if (!color.is_contrasty(defaultFg, {r: 255, g: 255, b: 255, a: 1})) {
      // Contrast check against what sites will assume to be default
      // (black fg, white bg) failed, so user most likely has 'Use system
      // colors' on
      contrast.userInverted = true;
    }
  },
};
<|endoftext|>


<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(FILL_ME_IN);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe(FILL_ME_IN);
    expect(overrideMessage()).toBe(FILL_ME_IN);
    expect(message).toBe(FILL_ME_IN);
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe(FILL_ME_IN);
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<commit_msg>About Functions: declare functions and internal variables... pass tests<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe(FILL_ME_IN);
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(FILL_ME_IN);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe(FILL_ME_IN);
    expect(overrideMessage()).toBe(FILL_ME_IN);
    expect(message).toBe(FILL_ME_IN);
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe(FILL_ME_IN);
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<commit_msg>Started AboutFunctions.js: Completed "should declare functions" - declared a sum function and ran it - expect a function call to equal sum of inputs<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe(FILL_ME_IN);
    expect(overrideMessage()).toBe(FILL_ME_IN);
    expect(message).toBe(FILL_ME_IN);
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe(FILL_ME_IN);
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>var sec = sec || {};
sec.geo = sec.geo || {};
sec.geo.kml = sec.geo.kml || {};
sec.geo.kml.KmlRenderer = function()
{
    this.colorDefault = "ff003fff";
    this.descriptionField = "#DESCRIPTION#";
    this.extendedData = "#EXTENDEDDATA#";
    this.colorField = "#COLOR#";
    this.nameField = "#NAME#";
    this.idField = "#ID#";
    this.placemarkidField = "#PLACEMARKID#";
    this.KML_START = null;
    this.KML_END = "</Folder>\n";
    this.PLACEMARK_START = null;
    this.PLACEMARK_END = "\t\t\t</MultiGeometry>\n\t\t</Placemark>\n";
    this.DEFAULT_EXDAT = "<Data name='sid'><value>#ID#</value></Data><Data name='shapeType'><value>#SHAPETYPE#</value></Data><Data name='lat'><value>#LAT#</value></Data><Data name='lon'><value>#LON#</value></Data><Data name='alt'><value>#ALT#</value></Data>";
    this.DEFAULT_BLSTY = "<![CDATA[$[sid]]]>";
    this.KML_START = "<Folder id=\"" + this.idField + "\">\n";
    this.PLACEMARK_START = "\t\t<Placemark id=\"" + this.placemarkidField + "\">\n" + "                      <Style>\n" + "                          <PolyStyle>\n" + "                              <color>" + this.colorField + "</color>\n" + "                          </PolyStyle>\n" + "                          <LineStyle>\n" + "                              <color>" + this.colorField + "</color>\n" + "                          </LineStyle>\n" + "                       </Style>\n" + "			<name>" + this.nameField + "</name>\n" + "			<description>" + this.descriptionField + "</description>\n" + "			<ExtendedData>" + this.extendedData + "</ExtendedData>\n" + "			<MultiGeometry>\n";

    this.KML_START = "<Folder id=\"" + this.idField + "\">\n";
    this.KML_END = "</Folder>\n";

    this.PLACEMARK_START = "" +
            "		<Placemark id=\"" + this.placemarkidField + "\">\n" +
            "                      <Style>\n" +
            "                          <PolyStyle>\n" +
            "                              <color>" + this.colorField + "</color>\n" +
            "                          </PolyStyle>\n" +
            "                          <LineStyle>\n" +
            "                              <color>" + this.colorField + "</color>\n" +
            "                          </LineStyle>\n" +
            "                       </Style>\n" +
            "			<name>" + this.nameField + "</name>\n" +
            "			<description>" + this.descriptionField + "</description>\n" +
            "			<ExtendedData>" + this.extendedData + "</ExtendedData>\n" +
            "			<MultiGeometry>\n";

    this.PLACEMARK_END = "" +
            "			</MultiGeometry>\n" +
            "		</Placemark>\n";

    this.DEFAULT_EXDAT = "<Data name='sid'><value>#ID#</value></Data><Data name='shapeType'><value>#SHAPETYPE#</value></Data><Data name='lat'><value>#LAT#</value></Data><Data name='lon'><value>#LON#</value></Data><Data name='alt'><value>#ALT#</value></Data>";
    this.DEFAULT_BLSTY = "<!" + "[CDAT" + "A[" + "$[sid]" + "]]" + ">";

    this.renderPolygons = function(ext) {
        var polys = new java.util.ArrayList();
        ext.setMaxDistance(200000);
        ext.setFlatness(1);
        ext.setLimit(3);
        var perimeterPoints = new java.util.ArrayList();
        var it = null;
        var ait = null;
        var oit = ext.getPathIterator(null);
        if (Clazz.instanceOf(oit, armyc2.c2sd.graphics2d.PathIterator))
            it = oit;
        else if (Clazz.instanceOf(oit, sec.sun.awt.geom.AreaIterator))
            ait = oit;
        var pre = null;
        if (it !== null) {
            while (!it.isDone()) {
                var strokePoints = Clazz.newArray(6, 0);
                var type = it.currentSegment(strokePoints);
                var longitudeDegrees = strokePoints[0];
                var latitudeDegrees = strokePoints[1];
                switch (type) {
                    case 0:
                    case 1:
                        if (pre !== null) {
                            var ps = new java.util.ArrayList();
                            ps.add(new sec.geo.shape.Point(pre.getLongitude(), pre.getLatitude(), ext.getMinAltitude()));
                            ps.add(new sec.geo.shape.Point(pre.getLongitude(), pre.getLatitude(), ext.getMaxAltitude()));
                            ps.add(new sec.geo.shape.Point(longitudeDegrees, latitudeDegrees, ext.getMaxAltitude()));
                            ps.add(new sec.geo.shape.Point(longitudeDegrees, latitudeDegrees, ext.getMinAltitude()));
                            ps.add(new sec.geo.shape.Point(pre.getLongitude(), pre.getLatitude(), ext.getMinAltitude()));
                            polys.add(new sec.geo.kml.KmlPolygon(ps, ext.getAltitudeMode()));
                        }
                        pre = new sec.geo.shape.Point(longitudeDegrees, latitudeDegrees);
                        perimeterPoints.add(pre);
                }
                it.next();
            }
        } else if (ait !== null) {
            while (!ait.isDone()) {
                var strokePoints = Clazz.newArray(6, 0);
                var type = ait.currentSegment(strokePoints);
                var longitudeDegrees = strokePoints[0];
                var latitudeDegrees = strokePoints[1];
                switch (type) {
                    case 0:
                    case 1:
                        if (pre !== null) {
                            var ps = new java.util.ArrayList();
                            ps.add(new sec.geo.shape.Point(pre.getLongitude(), pre.getLatitude(), ext.getMinAltitude()));
                            ps.add(new sec.geo.shape.Point(pre.getLongitude(), pre.getLatitude(), ext.getMaxAltitude()));
                            ps.add(new sec.geo.shape.Point(longitudeDegrees, latitudeDegrees, ext.getMaxAltitude()));
                            ps.add(new sec.geo.shape.Point(longitudeDegrees, latitudeDegrees, ext.getMinAltitude()));
                            ps.add(new sec.geo.shape.Point(pre.getLongitude(), pre.getLatitude(), ext.getMinAltitude()));
                            polys.add(new sec.geo.kml.KmlPolygon(ps, ext.getAltitudeMode()));
                        }
                        pre = new sec.geo.shape.Point(longitudeDegrees, latitudeDegrees);
                        perimeterPoints.add(pre);
                }
                ait.next();
            }
        }
        if (perimeterPoints.size() > 0) {
            if (perimeterPoints.get(0).equals(perimeterPoints.get(perimeterPoints.size() - 1))) {
                polys.add(new sec.geo.kml.KmlPolygon(this.transformPoints(perimeterPoints, ext.getMinAltitude()), ext.getAltitudeMode()));
                polys.add(new sec.geo.kml.KmlPolygon(this.transformPoints(perimeterPoints, ext.getMaxAltitude()), ext.getAltitudeMode()));
            } else {
                perimeterPoints.add(perimeterPoints.get(0));
                polys.add(new sec.geo.kml.KmlPolygon(this.transformPoints(perimeterPoints, ext.getMinAltitude()), ext.getAltitudeMode()));
                polys.add(new sec.geo.kml.KmlPolygon(this.transformPoints(perimeterPoints, ext.getMaxAltitude()), ext.getAltitudeMode()));
            }
        }
        return polys;
    };
    this.getPlacemarkKml = function(ext, id, name, description, color) {
        try {
            var sb = new sec.geo.utilities.StringBuilder();
            var polys = this.renderPolygons(ext);
            sb.append(this.PLACEMARK_START);
            var placemarkIdIndex = sb.indexOf(this.placemarkidField);
            var placemarkIdLength = this.placemarkidField.length;
            if (id !== null) {
                sb.replace(placemarkIdIndex, placemarkIdIndex + placemarkIdLength, id + "_mg");
            }
            var descriptionIndex = sb.indexOf(this.descriptionField);
            var descriptionLength = this.descriptionField.length;
            if (description !== null)
                sb.replace(descriptionIndex, descriptionIndex + descriptionLength, description);
            var colorIndex = sb.indexOf(this.colorField);
            var colorLength = this.colorField.length;
            if (color !== null) {
                sb.replace(colorIndex, colorIndex + colorLength, color);
            } else
                sb.replace(colorIndex, colorIndex + colorLength, this.colorDefault);
            var lineColorIndex = sb.indexOf2(this.colorField, colorIndex + colorLength);
            if (color !== null) {
                sb.replace(lineColorIndex, lineColorIndex + colorLength, color);
            } else
                sb.replace(lineColorIndex, lineColorIndex + colorLength, this.colorDefault);
            var nameIndex = sb.indexOf(this.nameField);
            var nameLength = this.nameField.length;
            if (name !== null)
                sb.replace(nameIndex, nameIndex + nameLength, name);
            for (var j = 0; j < polys.size(); j++)
            {
                var poly = polys.get(j);
                sb.append(poly.toString());
            }
            sb.append(this.PLACEMARK_END);
            return sb.toString();
        } catch (e) {
            throw e;
        }
    };
    this.getTrackKml = function(ext, id, name, description, color) {
        try {
            var aext = this.getAExtObject(ext);
            var sb = new sec.geo.utilities.StringBuilder();
            sb.append(this.KML_START);
            var idIndex = sb.indexOf(this.idField);
            var idLength = this.idField.length;
            sb.replace(idIndex, idIndex + idLength, id);

            var elements = aext.getElements();
            var j = 0;
            for (j = 0; j < elements.size(); j++)
            {
                var route = elements.get(j);
                var aext2 = new sec.geo.shape.AExtObject(route);
                sb.append(this.getPlacemarkKml(aext2, id, name, description, color));
            }

            sb.append(this.KML_END);
            return sb.toString();
        } catch (e) {
            throw e;
        }
    };
    this.getKml = function(ext, id, name, description, color) {
        try {
            var aext = this.getAExtObject(ext);
            if (aext.getElements() !== null)
                return (this.getTrackKml(ext, id, name, description, color));

            var sb = new sec.geo.utilities.StringBuilder();
            sb.append(this.KML_START);
            var idIndex = sb.indexOf(this.idField);
            var idLength = this.idField.length;
            sb.replace(idIndex, idIndex + idLength, id);
            sb.append(this.getPlacemarkKml(aext, id, name, description, color));
            sb.append(this.KML_END);
            return sb.toString();
        } catch (e) {
            throw e;
        }
    };
    this.getAExtObject = function(obj) {
        var line = null;
        var route = null;
        var circle = null;
        var polyarc = null;
        var polygon = null;
        var orbit = null;
        var radarc = null;
        var track = null;
        var cake = null;
        var point = null;
        var ext = null;
        if (Clazz.instanceOf(obj, sec.geo.shape.Line)) {
            line = obj;
            ext = new sec.geo.shape.AExtObject(line);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Route)) {
            route = obj;
            ext = new sec.geo.shape.AExtObject(route);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Polyarc)) {
            polyarc = obj;
            ext = new sec.geo.shape.AExtObject(polyarc);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Orbit)) {
            orbit = obj;
            ext = new sec.geo.shape.AExtObject(orbit);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Polygon)) {
            polygon = obj;
            ext = new sec.geo.shape.AExtObject(polygon);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Circle)) {
            circle = obj;
            ext = new sec.geo.shape.AExtObject(circle);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Radarc)) {
            radarc = obj;
            ext = new sec.geo.shape.AExtObject(radarc);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Track)) {
            track = obj;
            ext = new sec.geo.shape.AExtObject(track);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Cake)) {
            cake = obj;
            ext = new sec.geo.shape.AExtObject(cake);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Point)) {
            point = obj;
            ext = new sec.geo.shape.AExtObject(point);
        }
        return ext;
    };
    this.getCoords = function(obj) {
        var ext = this.getAExtObject(obj);
        var polys = this.renderPolygons(ext);
        var coords = new Array(polys.size());
        var i = 0;
        for (var poly, $poly = polys.iterator(); $poly.hasNext() && ((poly = $poly.next()) || true); ) {
            coords[i] = poly.toCoordString();
            i++;
        }
        return coords;
    };
    this.transformPoints = function(points, altitudeMeters) {
        var returnPoints = new java.util.ArrayList();
        for (var j = 0; j < points.size(); j++)
        {
            var p = points.get(j);
            returnPoints.add(new sec.geo.shape.Point(p.getLongitude(), p.getLatitude(), altitudeMeters));
        }
        return returnPoints;
    };
};
<commit_msg>fix for 3d milstd symbols not having cdata tag around description and name<commit_after>var sec = sec || {};
sec.geo = sec.geo || {};
sec.geo.kml = sec.geo.kml || {};
sec.geo.kml.KmlRenderer = function()
{
    this.colorDefault = "ff003fff";
    this.descriptionField = "#DESCRIPTION#";
    this.extendedData = "#EXTENDEDDATA#";
    this.colorField = "#COLOR#";
    this.nameField = "#NAME#";
    this.idField = "#ID#";
    this.placemarkidField = "#PLACEMARKID#";
    this.KML_START = null;
    this.KML_END = "</Folder>\n";
    this.PLACEMARK_START = null;
    this.PLACEMARK_END = "\t\t\t</MultiGeometry>\n\t\t</Placemark>\n";
    this.DEFAULT_EXDAT = "<Data name='sid'><value>#ID#</value></Data><Data name='shapeType'><value>#SHAPETYPE#</value></Data><Data name='lat'><value>#LAT#</value></Data><Data name='lon'><value>#LON#</value></Data><Data name='alt'><value>#ALT#</value></Data>";
    this.DEFAULT_BLSTY = "<![CDATA[$[sid]]]>";
    this.KML_START = "<Folder id=\"" + this.idField + "\">\n";
    this.PLACEMARK_START = "\t\t<Placemark id=\"" + this.placemarkidField + "\">\n" + "                      <Style>\n" + "                          <PolyStyle>\n" + "                              <color>" + this.colorField + "</color>\n" + "                          </PolyStyle>\n" + "                          <LineStyle>\n" + "                              <color>" + this.colorField + "</color>\n" + "                          </LineStyle>\n" + "                       </Style>\n" + "			<name>" + this.nameField + "</name>\n" + "			<description>" + this.descriptionField + "</description>\n" + "			<ExtendedData>" + this.extendedData + "</ExtendedData>\n" + "			<MultiGeometry>\n";

    this.KML_START = "<Folder id=\"" + this.idField + "\">\n";
    this.KML_END = "</Folder>\n";

    this.PLACEMARK_START = "" +
            "		<Placemark id=\"" + this.placemarkidField + "\">\n" +
            "                      <Style>\n" +
            "                          <PolyStyle>\n" +
            "                              <color>" + this.colorField + "</color>\n" +
            "                          </PolyStyle>\n" +
            "                          <LineStyle>\n" +
            "                              <color>" + this.colorField + "</color>\n" +
            "                          </LineStyle>\n" +
            "                       </Style>\n" +
            "			<name>" + this.nameField + "</name>\n" +
            "			<description>" + this.descriptionField + "</description>\n" +
            "			<ExtendedData>" + this.extendedData + "</ExtendedData>\n" +
            "			<MultiGeometry>\n";

    this.PLACEMARK_END = "" +
            "			</MultiGeometry>\n" +
            "		</Placemark>\n";

    this.DEFAULT_EXDAT = "<Data name='sid'><value>#ID#</value></Data><Data name='shapeType'><value>#SHAPETYPE#</value></Data><Data name='lat'><value>#LAT#</value></Data><Data name='lon'><value>#LON#</value></Data><Data name='alt'><value>#ALT#</value></Data>";
    this.DEFAULT_BLSTY = "<!" + "[CDAT" + "A[" + "$[sid]" + "]]" + ">";

    this.renderPolygons = function(ext) {
        var polys = new java.util.ArrayList();
        ext.setMaxDistance(200000);
        ext.setFlatness(1);
        ext.setLimit(3);
        var perimeterPoints = new java.util.ArrayList();
        var it = null;
        var ait = null;
        var oit = ext.getPathIterator(null);
        if (Clazz.instanceOf(oit, armyc2.c2sd.graphics2d.PathIterator))
            it = oit;
        else if (Clazz.instanceOf(oit, sec.sun.awt.geom.AreaIterator))
            ait = oit;
        var pre = null;
        if (it !== null) {
            while (!it.isDone()) {
                var strokePoints = Clazz.newArray(6, 0);
                var type = it.currentSegment(strokePoints);
                var longitudeDegrees = strokePoints[0];
                var latitudeDegrees = strokePoints[1];
                switch (type) {
                    case 0:
                    case 1:
                        if (pre !== null) {
                            var ps = new java.util.ArrayList();
                            ps.add(new sec.geo.shape.Point(pre.getLongitude(), pre.getLatitude(), ext.getMinAltitude()));
                            ps.add(new sec.geo.shape.Point(pre.getLongitude(), pre.getLatitude(), ext.getMaxAltitude()));
                            ps.add(new sec.geo.shape.Point(longitudeDegrees, latitudeDegrees, ext.getMaxAltitude()));
                            ps.add(new sec.geo.shape.Point(longitudeDegrees, latitudeDegrees, ext.getMinAltitude()));
                            ps.add(new sec.geo.shape.Point(pre.getLongitude(), pre.getLatitude(), ext.getMinAltitude()));
                            polys.add(new sec.geo.kml.KmlPolygon(ps, ext.getAltitudeMode()));
                        }
                        pre = new sec.geo.shape.Point(longitudeDegrees, latitudeDegrees);
                        perimeterPoints.add(pre);
                }
                it.next();
            }
        } else if (ait !== null) {
            while (!ait.isDone()) {
                var strokePoints = Clazz.newArray(6, 0);
                var type = ait.currentSegment(strokePoints);
                var longitudeDegrees = strokePoints[0];
                var latitudeDegrees = strokePoints[1];
                switch (type) {
                    case 0:
                    case 1:
                        if (pre !== null) {
                            var ps = new java.util.ArrayList();
                            ps.add(new sec.geo.shape.Point(pre.getLongitude(), pre.getLatitude(), ext.getMinAltitude()));
                            ps.add(new sec.geo.shape.Point(pre.getLongitude(), pre.getLatitude(), ext.getMaxAltitude()));
                            ps.add(new sec.geo.shape.Point(longitudeDegrees, latitudeDegrees, ext.getMaxAltitude()));
                            ps.add(new sec.geo.shape.Point(longitudeDegrees, latitudeDegrees, ext.getMinAltitude()));
                            ps.add(new sec.geo.shape.Point(pre.getLongitude(), pre.getLatitude(), ext.getMinAltitude()));
                            polys.add(new sec.geo.kml.KmlPolygon(ps, ext.getAltitudeMode()));
                        }
                        pre = new sec.geo.shape.Point(longitudeDegrees, latitudeDegrees);
                        perimeterPoints.add(pre);
                }
                ait.next();
            }
        }
        if (perimeterPoints.size() > 0) {
            if (perimeterPoints.get(0).equals(perimeterPoints.get(perimeterPoints.size() - 1))) {
                polys.add(new sec.geo.kml.KmlPolygon(this.transformPoints(perimeterPoints, ext.getMinAltitude()), ext.getAltitudeMode()));
                polys.add(new sec.geo.kml.KmlPolygon(this.transformPoints(perimeterPoints, ext.getMaxAltitude()), ext.getAltitudeMode()));
            } else {
                perimeterPoints.add(perimeterPoints.get(0));
                polys.add(new sec.geo.kml.KmlPolygon(this.transformPoints(perimeterPoints, ext.getMinAltitude()), ext.getAltitudeMode()));
                polys.add(new sec.geo.kml.KmlPolygon(this.transformPoints(perimeterPoints, ext.getMaxAltitude()), ext.getAltitudeMode()));
            }
        }
        return polys;
    };
    this.getPlacemarkKml = function(ext, id, name, description, color) {
        try {
            var sb = new sec.geo.utilities.StringBuilder();
            var polys = this.renderPolygons(ext);
            sb.append(this.PLACEMARK_START);
            var placemarkIdIndex = sb.indexOf(this.placemarkidField);
            var placemarkIdLength = this.placemarkidField.length;
            if (id !== null) {
                sb.replace(placemarkIdIndex, placemarkIdIndex + placemarkIdLength, id + "_mg");
            }
            var descriptionIndex = sb.indexOf(this.descriptionField);
            var descriptionLength = this.descriptionField.length;
            if (description !== null)
                sb.replace(descriptionIndex, descriptionIndex + descriptionLength, "<![CDATA[" + description + "]]>");
            var colorIndex = sb.indexOf(this.colorField);
            var colorLength = this.colorField.length;
            if (color !== null) {
                sb.replace(colorIndex, colorIndex + colorLength, color);
            } else
                sb.replace(colorIndex, colorIndex + colorLength, this.colorDefault);
            var lineColorIndex = sb.indexOf2(this.colorField, colorIndex + colorLength);
            if (color !== null) {
                sb.replace(lineColorIndex, lineColorIndex + colorLength, color);
            } else
                sb.replace(lineColorIndex, lineColorIndex + colorLength, this.colorDefault);
            var nameIndex = sb.indexOf(this.nameField);
            var nameLength = this.nameField.length;
            if (name !== null)
                sb.replace(nameIndex, nameIndex + nameLength, "<![CDATA[" + name + "]]>");
            for (var j = 0; j < polys.size(); j++)
            {
                var poly = polys.get(j);
                sb.append(poly.toString());
            }
            sb.append(this.PLACEMARK_END);
            return sb.toString();
        } catch (e) {
            throw e;
        }
    };
    this.getTrackKml = function(ext, id, name, description, color) {
        try {
            var aext = this.getAExtObject(ext);
            var sb = new sec.geo.utilities.StringBuilder();
            sb.append(this.KML_START);
            var idIndex = sb.indexOf(this.idField);
            var idLength = this.idField.length;
            sb.replace(idIndex, idIndex + idLength, id);

            var elements = aext.getElements();
            var j = 0;
            for (j = 0; j < elements.size(); j++)
            {
                var route = elements.get(j);
                var aext2 = new sec.geo.shape.AExtObject(route);
                sb.append(this.getPlacemarkKml(aext2, id, name, description, color));
            }

            sb.append(this.KML_END);
            return sb.toString();
        } catch (e) {
            throw e;
        }
    };
    this.getKml = function(ext, id, name, description, color) {
        try {
            var aext = this.getAExtObject(ext);
            if (aext.getElements() !== null)
                return (this.getTrackKml(ext, id, name, description, color));

            var sb = new sec.geo.utilities.StringBuilder();
            sb.append(this.KML_START);
            var idIndex = sb.indexOf(this.idField);
            var idLength = this.idField.length;
            sb.replace(idIndex, idIndex + idLength, id);
            sb.append(this.getPlacemarkKml(aext, id, name, description, color));
            sb.append(this.KML_END);
            return sb.toString();
        } catch (e) {
            throw e;
        }
    };
    this.getAExtObject = function(obj) {
        var line = null;
        var route = null;
        var circle = null;
        var polyarc = null;
        var polygon = null;
        var orbit = null;
        var radarc = null;
        var track = null;
        var cake = null;
        var point = null;
        var ext = null;
        if (Clazz.instanceOf(obj, sec.geo.shape.Line)) {
            line = obj;
            ext = new sec.geo.shape.AExtObject(line);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Route)) {
            route = obj;
            ext = new sec.geo.shape.AExtObject(route);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Polyarc)) {
            polyarc = obj;
            ext = new sec.geo.shape.AExtObject(polyarc);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Orbit)) {
            orbit = obj;
            ext = new sec.geo.shape.AExtObject(orbit);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Polygon)) {
            polygon = obj;
            ext = new sec.geo.shape.AExtObject(polygon);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Circle)) {
            circle = obj;
            ext = new sec.geo.shape.AExtObject(circle);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Radarc)) {
            radarc = obj;
            ext = new sec.geo.shape.AExtObject(radarc);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Track)) {
            track = obj;
            ext = new sec.geo.shape.AExtObject(track);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Cake)) {
            cake = obj;
            ext = new sec.geo.shape.AExtObject(cake);
        } else if (Clazz.instanceOf(obj, sec.geo.shape.Point)) {
            point = obj;
            ext = new sec.geo.shape.AExtObject(point);
        }
        return ext;
    };
    this.getCoords = function(obj) {
        var ext = this.getAExtObject(obj);
        var polys = this.renderPolygons(ext);
        var coords = new Array(polys.size());
        var i = 0;
        for (var poly, $poly = polys.iterator(); $poly.hasNext() && ((poly = $poly.next()) || true); ) {
            coords[i] = poly.toCoordString();
            i++;
        }
        return coords;
    };
    this.transformPoints = function(points, altitudeMeters) {
        var returnPoints = new java.util.ArrayList();
        for (var j = 0; j < points.size(); j++)
        {
            var p = points.get(j);
            returnPoints.add(new sec.geo.shape.Point(p.getLongitude(), p.getLatitude(), altitudeMeters));
        }
        return returnPoints;
    };
};
<|endoftext|>


<commit_before>
/**
 * UserJS shim
 * http://www.opera.com/docs/userjs/specs
 */

EventTarget.mixin( Opera.prototype );

Opera.prototype.defineMagicVariable = function(name, getter, setter) {

  if((!getter || Object.prototype.toString.call(getter) !== "[object Function]") ||
        (!setter || Object.prototype.toString.call(setter) !== "[object Function]")) {
    return;
  }

  var magicScriptEl = document.createElement('script');
  magicScriptEl.setAttribute('type', 'text/javascript');

  if (getter && Object.prototype.toString.call(getter) === "[object Function]") {
    magicScriptEl.textContent += "window.__defineGetter__('" + name + "', " + getter.toString() + ");\n";
  }

  if (setter && Object.prototype.toString.call(setter) === "[object Function]") {
    magicScriptEl.textContent += "window.__defineSetter__('" + name + "', " + setter.toString() + ");\n";
  }

  document.getElementsByTagName('head')[0].appendChild( magicScriptEl );
  document.getElementsByTagName('head')[0].removeChild( magicScriptEl );

};

Opera.prototype.defineMagicFunction = function(name, implementation) {

  if(!implementation || Object.prototype.toString.call(implementation) !== "[object Function]") {
    return;
  }

  var magicScriptEl = document.createElement('script');
  magicScriptEl.setAttribute('type', 'text/javascript');

  magicScriptEl.textContent = "var " + name + " = " + implementation.toString() + ";";

  document.getElementsByTagName('head')[0].appendChild( magicScriptEl );
  document.getElementsByTagName('head')[0].removeChild( magicScriptEl );

};

Opera.prototype.addEventListener = function(name, fn, useCapture) {
  // TODO Implement http://www.opera.com/docs/userjs/specs/#evlistener
  // ... this.on(name, function)
};

Opera.prototype.removeEventListener = function(name, fn, useCapture) {
  // TODO Implement http://www.opera.com/docs/userjs/specs/#evlistener
  // ... this.off(name, function)
};

// Same backend implementation as widget.preferences
Opera.prototype.__defineGetter__('scriptStorage', function() {
  return widget.preferences;
});

Opera.prototype.setOverrideHistoryNavigationMode = function(mode) {
  // NOT IMPLEMENTED
};

Opera.prototype.__defineGetter__('getOverrideHistoryNavigationMode', function() {
  return "automatic"; // default
});
<commit_msg>align with the way the old implementations handle undefined and null passed to defineMagicVariable (silent fail on undefined, accept null)<commit_after>
/**
 * UserJS shim
 * http://www.opera.com/docs/userjs/specs
 */

EventTarget.mixin( Opera.prototype );

Opera.prototype.defineMagicVariable = function(name, getter, setter) {
  if( getter === undefined || setter === undefined ){
    return;
  }
  var allowedStringifications = {"[object Function]":1, "[object Null]":1};
  if( ! ( ( Object.prototype.toString.call(getter) in allowedStringifications ) &&
        ( Object.prototype.toString.call(setter) in allowedStringifications )) {
    return;
  }

  var magicScriptEl = document.createElement('script');
  magicScriptEl.setAttribute('type', 'text/javascript');

  if (getter && Object.prototype.toString.call(getter) === "[object Function]") {
    magicScriptEl.textContent += "window.__defineGetter__('" + name + "', " + getter.toString() + ");\n";
  }

  if (setter && Object.prototype.toString.call(setter) === "[object Function]") {
    magicScriptEl.textContent += "window.__defineSetter__('" + name + "', " + setter.toString() + ");\n";
  }

  document.getElementsByTagName('head')[0].appendChild( magicScriptEl );
  document.getElementsByTagName('head')[0].removeChild( magicScriptEl );

};

Opera.prototype.defineMagicFunction = function(name, implementation) {

  if(!implementation || Object.prototype.toString.call(implementation) !== "[object Function]") {
    return;
  }

  var magicScriptEl = document.createElement('script');
  magicScriptEl.setAttribute('type', 'text/javascript');

  magicScriptEl.textContent = "var " + name + " = " + implementation.toString() + ";";

  document.getElementsByTagName('head')[0].appendChild( magicScriptEl );
  document.getElementsByTagName('head')[0].removeChild( magicScriptEl );

};

Opera.prototype.addEventListener = function(name, fn, useCapture) {
  // TODO Implement http://www.opera.com/docs/userjs/specs/#evlistener
  // ... this.on(name, function)
};

Opera.prototype.removeEventListener = function(name, fn, useCapture) {
  // TODO Implement http://www.opera.com/docs/userjs/specs/#evlistener
  // ... this.off(name, function)
};

// Same backend implementation as widget.preferences
Opera.prototype.__defineGetter__('scriptStorage', function() {
  return widget.preferences;
});

Opera.prototype.setOverrideHistoryNavigationMode = function(mode) {
  // NOT IMPLEMENTED
};

Opera.prototype.__defineGetter__('getOverrideHistoryNavigationMode', function() {
  return "automatic"; // default
});
<|endoftext|>


<commit_before>import {Pos, style} from "../model"

export function addInputRules(pm, rules) {
  if (!pm.mod.interpretInput)
    pm.mod.interpretInput = new InputRules(pm)
  pm.mod.interpretInput.addRules(rules)
}

export function removeInputRule(pm, rules) {
  let ii = pm.mod.interpretInput
  if (!ii) return
  ii.removeRules(rules)
  if (ii.rules.length == 0) {
    ii.unregister()
    pm.mod.interpretInput = null
  }
}

export class Rule {
  constructor(lastChar, match, handler) {
    this.lastChar = lastChar
    this.match = match
    this.handler = handler
  }
}

class InputRules {
  constructor(pm) {
    this.pm = pm
    this.rules = []
    this.cancelVersion = null

    pm.on("selectionChange", this.onSelChange = () => this.cancelVersion = null)
    pm.on("textInput", this.onTextInput = this.onTextInput.bind(this))
    pm.extendCommand("delBackward", "high", this.delBackward = this.delBackward.bind(this))
  }

  unregister() {
    this.pm.off("selectionChange", this.onSelChange)
    this.pm.off("textInput", this.onTextInput)
    this.pm.unextendCommand("delBackward", "high", this.delBackward)
  }

  addRules(rules) {
    this.rules = this.rules.concat(rules)
  }

  removeRules(rules) {
    for (let i = 0; i < rules.length; i++) {
      let found = this.rules.indexOf(rules[i])
      if (found > -1) this.rules.splice(found, 1)
    }
  }

  onTextInput(text) {
    let pos = this.pm.selection.head

    let textBefore, isCode
    let lastCh = text[text.length - 1]

    for (let i = 0; i < this.rules.length; i++) {
      let rule = this.rules[i], match
      if (rule.lastChar && rule.lastChar != lastCh) continue
      if (textBefore == null) {
        ;({textBefore, isCode} = getContext(this.pm.doc, pos))
        if (isCode) return
      }
      if (match = rule.match.exec(textBefore)) {
        let startVersion = this.pm.history.getVersion()
        if (typeof rule.handler == "string") {
          let offset = pos.offset - (match[1] || match[0]).length
          let start = new Pos(pos.path, offset)
          // FIXME this overwrites the style of the original text
          this.pm.apply(this.pm.tr.delete(start, pos).insertText(start, rule.handler))
        } else {
          rule.handler(this.pm, match, pos)
        }
        this.cancelVersion = startVersion
        return
      }
    }
  }

  delBackward() {
    if (this.cancelVersion) {
      this.pm.history.backToVersion(this.cancelVersion)
      this.cancelVersion = null
    } else {
      return false
    }
  }
}

function getContext(doc, pos) {
  let parent = doc.path(pos.path)
  let isPlain = parent.type.plainText
  let textBefore = ""
  for (let offset = 0, i = 0; offset < pos.offset;) {
    let child = parent.content[i++], size = child.size
    textBefore += offset + size > pos.offset ? child.text.slice(0, pos.offset - offset) : child.text
    if (offset + size >= pos.offset) {
      if (style.contains(child.styles, style.code))
        isPlain = true
      break
    }
    offset += size
  }
  return {textBefore, isPlain}
}
<commit_msg>Make sure inputrules replacements don't drop styles<commit_after>import {Pos, Span, style, spanStylesAt} from "../model"

export function addInputRules(pm, rules) {
  if (!pm.mod.interpretInput)
    pm.mod.interpretInput = new InputRules(pm)
  pm.mod.interpretInput.addRules(rules)
}

export function removeInputRule(pm, rules) {
  let ii = pm.mod.interpretInput
  if (!ii) return
  ii.removeRules(rules)
  if (ii.rules.length == 0) {
    ii.unregister()
    pm.mod.interpretInput = null
  }
}

export class Rule {
  constructor(lastChar, match, handler) {
    this.lastChar = lastChar
    this.match = match
    this.handler = handler
  }
}

class InputRules {
  constructor(pm) {
    this.pm = pm
    this.rules = []
    this.cancelVersion = null

    pm.on("selectionChange", this.onSelChange = () => this.cancelVersion = null)
    pm.on("textInput", this.onTextInput = this.onTextInput.bind(this))
    pm.extendCommand("delBackward", "high", this.delBackward = this.delBackward.bind(this))
  }

  unregister() {
    this.pm.off("selectionChange", this.onSelChange)
    this.pm.off("textInput", this.onTextInput)
    this.pm.unextendCommand("delBackward", "high", this.delBackward)
  }

  addRules(rules) {
    this.rules = this.rules.concat(rules)
  }

  removeRules(rules) {
    for (let i = 0; i < rules.length; i++) {
      let found = this.rules.indexOf(rules[i])
      if (found > -1) this.rules.splice(found, 1)
    }
  }

  onTextInput(text) {
    let pos = this.pm.selection.head

    let textBefore, isCode
    let lastCh = text[text.length - 1]

    for (let i = 0; i < this.rules.length; i++) {
      let rule = this.rules[i], match
      if (rule.lastChar && rule.lastChar != lastCh) continue
      if (textBefore == null) {
        ;({textBefore, isCode} = getContext(this.pm.doc, pos))
        if (isCode) return
      }
      if (match = rule.match.exec(textBefore)) {
        let startVersion = this.pm.history.getVersion()
        if (typeof rule.handler == "string") {
          let offset = pos.offset - (match[1] || match[0]).length
          let start = new Pos(pos.path, offset)
          let styles = spanStylesAt(this.pm.doc, pos)
          this.pm.apply(this.pm.tr.delete(start, pos).insert(start, Span.text(rule.handler, styles)))
        } else {
          rule.handler(this.pm, match, pos)
        }
        this.cancelVersion = startVersion
        return
      }
    }
  }

  delBackward() {
    if (this.cancelVersion) {
      this.pm.history.backToVersion(this.cancelVersion)
      this.cancelVersion = null
    } else {
      return false
    }
  }
}

function getContext(doc, pos) {
  let parent = doc.path(pos.path)
  let isPlain = parent.type.plainText
  let textBefore = ""
  for (let offset = 0, i = 0; offset < pos.offset;) {
    let child = parent.content[i++], size = child.size
    textBefore += offset + size > pos.offset ? child.text.slice(0, pos.offset - offset) : child.text
    if (offset + size >= pos.offset) {
      if (style.contains(child.styles, style.code))
        isPlain = true
      break
    }
    offset += size
  }
  return {textBefore, isPlain}
}
<|endoftext|>


<commit_before>
import { getPrebidPbjs } from './getPrebidPbjs'

// See: http://prebid.org/dev-docs/examples/basic-example.html
export default function () {
  // Prebid config section START
  // Make sure this is inserted before your GPT tag.
  const prebidTimeoutMs = 800

  // Note: brealtime is automatically aliased by the
  // AppNexus bid adapter.
  const adUnits = [{
    code: 'div-gpt-ad-1464385742501-0',
    sizes: [[300, 250]],
    bids: [
      {
        bidder: 'sonobi',
        params: {
          dom_id: 'div-gpt-ad-1464385742501-0',
          ad_unit: '/43865596/HBTR'
        }
      },
      {
        bidder: 'pulsepoint',
        params: {
          cf: '300X250',
          cp: '560174',
          ct: '460982'
        }
      },
      {
        bidder: 'aol',
        params: {
          network: '10559.1',
          placement: '4117692',
          alias: 'desktop_newtab_300x250',
          sizeId: '170'
        }
      },
      {
        bidder: 'sovrn',
        params: {
          tagid: '438916'
        }
      },
      {
        bidder: 'openx',
        params: {
          unit: '43865596',
          delDomain: 'tabforacause-d.openx.net'
        }
      },
      {
        bidder: 'brealtime',
        params: {
          placementId: '10955690'
        }
      }
    ]
  },
  {
    code: 'div-gpt-ad-1464385677836-0',
    sizes: [[728, 90]],
    bids: [
      {
        bidder: 'sonobi',
        params: {
          dom_id: 'div-gpt-ad-1464385677836-0',
          ad_unit: '/43865596/HBTL'
        }
      },
      {
        bidder: 'pulsepoint',
        params: {
          cf: '728X90',
          cp: '560174',
          ct: '460981'
        }
      },
      {
        bidder: 'aol',
        params: {
          network: '10559.1',
          placement: '4117691',
          alias: 'desktop_newtab_728x90',
          sizeId: '225'
        }
      },
      {
        bidder: 'sovrn',
        params: {
          tagid: '438918'
        }
      },
      {
        bidder: 'openx',
        params: {
          unit: '43865596',
          delDomain: 'tabforacause-d.openx.net'
        }
      },
      {
        bidder: 'brealtime',
        params: {
          placementId: '10955287'
        }
      }
    ]
  }]
  // Prebid config section END

  const googletag = window.googletag || {}
  googletag.cmd = googletag.cmd || []
  googletag.cmd.push(() => {
    googletag.pubads().disableInitialLoad()
  })

  const pbjs = getPrebidPbjs()

  pbjs.que.push(() => {
    pbjs.addAdUnits(adUnits)

    pbjs.bidderSettings = {
      aol: {
        // AOL sends gross CPM.
        bidCpmAdjustment: function (bidCpm) {
          return bidCpm * 0.80
        }
      }
    }

    pbjs.requestBids({
      bidsBackHandler: sendAdserverRequest
    })
  })

  function sendAdserverRequest () {
    if (pbjs.adserverRequestSent) {
      return
    }
    pbjs.adserverRequestSent = true
    googletag.cmd.push(() => {
      pbjs.que.push(() => {
        pbjs.setTargetingForGPTAsync()
        googletag.pubads().refresh()
      })
    })
  }

  setTimeout(() => {
    sendAdserverRequest()
  }, prebidTimeoutMs)
}
<commit_msg>Change OpenX ad unit ID.<commit_after>
import { getPrebidPbjs } from './getPrebidPbjs'

// See: http://prebid.org/dev-docs/examples/basic-example.html
export default function () {
  // Prebid config section START
  // Make sure this is inserted before your GPT tag.
  const prebidTimeoutMs = 800

  // Note: brealtime is automatically aliased by the
  // AppNexus bid adapter.
  const adUnits = [{
    code: 'div-gpt-ad-1464385742501-0',
    sizes: [[300, 250]],
    bids: [
      {
        bidder: 'sonobi',
        params: {
          dom_id: 'div-gpt-ad-1464385742501-0',
          ad_unit: '/43865596/HBTR'
        }
      },
      {
        bidder: 'pulsepoint',
        params: {
          cf: '300X250',
          cp: '560174',
          ct: '460982'
        }
      },
      {
        bidder: 'aol',
        params: {
          network: '10559.1',
          placement: '4117692',
          alias: 'desktop_newtab_300x250',
          sizeId: '170'
        }
      },
      {
        bidder: 'sovrn',
        params: {
          tagid: '438916'
        }
      },
      {
        bidder: 'openx',
        params: {
          unit: '538658529',
          delDomain: 'tabforacause-d.openx.net'
        }
      },
      {
        bidder: 'brealtime',
        params: {
          placementId: '10955690'
        }
      }
    ]
  },
  {
    code: 'div-gpt-ad-1464385677836-0',
    sizes: [[728, 90]],
    bids: [
      {
        bidder: 'sonobi',
        params: {
          dom_id: 'div-gpt-ad-1464385677836-0',
          ad_unit: '/43865596/HBTL'
        }
      },
      {
        bidder: 'pulsepoint',
        params: {
          cf: '728X90',
          cp: '560174',
          ct: '460981'
        }
      },
      {
        bidder: 'aol',
        params: {
          network: '10559.1',
          placement: '4117691',
          alias: 'desktop_newtab_728x90',
          sizeId: '225'
        }
      },
      {
        bidder: 'sovrn',
        params: {
          tagid: '438918'
        }
      },
      {
        bidder: 'openx',
        params: {
          unit: '538658529',
          delDomain: 'tabforacause-d.openx.net'
        }
      },
      {
        bidder: 'brealtime',
        params: {
          placementId: '10955287'
        }
      }
    ]
  }]
  // Prebid config section END

  const googletag = window.googletag || {}
  googletag.cmd = googletag.cmd || []
  googletag.cmd.push(() => {
    googletag.pubads().disableInitialLoad()
  })

  const pbjs = getPrebidPbjs()

  pbjs.que.push(() => {
    pbjs.addAdUnits(adUnits)

    pbjs.bidderSettings = {
      aol: {
        // AOL sends gross CPM.
        bidCpmAdjustment: function (bidCpm) {
          return bidCpm * 0.80
        }
      }
    }

    pbjs.requestBids({
      bidsBackHandler: sendAdserverRequest
    })
  })

  function sendAdserverRequest () {
    if (pbjs.adserverRequestSent) {
      return
    }
    pbjs.adserverRequestSent = true
    googletag.cmd.push(() => {
      pbjs.que.push(() => {
        pbjs.setTargetingForGPTAsync()
        googletag.pubads().refresh()
      })
    })
  }

  setTimeout(() => {
    sendAdserverRequest()
  }, prebidTimeoutMs)
}
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import Modal from 'react-modal';
import { Tab, Tabs, TabList, TabPanel } from '../../src/main';

Modal.setAppElement(document.getElementById('example'));
Modal.injectCSS();

const App = React.createClass({
  getInitialState() {
    return {
      isModalOpen: false,
      selectedIndex: -1,
      tabs: [
        { label: 'Foo', content: 'This is foo' },
        { label: 'Bar', content: 'This is bar' },
        { label: 'Baz', content: 'This is baz' },
        { label: 'Zap', content: 'This is zap' },
      ],
    };
  },

  render() {
    return (

          <button onClick={this.openModal}>+ Add</button>

        <Tabs selectedIndex={this.state.selectedIndex}>
          <TabList>
            {this.state.tabs.map((tab, i) => {
              return (
                <Tab key={i}>
                  {tab.label} ✕
                </Tab>
              );
            })}
          </TabList>
          {this.state.tabs.map((tab, i) => {
            return <TabPanel key={i}>{tab.content}</TabPanel>;
          })}
        </Tabs>
        <Modal
          isOpen={this.state.isModalOpen}
          onRequestClose={this.closeModal}
          style={{ width: 400, height: 350, margin: '0 auto' }}
        >

Add a Tab

          Label:

          <input id="label" type="text" ref="label" />

          Content:

          <textarea id="content" ref="content" rows="10" cols="50"></textarea>

          <button onClick={this.addTab}>OK</button>{' '}
          <button onClick={this.closeModal}>Cancel</button>
        </Modal>

    );
  },

  openModal() {
    this.setState({
      isModalOpen: true,
    });
  },

  closeModal() {
    this.setState({
      isModalOpen: false,
    });
  },

  addTab() {
    const label = this.refs.label.value;
    const content = this.refs.content.value;

    this.state.tabs.push({
      label: label,
      content: content,
    });
    this.setState({
      selectedIndex: this.state.tabs.length - 1,
    });
    this.closeModal();
  },

  removeTab(index) {
    this.state.tabs.splice(index, 1);
    this.forceUpdate();
  },
});

ReactDOM.render(<App />, document.getElementById('example'));
<commit_msg>example: Not mutate state and correctly handle selectedIndex [skip ci]<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import Modal from 'react-modal';
import { Tab, Tabs, TabList, TabPanel } from '../../src/main';

Modal.setAppElement(document.getElementById('example'));

const App = React.createClass({
  getInitialState() {
    return {
      isModalOpen: false,
      selectedIndex: -1,
      tabs: [
        { label: 'Foo', content: 'This is foo' },
        { label: 'Bar', content: 'This is bar' },
        { label: 'Baz', content: 'This is baz' },
        { label: 'Zap', content: 'This is zap' },
      ],
    };
  },

  openModal() {
    this.setState({
      isModalOpen: true,
    });
  },

  closeModal() {
    this.setState({
      isModalOpen: false,
    });
  },

  addTab() {
    const label = this.refs.label.value;
    const content = this.refs.content.value;

    this.setState({
      tabs: [
        ...this.state.tabs,
        { label, content },
      ],
      selectedIndex: this.state.tabs.length,
    });
    this.closeModal();
  },

  removeTab(index) {
    this.setState({
      tabs: this.state.tabs.filter((tab, i) => i !== index),
      selectedIndex: this.state.selectedIndex - 1,
    });
  },

  render() {
    return (

          <button onClick={this.openModal}>+ Add</button>

        <Tabs
          selectedIndex={this.state.selectedIndex}
          onSelect={selectedIndex => this.setState({ selectedIndex })}
        >
          <TabList>
            {this.state.tabs.map((tab, i) => (
              <Tab key={i}>
                {tab.label}  this.removeTab(i)}>✕
              </Tab>
            ))}
          </TabList>
          {this.state.tabs.map((tab, i) => <TabPanel key={i}>{tab.content}</TabPanel>)}
        </Tabs>
        <Modal
          isOpen={this.state.isModalOpen}
          onRequestClose={this.closeModal}
          style={{ width: 400, height: 350, margin: '0 auto' }}
        >

Add a Tab

          Label:

          <input id="label" type="text" ref="label" />

          Content:

          <textarea id="content" ref="content" rows="10" cols="50" />

          <button onClick={this.addTab}>OK</button>{' '}
          <button onClick={this.closeModal}>Cancel</button>
        </Modal>

    );
  },
});

ReactDOM.render(<App />, document.getElementById('example'));
<|endoftext|>


<commit_before>
var button = new GUId3.Button()
button.cssClass('example5')
button.width(100).height(50)
button.labelOn('zomgon').labelOff('zomgoff')
button.callback(function(v){
  if(v){
    d3.select('div#example5').style('background-color', '#406573')
  } else {
    d3.select('div#example5').style('background-color', 'black')
  }
})

// create the container, or select one
var container = d3.select('div#example5')
  .append('svg').attr('width', 500).attr('height', 300)

// create the button
button.create(container.append('g')
  .attr('transform','translate(10,10)'))
button.setValue(true)

var msg_center = d3.select('div#example5').append('div').attr('id','msg_center').style('color', 'green')

console.log(msg_center)
<commit_msg>fixes #25<commit_after>
var button = new GUId3.Button()
button.cssClass('example5')
button.width(100).height(50)
button.labelOn('zomgon').labelOff('zomgoff')
button.callback(function(v){
  if(v){
    d3.select('div#example5').style('background-color', '#406573')
  } else {
    d3.select('div#example5').style('background-color', 'black')
  }
})

// create the container, or select one
var container = d3.select('div#example5')
  .append('svg').attr('width', 500).attr('height', 300)

// create the button
button.create(container.append('g')
  .attr('transform','translate(10,10)'))
button.setValue(true)
<|endoftext|>


<commit_before>import { registry } from './registry.js';
import { isString } from './typeof.js';

function isNew(node) {
    try {
        return !isString(node.outerHTML);
    } catch (ex) {
        return true;
    }
}

export function Polyfill(Original) {
    const Modified = function() {
        if (this.constructor) {
            if (!isNew(this)) {
                return this;
            }
            let desc = registry.get(this.is);
            let config = desc.config;
            // Find the tagname of the constructor and create a new element with it
            let element = document.createElement(
                config.extends ? config.extends : this.is
            );
            if (config.extends) {
                element.setAttribute('is', this.is);
            }
            element.__proto__ = desc.Ctr.prototype;
            return element;
        }
        return null;
    };
    Modified.prototype = Object.create(Original.prototype, {
        constructor: {
            value: self[name],
            configurable: true,
            writable: true,
        },
    });
    return Modified;
}
<commit_msg>fix: crossbrowser shim for native elements<commit_after>import { registry } from './registry.js';
import { isString } from './typeof.js';

function isNew(node) {
    try {
        return !isString(node.outerHTML);
    } catch (ex) {
        return true;
    }
}

export function Polyfill(Original) {
    function Modified() {
        if (this.constructor) {
            if (!isNew(this)) {
                return this;
            }
            let desc = registry.get(this.is);
            let config = desc.config;
            // Find the tagname of the constructor and create a new element with it
            let element;
            if (registry.native) {
                element = Reflect.construct(
                    Original,
                    [],
                    this.constructor
                );
            } else {
                element = document.createElement(
                    config.extends ? config.extends : this.is
                );
            }
            element.__proto__ = desc.Ctr.prototype;
            if (config.extends) {
                element.setAttribute('is', this.is);
            }
            return element;
        }
        return null;
    }
    Modified.prototype = Object.create(Original.prototype, {
        constructor: {
            value: Modified,
            configurable: true,
            writable: true,
        },
    });
    return Modified;
}
<|endoftext|>